├── .devcontainer ├── advanced │ └── devcontainer.json └── devcontainer.json ├── .github └── workflows │ ├── deploy.yml │ └── mybinder.yml ├── .gitignore ├── 00-IntroCourse ├── CourseIntroAndRules.ipynb └── img │ └── Core-programming.jpg ├── 01-IntroCPP ├── CPP-FastPacedIntro.ipynb ├── IntroProgrammingCourse.ipynb └── Resources.ipynb ├── 02-derivatives └── NumericalDifferentiation.ipynb ├── 03-integration └── NumericalIntegration_Basics.ipynb ├── 04-vector-containers └── ModernArrays.ipynb ├── 05-matrixI ├── 2D-matrices-to-1D-arrays.ipynb └── fig │ ├── 1d-2d-mapping.png │ ├── 2d-array-memory.png │ └── 2d-array.png ├── 06-ArrayComputing └── ArrayComputing-Valarray.ipynb ├── 07-LinearAlgebra ├── LinearAlgebraEigen.ipynb └── fig │ ├── linear-example-01.pdf │ ├── linear-example-01.png │ ├── linear-example-03.pdf │ ├── linear-example-03.png │ ├── linear-example-04-T-B.pdf │ ├── linear-example-04-T-B.png │ ├── linear-example-04-T.pdf │ ├── linear-example-04-T.png │ ├── problem-05.png │ ├── problem-06.png │ └── problem-08.png ├── 08-ODE-IVP └── InitialValueProblem.ipynb ├── 09-ODE-IVP-OOP-MolecularDynamics ├── IntroMolecularDynamics.ipynb └── fig │ └── sfml.png ├── 10-RandomSystems ├── RandomNumbers.ipynb ├── RandomNumbersInSimulations.ipynb ├── fig-RandomNumbers │ ├── bad-lcg.png │ ├── ellipse-bad.png │ ├── ellipse-good.png │ ├── good-lcg.png │ └── triangle.png └── fig-RandomSimulations │ ├── needle.png │ └── neutron.png ├── 11-IntroPython ├── 01-IntroProgrammingPython.ipynb ├── 02-IntroProgrammingPython-DataStructs.ipynb ├── 03-matplotlib-intro.ipynb ├── 04-numpy-basic-reduced.ipynb ├── 05-Scipy.ipynb └── fig │ ├── chelsea-zoom-green.jpg │ ├── kitty-bad-gray.jpg │ ├── kitty-blue.jpg │ ├── kitty-good-gray.jpg │ ├── kitty.jpg │ ├── slicing.png │ └── subplots.png ├── A-01-Git └── VersionControlGit.ipynb ├── A-02-Containers └── Docker.ipynb ├── Dockerfile ├── Makefile ├── README.md ├── _config.yml ├── _static └── styles.css ├── _toc.yml ├── header.ipynb ├── requirements.txt └── utils ├── Makefile ├── deploy-local-push-remote.yml ├── reset_notebook_theme.sh └── setup_notebook_theme.sh /.devcontainer/advanced/devcontainer.json: -------------------------------------------------------------------------------- 1 | // For format details, see https://aka.ms/devcontainer.json. For config options, see the 2 | // README at: https://github.com/devcontainers/templates/tree/main/src/docker-existing-dockerfile 3 | { 4 | "name": "ProgCPP lectures", 5 | "build": { 6 | // Sets the run context to one level up instead of the .devcontainer folder. 7 | "context": "../..", 8 | // Update the 'dockerFile' property if you aren't using the standard 'Dockerfile' filename. 9 | "dockerfile": "../../Dockerfile" 10 | }, 11 | 12 | // Features to add to the dev container. More info: https://containers.dev/features. 13 | "features": { 14 | "ghcr.io/devcontainers-contrib/features/gdbgui:2": {} 15 | }, 16 | 17 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 18 | // "forwardPorts": [], 19 | 20 | // Uncomment the next line to run commands after the container is created. 21 | // "postCreateCommand": "cat /etc/os-release", 22 | 23 | // Configure tool-specific properties. 24 | "customizations": { 25 | "vscode": { 26 | "extensions": [ 27 | "MS-vsliveshare.vsliveshare", 28 | "ms-vscode.cpptools", 29 | "ms-python.python", 30 | "ms-toolsai.jupyter", 31 | "ms-vscode-remote.remote-containers", 32 | "ms-vscode-remote.remote-ssh", 33 | "ms-vscode-remote.vscode-remote-extensionpack", 34 | "ms-vscode.cpptools-extension-pack", 35 | "tootone.org-mode", 36 | "ms-vscode.makefile-tools" 37 | ] 38 | } 39 | }, 40 | 41 | // Uncomment to connect as an existing user other than the container default. More info: https://aka.ms/dev-containers-non-root. 42 | // "remoteUser": "devcontainer" 43 | 44 | "hostRequirements": { 45 | "cpus": 8, 46 | "memory": "8gb", 47 | "storage": "32gb" 48 | } 49 | 50 | // "postCreateCommand": "git checkout 2024-1s" 51 | } 52 | -------------------------------------------------------------------------------- /.devcontainer/devcontainer.json: -------------------------------------------------------------------------------- 1 | // For format details, see https://aka.ms/devcontainer.json. For config options, see the 2 | // README at: https://github.com/devcontainers/templates/tree/main/src/docker-existing-dockerfile 3 | { 4 | "name": "ProgCPP lectures", 5 | "build": { 6 | // Sets the run context to one level up instead of the .devcontainer folder. 7 | "context": "../", 8 | // Update the 'dockerFile' property if you aren't using the standard 'Dockerfile' filename. 9 | "dockerfile": "../Dockerfile" 10 | }, 11 | 12 | // // Features to add to the dev container. More info: https://containers.dev/features. 13 | // "features": { 14 | // "ghcr.io/devcontainers-contrib/features/gdbgui:2": {} 15 | // }, 16 | 17 | // Use 'forwardPorts' to make a list of ports inside the container available locally. 18 | // "forwardPorts": [], 19 | 20 | // Uncomment the next line to run commands after the container is created. 21 | // "postCreateCommand": "cat /etc/os-release", 22 | 23 | // Configure tool-specific properties. 24 | "customizations": { 25 | "vscode": { 26 | "extensions": [ 27 | "MS-vsliveshare.vsliveshare", 28 | "ms-vscode.cpptools", 29 | "ms-python.python", 30 | "ms-toolsai.jupyter", 31 | "ms-vscode-remote.remote-containers", 32 | "ms-vscode-remote.remote-ssh", 33 | "ms-vscode-remote.vscode-remote-extensionpack", 34 | "ms-vscode.cpptools-extension-pack", 35 | "tootone.org-mode", 36 | "ms-vscode.makefile-tools" 37 | ] 38 | } 39 | }, 40 | 41 | // Uncomment to connect as an existing user other than the container default. More info: https://aka.ms/dev-containers-non-root. 42 | // "remoteUser": "devcontainer" 43 | 44 | // REMOVE requirements to use defult values 45 | // "hostRequirements": { 46 | // "cpus": 8, 47 | // "memory": "8gb", 48 | // "storage": "32gb" 49 | // } 50 | 51 | // "postCreateCommand": "git checkout 2024-1s" 52 | } 53 | -------------------------------------------------------------------------------- /.github/workflows/deploy.yml: -------------------------------------------------------------------------------- 1 | name: deploy-book 2 | on: 3 | push: 4 | branches: 5 | - master 6 | env: 7 | BASE_URL: /${{ github.event.repository.name || 'local-test' }} 8 | concurrency: 9 | group: "pages" 10 | cancel-in-progress: false 11 | jobs: 12 | deploy-book: 13 | runs-on: ubuntu-latest 14 | permissions: 15 | pages: write 16 | id-token: write 17 | steps: 18 | - name: Checkout repository 19 | uses: actions/checkout@v3 20 | 21 | - name: Set up Python 3.11 22 | uses: actions/setup-python@v4 23 | with: 24 | python-version: 3.11 25 | 26 | - name: Install dependencies 27 | run: | 28 | pip install -r requirements.txt 29 | 30 | - name: Build the book 31 | run: | 32 | jupyter-book build . 33 | 34 | # For GitHub environment - actual deployment 35 | - name: Deploy to GitHub Pages 36 | if: ${{ !env.ACT }} 37 | uses: peaceiris/actions-gh-pages@v3.5.9 38 | with: 39 | personal_token: ${{ secrets.ACTIONS_FOR_BOOK_ACCESS_TOKEN }} 40 | publish_dir: ./_build/html 41 | publish_branch: gh-pages 42 | 43 | # For local testing - just verify the build 44 | - name: Local build verification 45 | if: ${{ env.ACT }} 46 | run: | 47 | echo "🚀 Local build verification completed!" 48 | echo "✓ Book built successfully in ./_build/html" 49 | echo "📚 Contents of build directory:" 50 | ls -la ./_build/html 51 | echo "" 52 | echo "ℹ️ Note: Running in local environment - skipping gh-pages deployment" 53 | echo " When this runs on GitHub, content will be deployed to gh-pages branch" 54 | -------------------------------------------------------------------------------- /.github/workflows/mybinder.yml: -------------------------------------------------------------------------------- 1 | name: Binder 2 | 3 | on: 4 | push: 5 | branches: 6 | - master # Trigger the workflow on push to the master branch 7 | 8 | jobs: 9 | Create-MyBinderOrg-Cache: 10 | runs-on: ubuntu-latest 11 | steps: 12 | - name: cache binder build on mybinder.org 13 | uses: jupyterhub/repo2docker-action@master 14 | with: 15 | NO_PUSH: true 16 | MYBINDERORG_TAG: ${{ github.event.ref }} # This builds the container on mybinder.org with the branch that was pushed on. 17 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | *.out* 2 | *.x* 3 | *.cpp 4 | *.py 5 | *.txt 6 | *.ipynb_checkpoints* 7 | *.virtual_documents 8 | _build/ 9 | **/*.cpp 10 | .DS_Store 11 | __pycache__ 12 | .secrets 13 | drafts 14 | gradebook.db 15 | *~ 16 | *pdf 17 | *db 18 | Dockerfile-* 19 | -------------------------------------------------------------------------------- /00-IntroCourse/CourseIntroAndRules.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "e1b67d03-0c9d-4a64-9ddb-c60ff7c3a38b", 6 | "metadata": {}, 7 | "source": [ 8 | "# Programación e Introducción a los Métodos Numéricos\n", 9 | "\n", 10 | "\n", 11 | "\n", 12 | "\n", 13 | "# Objetivo General\n", 14 | "\n", 15 | "Introducir al estudiante a las técnicas básicas de programación y su aplicación numérica\n", 16 | "usando el lenguaje C++, con aplicaciones a diversos métodos numéricos\n", 17 | "básicos: diferenciación e integración, problemas matriciales, solución\n", 18 | "de ecuaciones algebraicas, solución de ecuaciones diferenciales\n", 19 | "ordinarias, etc. \n", 20 | "\n", 21 | "Simulation: https://youtu.be/lS_qeBy3aQI?si=ECDSZHouSlh2PQLq&t=446" 22 | ] 23 | }, 24 | { 25 | "cell_type": "markdown", 26 | "id": "c0e377bc-ea67-4cee-8368-10ec7660c4b6", 27 | "metadata": {}, 28 | "source": [ 29 | "# Contenidos generales y programa tentativo\n", 30 | "## Módulo I: Fundamentos de Programación de Computadores \n", 31 | "1. **Introducción al curso y al desarrollo en c++ :** Entorno de\n", 32 | " trabajo (google collab, muestra de acceso remoto a la sala de\n", 33 | " cómputo, binder, etc). Lenguajes de programación. Compiladores,\n", 34 | " editores (emacs, vs code). Estructura básica, compilación y\n", 35 | " ejecución de un programa en c++.\n", 36 | "2. **Introducción básica a `C++`**: Función `main`. Variables y tipos\n", 37 | " (`int,\n", 38 | " float, double`). Operadores aritmeticos (`+, -, *, ++`, etc),\n", 39 | " lógicos (`&&,\n", 40 | " and, or`), de comparación (`==,!=`). Precedencia de operadores.\n", 41 | " Condicional `if` , `else` . Aplicación: números pares, divisores.\n", 42 | " Introducción a loops.\n", 43 | "3. **Funciones y modularización de archivos:** Más sobre funciones.\n", 44 | " Modularización de archivos, separando declaración, implementación, y\n", 45 | " función main. Parámetros de la línea de comandos. Aplicación: Testing\n", 46 | " de funciones con catch2.\n", 47 | " \n", 48 | "## Módulo II: Aplicaciones numéricas básicas \n", 49 | "1. **Loops y funciones**: loops clásicos (`for`, `while`, `do-while`).\n", 50 | " Loops modernos automáticos en rangos, Funciones básicas como modelo\n", 51 | " base de programación. Aplicación: Sumas de series, aproximación de\n", 52 | " número $\\pi$. Búsqueda de raíces.\n", 53 | "2. **Derivadas numéricas**: Método forward, central, y aplicación de la\n", 54 | " extrapolación de Richardson. Escritura con formato usando ofstream.\n", 55 | " Introducción a la derivación automática usando clases.\n", 56 | "3. **Cuadraturas numéricas**: Trapecio, Simpson, y Gauss. Errores matemáticos y errores numéricos.\n", 57 | "\n", 58 | "## Módulo III: Aplicaciones matriciales básicas y librerías\n", 59 | "1. **Arreglos modernos `std::vector`, `std::array`**: Arreglos\n", 60 | " modernos, heap y stack, acceso de memoria. Ejemplos con vectores\n", 61 | " matemáticos, aleatorios y normas. Introducción al deugging y a los\n", 62 | " sanitizers.\n", 63 | "2. **Matrices representadas en arreglos**: Colapso de índices.\n", 64 | " problemas matriciales y escalamiento.\n", 65 | "3. **Array computing**: Operaciones a nivel de coeficientes,\n", 66 | " `std::valarray`. Representación vectorial de las operaciones.\n", 67 | "4. **Álgebra lineal computacional**: Algoritmos, librerías como\n", 68 | " `eigen`, matrices complejas, problemas y aplicaciones. Matrices\n", 69 | " aleatorias. Problemas de valor propio.\n", 70 | " \n", 71 | "## Módulo IV: Ecuaciones differenciales de valor inicial\n", 72 | "1. **ODE y problemas de valor inicial**: Ecuaciones diferenciales\n", 73 | " ordinarias de valor inicial. Algoritmo de Euler, Runge-Kutta, etc.\n", 74 | " Órdenes de convergencia, Aplicaciones a sistemas dinámicos.\n", 75 | "2. **Introducción a la dinamica molecular**: Simulaciones de dinámica\n", 76 | " molecular, algoritmos, modularización, visualización de datos\n", 77 | " (post-processing), visualización del sistema con opengl.\n", 78 | " \n", 79 | "## Módulo V: introducción a Python\n", 80 | "1. **Programación básica en python**: Variables, selección, loops y funciones. \n", 81 | "2. **Estructuras básicas de datos**: Listas, arreglos y diccionarios. \n", 82 | "\n", 83 | "## Temas opcionales\n", 84 | "1. **(Opt) Librería estándar de algoritmos STL**. Ejemplo: Ordenamiento de\n", 85 | " datos con la librería estándar, números aleatorios, contenedores.\n", 86 | "2. **(Opt) ODE y problemas de valor de frontera**: Ecuaciones\n", 87 | " diferenciales ordinarias de valor inicial. Algoritmo de Euler,\n", 88 | " Runge-Kutta, etc. Órdenes de convergencia, Aplicaciones a sistemas\n", 89 | " dinámicos.\n", 90 | "3. **(Opt) Introducción a la solución numérica de ecuaciones\n", 91 | " diferenciales parciales:** Ecuación de Laplace y método de\n", 92 | " relajación.\n", 93 | "4. **(Opt) Números aleatorios**: Distribuciones, cálculo de integrales,\n", 94 | " métodos básicos de MonteCarlo.\n", 95 | "5. **(Opt) Errores en computación numérica:** Substracción cancelativa,\n", 96 | " round-off, precisión, etc." 97 | ] 98 | }, 99 | { 100 | "cell_type": "markdown", 101 | "id": "4a70c8f6-8af2-4d58-9a0d-b26783f8dbf4", 102 | "metadata": {}, 103 | "source": [ 104 | "# Evaluación\n", 105 | "\n", 106 | "| Item | Porcentaje | Fecha | Información adicional |\n", 107 | "|----|----|----|----|\n", 108 | "| Examen Parcial 1 | 15 | Semana 4-5 | Presencial |\n", 109 | "| Examen Parcial 2 | 20 | Semana 9-11 | Presencial |\n", 110 | "| Tareas y práctica | 40 | Cada clase | Evaluación permanente |\n", 111 | "| Proyecto Final | 25 | Última semana | Se sustenta con video, informe y código |\n", 112 | "\n", 113 | "Atención de dudas:\n", 114 | "1. **Reservas usando el calendario de google**\n", 115 | "2. **Foro en moodle: micampus.unal.edu.co**\n", 116 | "3. Email con la pregunta claramente detallada.\n", 117 | "2. Email proponiendo al menos dos horarios de reunión e indicando la pregunta\n", 118 | "\n", 119 | "## Metodología de evaluación\n", 120 | "La metodología de evaluacion es mixta, usando diferentes recursos que evalúan diferentes aspectos del aprendizaje:\n", 121 | "\n", 122 | "a) Tareas normales que se califican sobre 5.0. Estas puede ser tareas sencillas de un día para otro, o workshops en donde ustedes entregan y además revisan el trabajo de sus compañeros, y la nota final depende de la calidad de lo que entregó y de lo bien que evaluó (se castigan calificaciones demasiado buenas, demasiado malas, etc)\n", 123 | "\n", 124 | "b) Minitareas, que normalmente valen entre 1.0 a 2.0, y se van acumulando hasta convertirse en una tarea completa qu puede sumar más de 5.0 (ahí está la ayuda en bonos). Estas muchas veces se hacen en clase y al sumar más de 5.0 permiten que usted no presente alguna y aún así aspire a sacar 5.0. Adicionalmente, pueden consistir de videos de preparación de clase y otras actividades. \n", 125 | "\n", 126 | "c) Evaluaciones tipo parcial, en ambientes limitados y de tiempo limitado. Normalmente son de selección múltiple o programas que deben cumplir ciertos casos de prueba, ya sean explícitos u ocultos. \n", 127 | "\n", 128 | "d) Proyectos se busca la solución de problemas más complejos , en grupo. Allí se deben fotalecer las habilidades blandas y usar herramientas apropiadas para coordinar el trabajo en grupo. Adicionalmente, la nota final de estos trabajos en grupo depende también de una evaluación anónima que hagan sus propios compañeros sobre su contribución, de manera que si usted no trabaja, no obtendrá la misma nota que los demás aunque estén en el mismo grupo. " 129 | ] 130 | }, 131 | { 132 | "cell_type": "markdown", 133 | "id": "86a4c47a-1793-41fa-9062-5b621e11f3fe", 134 | "metadata": {}, 135 | "source": [ 136 | "# Recursos básicos del curso\n", 137 | "\n", 138 | "## Instrucciones de acceso remoto a la sala de cómputo, recursos, usb live, etc\n", 139 | "\n", 140 | "\n", 141 | "\n", 142 | "## Listas de videos:\n", 143 | "\n", 144 | "- [Programación en c++ - videos básicos](https://www.youtube.com/playlist?list=PLxbXsIEaf05oYYsYbMfB5_gTthmFfH0R1)\n", 145 | "- [2024-II](https://www.youtube.com/playlist?list=PLxbXsIEaf05rfmmfUi16B_R3unWY84xZQ)\n", 146 | "- [2024-1s](https://www.youtube.com/playlist?list=PLxbXsIEaf05pd-AyF7G-BWuIxAmIyhyAd)\n", 147 | "\n", 148 | "\n", 149 | "## Complementary tools\n", 150 | "\n", 151 | "- \n", 152 | "- ****\n", 153 | "- ****\n", 154 | "- \n", 155 | "- ****\n", 156 | "- \n", 157 | "- \n", 158 | "- \n", 159 | "- " 160 | ] 161 | }, 162 | { 163 | "cell_type": "markdown", 164 | "id": "9350a7c3-63b7-4983-a6eb-15f90eb6a1a4", 165 | "metadata": {}, 166 | "source": [ 167 | "# Bibliografía\n", 168 | "- Canale, R.P., and D. Steven C. Chapra. Numerical Methods for Engineers. McGraw-Hill Education, 2014. https://books.google.com.co/books?id=avsMnQEACAAJ.\n", 169 | "- Deitel, P., and H. Deitel. C++ How to Program. How to Program. Prentice Hall PTR, 2013. https://books.google.com.co/books?id=S9oxoAEACAAJ.\n", 170 | "- Garcia, A.L. Numerical Methods for Physics. Prentice Hall, 2000. https://books.google.com.co/books?id=MPVAAQAAIAAJ.\n", 171 | "- Langtangen, H.P. A Primer on Scientific Programming with Python. Texts in Computational Science and Engineering. Springer Berlin Heidelberg, 2016. https://books.google.com.co/books?id=nUzADAAAQBAJ.\n", 172 | "- Nunez-Iglesias, J., S.Ø. van der Walt, and H. Dashnow. Elegant SciPy: The Art of Scientific Python. O’Reilly Media, 2017. https://books.google.com.co/books?id=4tOdjgEACAAJ.\n", 173 | "- Pitt-Francis, J., and J. Whiteley. Guide to Scientific Computing in C++. Undergraduate Topics in Computer Science. Springer International Publishing, 2018. https://books.google.com.co/books?id=e1FTDwAAQBAJ.\n", 174 | "- Širca, S., and M. Horvat. Computational Methods in Physics: Compendium for Students. Graduate Texts in Physics. Springer International Publishing, 2018. https://books.google.com.co/books?id=9XhhDwAAQBAJ.\n", 175 | "- Smith, E. Introduction to the Tools of Scientific Computing. Texts in Computational Science and Engineering. Springer International Publishing, 2020. https://books.google.com.co/books?id=B5YMEAAAQBAJ.\n", 176 | "- Stroustrup, B. Programming: Principles and Practice Using C++. Pearson Education, 2014. https://books.google.com.co/books?id=We21AwAAQBAJ." 177 | ] 178 | }, 179 | { 180 | "cell_type": "code", 181 | "execution_count": null, 182 | "id": "04a49727-d4ea-41f4-924a-e37f11af18e7", 183 | "metadata": {}, 184 | "outputs": [], 185 | "source": [] 186 | } 187 | ], 188 | "metadata": { 189 | "kernelspec": { 190 | "display_name": "Python 3 (ipykernel)", 191 | "language": "python", 192 | "name": "python3" 193 | }, 194 | "language_info": { 195 | "codemirror_mode": { 196 | "name": "ipython", 197 | "version": 3 198 | }, 199 | "file_extension": ".py", 200 | "mimetype": "text/x-python", 201 | "name": "python", 202 | "nbconvert_exporter": "python", 203 | "pygments_lexer": "ipython3", 204 | "version": "3.12.5" 205 | } 206 | }, 207 | "nbformat": 4, 208 | "nbformat_minor": 5 209 | } 210 | -------------------------------------------------------------------------------- /00-IntroCourse/img/Core-programming.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/00-IntroCourse/img/Core-programming.jpg -------------------------------------------------------------------------------- /01-IntroCPP/IntroProgrammingCourse.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "1d8d7d8a", 6 | "metadata": {}, 7 | "source": [ 8 | "# Introduction to Programming and C++\n", 9 | "\n", 10 | "
\n", 11 | " \"Image\n", 12 | "
\n", 13 | "\n", 14 | "[C++](https://en.wikipedia.org/wiki/C%2B%2B?useskin=vector) is\n", 15 | "- A high level language\n", 16 | "- A powerful, battle tested language (old), with new standards every 3 years.\n", 17 | "- A multiparadigm language (we will learn only a subset)\n", 18 | "- A compiled language (using compilers like `g++` or `icc`)\n", 19 | "- Highly performant, used vastly on scientific and many other applications: amazon.com, intel, IBM, facebook, Google, Microsoft, Apple, Adobe, ...\n", 20 | "- Games written in c++: Assasins creed, Call of Duty, Mass Effect, World of Warcraft, Starcraft, Halo, Among Us, ...\n", 21 | "\n", 22 | "The main idea at the end of this course is to be able to program something like https://www.youtube.com/watch?v=lS_qeBy3aQI, where more complex systems are available https://flyover.github.io/box2d.ts/testbed/\n", 23 | "\n", 24 | "C++ allows you to really exploit your computational resources: \n", 25 | "https://computers-are-fast.github.io/\n", 26 | "\n", 27 | "Also, if you want to know more about a computer, please check https://www.youtube.com/watch?v=d86ws7mQYIg\n", 28 | "\n", 29 | "- Moore law " 30 | ] 31 | }, 32 | { 33 | "cell_type": "markdown", 34 | "id": "c805ccf6", 35 | "metadata": {}, 36 | "source": [ 37 | "
\n", 38 | " \"Image\n", 39 | "
From: \"https://global-uploads.webflow.com/5d0dc87aac109e1ffdbe379c/60c747b9e5f372c3bc2cfb12_pieT5veoNqVqJjagsCTj8_Cg1zDJTJDUF5mlKj0SaHM4MHCp2EGw6TwkBWEQEFd5qg0GAbAIBgJss6tjDvvng_Tk6gse8dRQrstEBaL9lq8BdZ54523gEQPROzireFIDMMRk20k.png\"
\n", 40 | "
\n", 41 | "\n", 42 | "
\n", 43 | " \"Image\n", 44 | "
From: \"https://educative-inc.medium.com/c-is-a-good-first-language-to-learn-646297e765ea\"
\n", 45 | "
\n", 46 | "\n", 47 | "
\n", 48 | " \"Image\n", 49 | "
From: \"https://media.springernature.com/full/springer-static/image/art%3A10.1186%2F1751-0473-7-5/MediaObjects/13029_2012_Article_73_Fig1_HTML.jpg\"
\n", 50 | "
\n", 51 | "\n", 52 | "
\n", 53 | " \"Image\n", 54 | "
From: \"https://media.springernature.com/m685/springer-static/image/art%3A10.1038%2Fs41550-020-1208-y/MediaObjects/41550_2020_1208_Fig3_HTML.png\"
\n", 55 | "
\n", 56 | "\n", 57 | "Here is an [outline](https://en.wikipedia.org/wiki/Outline_of_C%2B%2B?useskin=vector)" 58 | ] 59 | }, 60 | { 61 | "cell_type": "markdown", 62 | "id": "45fdf4b5", 63 | "metadata": {}, 64 | "source": [ 65 | "## Typical basic workflow" 66 | ] 67 | }, 68 | { 69 | "cell_type": "code", 70 | "execution_count": null, 71 | "id": "eb6bf1e5", 72 | "metadata": { 73 | "ExecuteTime": { 74 | "end_time": "2023-07-26T03:18:58.162714Z", 75 | "start_time": "2023-07-26T03:18:58.155397Z" 76 | } 77 | }, 78 | "outputs": [], 79 | "source": [ 80 | "%load_ext nb_js_diagrammers" 81 | ] 82 | }, 83 | { 84 | "cell_type": "code", 85 | "execution_count": null, 86 | "id": "87de6f3e", 87 | "metadata": { 88 | "ExecuteTime": { 89 | "end_time": "2023-07-26T03:19:12.171004Z", 90 | "start_time": "2023-07-26T03:19:12.161973Z" 91 | }, 92 | "code_folding": [] 93 | }, 94 | "outputs": [], 95 | "source": [ 96 | "%%mermaid_magic -h 500 \n", 97 | "graph TD;\n", 98 | " A[Understand the problem] --> B[Edit the code: vscode, emacs, vim, ...]\n", 99 | " B --> C[Compile your code: g++ filename.cpp]\n", 100 | " C -- Yes --> D[Execute the executable: ./a.out]\n", 101 | " C -- No --> B\n", 102 | " D -- Yes --> E[Analyze results: Plot, fit, etc. Maybe use python]\n", 103 | " D -- No --> B\n", 104 | " E -- No, or improvement --> B\n", 105 | " E -- More thinking needed --> A" 106 | ] 107 | }, 108 | { 109 | "cell_type": "markdown", 110 | "id": "c28dd301", 111 | "metadata": {}, 112 | "source": [ 113 | "0. **Understand the problem**. Think about the tasks you need as a high level version.\n", 114 | "1. **Edit** the code: vscode, emacs, vim, ...\n", 115 | "2. **Compile** your code: `g++ filename.cpp ` . In case of errors, return to step 1.\n", 116 | "3. **Execute** the executable: `./a.out` . In case of errors, return to step 1.\n", 117 | "4. **Analyze results**: Plot, fit, etc. Maybe use python. In case of errors, return to step 1\n", 118 | "\n", 119 | "The following shows the workflow for a helloworld program." 120 | ] 121 | }, 122 | { 123 | "cell_type": "markdown", 124 | "id": "07a0c5cc", 125 | "metadata": {}, 126 | "source": [ 127 | "**Step 0: Think**\n", 128 | "We want a program that prints the message \"Hello world\" to the standard output (the screen, normally). So we need a standard header like `iostream`, and use `std::cout`. Therefore our general program flow would be\n", 129 | "```bash\n", 130 | "library to print to the screen: include iostream\n", 131 | "in the main function\n", 132 | " use cout or print or println or printf to write \"Hellow world\"\n", 133 | "```\n", 134 | "\n", 135 | "**Step 1: Edit**\n", 136 | "We will edit the code now. Please use an editor and write the following code\n", 137 | "```c++\n", 138 | "// This prints a comment\n", 139 | "#include \n", 140 | "\n", 141 | "int main(void)\n", 142 | "{\n", 143 | " std::cout << \"Hello world\\n\";\n", 144 | " return 0;\n", 145 | "}\n", 146 | "```" 147 | ] 148 | }, 149 | { 150 | "cell_type": "markdown", 151 | "id": "998fb7ac", 152 | "metadata": {}, 153 | "source": [ 154 | "**Step 2: Compile**\n", 155 | "Now we will compile with the compiler `g++` (there are a [lot more](https://en.wikipedia.org/w/index.php?title=List_of_compilers&useskin=vector#C++_compilers)). In a terminal, in the same directory where the fie was saved, just run\n", 156 | "```bash\n", 157 | "g++ helloworld.cpp\n", 158 | "```\n", 159 | "You have terminals available in a local or remote linux installation, in vscode in a code space, in binder, but not in google collab. There you need to either pay to have a terminal (is not that expensive), or just run a cell prepending `!` as follows\n", 160 | "\n", 161 | "```bash\n", 162 | "!g++ helloworld.cpp\n", 163 | "```\n", 164 | "\n", 165 | "This produces the executable `a.out` (you can change the name using the compilation flag `-o name.x`), as\n", 166 | "```bash\n", 167 | "g++ helloworld.cpp -o hello.x\n", 168 | "```\n", 169 | "You can check the contents of the current dir with \n", 170 | "```bash\n", 171 | "ls\n", 172 | "```\n", 173 | "(remeber to prepend a `!` if you are using collab)" 174 | ] 175 | }, 176 | { 177 | "cell_type": "markdown", 178 | "id": "8819a225", 179 | "metadata": {}, 180 | "source": [ 181 | "**Step 3: Execute** \n", 182 | "To execute, we need to specify the path to the executable. We are going to use the symbol './', which means the current directory\n", 183 | "```bash\n", 184 | "./hello.x\n", 185 | "```\n", 186 | "(or `./a.out`)" 187 | ] 188 | }, 189 | { 190 | "cell_type": "markdown", 191 | "id": "7ac8a99c", 192 | "metadata": {}, 193 | "source": [ 194 | "Congratulation! Now you are a c++ developer ... not so fast!" 195 | ] 196 | }, 197 | { 198 | "cell_type": "markdown", 199 | "id": "9bfa3a72", 200 | "metadata": {}, 201 | "source": [ 202 | "## Understanding helloworld\n", 203 | "\n", 204 | "There are a lot of things under the hood for the simple helloworld program." 205 | ] 206 | }, 207 | { 208 | "cell_type": "markdown", 209 | "id": "8e4d5ab5", 210 | "metadata": {}, 211 | "source": [ 212 | "### Comments\n", 213 | "You can add comments, ignored by the compiler, using either `//`, for single line comments, or \n", 214 | "```c++\n", 215 | "/* \n", 216 | " large multiline \n", 217 | " comment\n", 218 | "*/\n", 219 | "```\n", 220 | "for multiline comments." 221 | ] 222 | }, 223 | { 224 | "cell_type": "markdown", 225 | "id": "60272a3a", 226 | "metadata": {}, 227 | "source": [ 228 | "### Pre-processor\n", 229 | "The line\n", 230 | "```c++\n", 231 | "#include \n", 232 | "```\n", 233 | "Tells the **pre-processor** to include the **standard** library `iostream`, which is the one in cahrge of (i)npunt and (o)utput of (stream)s. It also gives you `std::cin` to read from the standard input, `std::cerr` and `std::clog` for the standard error, and so on. There are many standard headers, and you should get familiar and use them extensively. Please see [cppreference](https://en.cppreference.com/w/) .\n", 234 | "\n", 235 | "The pre-processor allows conditional compilation, activates possible parallelism with openmp and does many more things, but for now we will keep it usage like that. Actually, it is in the path to be eliminated in favor of modules. \n", 236 | "\n", 237 | "Do not use `.h` headers. Those come from C , are not using the `std` namespace, and are a bad practice." 238 | ] 239 | }, 240 | { 241 | "cell_type": "markdown", 242 | "id": "5c1648c6", 243 | "metadata": {}, 244 | "source": [ 245 | "### The main function\n", 246 | "Good programming is based on splitting a daunting task into several smaller tasks that are isolated from each other and perform one thing well. Therefore, the concept of a *function* is of paramount importance. In c++, a function has a name, a set of arguments (parameters that it receives, like the domain, although the parameter number and type can be any), and a result type (a range) if it returns something. The typical function prototype is\n", 247 | "```c++\n", 248 | "return_type function_name(type1 par1, type2 par2);\n", 249 | "```\n", 250 | "As an example, the following is the declaration (how is called, what it receives and what it returns) for a that receives two integers and return their sum\n", 251 | "```c++\n", 252 | "int sum(int a, int b);\n", 253 | "```\n", 254 | "and this would be the implementation\n", 255 | "```c++\n", 256 | "int sum(int a, int b) {\n", 257 | " return a+b; \n", 258 | "}\n", 259 | "```\n", 260 | "For reasons that we will learn later, modularization is very important. \n", 261 | "\n", 262 | "There is a very important function, called the `main` function, which is mandatory per program (and only can be per executable) and is the one that talks to the operating system. Usually, it is expected that the main function calls other functions in the program. Some signatures of the main function are \n", 263 | "```c++\n", 264 | "int main(void)\n", 265 | "{\n", 266 | " ... \n", 267 | "}\n", 268 | "```\n", 269 | "which means that the executable does not receive any arguments, or \n", 270 | "```c++\n", 271 | "int main(int argc, char **argv)\n", 272 | "{\n", 273 | " ... \n", 274 | "}\n", 275 | "```\n", 276 | "which mean that the executable can receive arguments, like\n", 277 | "```sh\n", 278 | "./program.x 1.2 3\n", 279 | "```" 280 | ] 281 | }, 282 | { 283 | "cell_type": "markdown", 284 | "id": "b069ee80", 285 | "metadata": {}, 286 | "source": [ 287 | "### `std::cout` to print\n", 288 | "The instruction `std::cout` allows to print to the standard output. The `\\n` prints a new line. **Warning:** Do not use \n", 289 | "```c++\n", 290 | "using namespace std; // DO NOT DO THIS\n", 291 | "```\n", 292 | "it is a bad practice, frowned upon. You can use a linter or static analysis tool, like cpplint, to chech for advice and errors. " 293 | ] 294 | }, 295 | { 296 | "cell_type": "markdown", 297 | "id": "c8a2faf4", 298 | "metadata": {}, 299 | "source": [ 300 | "### Return statement\n", 301 | "The `return` statement allows to exit the function, returning something or nothing. It depends on your use case if you need it or not." 302 | ] 303 | }, 304 | { 305 | "cell_type": "markdown", 306 | "id": "758ada98", 307 | "metadata": {}, 308 | "source": [ 309 | "## Practical exercise\n", 310 | "Now please write a program that reads your name, and then prints `Hello, your-name-here` . Check if it is better to use `std::cin` or `std::getline`. Compile it and test it. " 311 | ] 312 | }, 313 | { 314 | "cell_type": "code", 315 | "execution_count": null, 316 | "id": "0b24f476", 317 | "metadata": { 318 | "ExecuteTime": { 319 | "end_time": "2023-07-25T16:55:22.637349Z", 320 | "start_time": "2023-07-25T16:55:22.635684Z" 321 | } 322 | }, 323 | "outputs": [], 324 | "source": [ 325 | "# Compilation\n" 326 | ] 327 | }, 328 | { 329 | "cell_type": "code", 330 | "execution_count": null, 331 | "id": "54852ee4", 332 | "metadata": { 333 | "ExecuteTime": { 334 | "end_time": "2023-07-25T16:55:26.706379Z", 335 | "start_time": "2023-07-25T16:55:26.704499Z" 336 | } 337 | }, 338 | "outputs": [], 339 | "source": [ 340 | "# Execution" 341 | ] 342 | }, 343 | { 344 | "cell_type": "markdown", 345 | "id": "d414d810", 346 | "metadata": {}, 347 | "source": [ 348 | "## Some useful tools \n", 349 | "As you learn more and your apps grow in complexity, you might need to use tools to easy the developer work so to focus on the analysis and results, while mantaining readability and good practices. Please also focus in this in **learning linux**, is the environment that scientist use. You can find many online resources, like http://www.ee.surrey.ac.uk/Teaching/Unix/ or https://swcarpentry.github.io/shell-novice/. For a general overview of what it means to be a modern c++ developer, see https://roadmap.sh/cpp\n", 350 | "\n", 351 | "### Good programming practices\n", 352 | "- Modularize your code\n", 353 | "- Use testing\n", 354 | "- Minimum privilige principle\n", 355 | "- A function does one thing right\n", 356 | "- Do not use `using namespace std;` , \n", 357 | "- Avoid code duplication\n", 358 | "- ..." 359 | ] 360 | }, 361 | { 362 | "cell_type": "markdown", 363 | "id": "d3801fc5", 364 | "metadata": {}, 365 | "source": [ 366 | "### IDE\n", 367 | "An IDE is not just an editor but also gives you an environment with debuggers, refactoring, etc. You might use \n", 368 | "- [Visual studio code](https://code.visualstudio.com/) . Very famous right now. Runs on electron. Can connect remotely, but cannot run in the terminal. A lot of metrics sent to servers. \n", 369 | "- [VSCodium](https://vscodium.com/) Free implementation, no telemetry. But not all plugins work.\n", 370 | "- [Emacs doom](https://github.com/doomemacs/doomemacs) or [space emacs](https://www.spacemacs.org/). Emacs distributions with many packages to make emacs a useful IDE.\n", 371 | "- [Lapce](https://lapce.dev/#downloads-all) A rust implementation which is very fast.\n", 372 | "- And much more: Sublime text, atom, Notepad++, Eclipse, Clion, Blocks , .." 373 | ] 374 | }, 375 | { 376 | "cell_type": "markdown", 377 | "id": "5d373508", 378 | "metadata": {}, 379 | "source": [ 380 | "### Sanitizers\n", 381 | "When compiling, use sanitizers to allow for runtime error detections\n", 382 | "```bash\n", 383 | "g++ -fsanitize=address,undefined,leak filename.cpp -o ...\n", 384 | "```" 385 | ] 386 | }, 387 | { 388 | "cell_type": "markdown", 389 | "id": "59ff5d5b", 390 | "metadata": {}, 391 | "source": [ 392 | "### Debuggers\n", 393 | "A programmer spent 80% of the time debugging and fixing its code, and 20% programming. To track errors, it is useful to use something more advanced than printing messages (poor's man debugger). You can use tools like:\n", 394 | "- [gdb](https://www.sourceware.org/gdb/)\n", 395 | "- [ddd](https://www.gnu.org/software/ddd/)\n", 396 | "- The debuggers included on visual studio code, emacs or the IDE you selected (they basically use gdb under the hood)\n", 397 | "- [Online debugger](https://www.onlinegdb.com/)\n", 398 | "- [Python tutor for c++](https://pythontutor.com/cpp.html#mode=edit)" 399 | ] 400 | }, 401 | { 402 | "cell_type": "markdown", 403 | "id": "0ef34453", 404 | "metadata": {}, 405 | "source": [ 406 | "### Linters\n", 407 | "Sometimes you need tools that tell some possible errors in your code without actually running it. You can use \n", 408 | "- [cpplint](https://github.com/cpplint/cpplint)\n", 409 | "- [cppcheck](https://github.com/danmar/cppcheck)\n", 410 | "- [clang static analyszer](https://clang-analyzer.llvm.org/)\n", 411 | "- [clang tidy](https://clang.llvm.org/extra/clang-tidy/)" 412 | ] 413 | }, 414 | { 415 | "cell_type": "markdown", 416 | "id": "88d934de", 417 | "metadata": {}, 418 | "source": [ 419 | "### Formatting\n", 420 | "Formatting the code is key for readability of one self and others. You can use something like [clang-format](https://clang.llvm.org/docs/ClangFormat.html) to format your ugly and unreadable code." 421 | ] 422 | }, 423 | { 424 | "cell_type": "markdown", 425 | "id": "e0638706", 426 | "metadata": {}, 427 | "source": [ 428 | "### Compilation\n", 429 | "There are several compilers that you can use, like:\n", 430 | "- [gnu gcc/g++ compilers](https://gcc.gnu.org/)\n", 431 | "- [clang](https://clang.llvm.org/)\n", 432 | "- [Intel compilers](https://www.intel.com/content/www/us/en/developer/tools/oneapi/dpc-compiler.html#gs.315ucf)\n", 433 | "- [Amd compilers](https://www.amd.com/en/developer/aocc.html)\n", 434 | "Sometimes it is useful to try several compilers to find possible bugs in the code.\n", 435 | "\n", 436 | "There are also some online alternatives, useful to test code and small projects (see also the debugging section)\n", 437 | "- [Coliru](http://coliru.stacked-crooked.com/)\n", 438 | "- [Compiler Explorer](https://gcc.godbolt.org/)\n", 439 | "- [Repl.it](https://replit.com/)\n", 440 | "\n", 441 | "As your code grows in complexity (but even in the case of simple projects), the constant compilation, debugging, linting, etc could transform into a repetitive task that might be automatized. For simple projects you can use gnu make, using tutorials like https://makefiletutorial.com/ or https://www.cs.colby.edu/maxwell/courses/tutorials/maketutor/ or http://swcarpentry.github.io/make-novice/. For more complex projects and multiplatform support, you might use [cmake](https://www.google.com/search?client=firefox-b-d&q=cmake+tutorial+modern). " 442 | ] 443 | }, 444 | { 445 | "cell_type": "markdown", 446 | "id": "9f7d0177", 447 | "metadata": {}, 448 | "source": [ 449 | "### Package managers\n", 450 | "Besides the typical operating system package manager, you can also use tools like [spack](https://spack.readthedocs.io/en/latest/), [meson](https://mesonbuild.com/), [vcpkg](https://github.com/microsoft/vcpkg), [conan](https://conan.io/), ..." 451 | ] 452 | }, 453 | { 454 | "cell_type": "markdown", 455 | "id": "9dc54a45", 456 | "metadata": {}, 457 | "source": [ 458 | "### Version control\n", 459 | "It is ALWAYS advisable to use version control. Please use git, so you will be able to rollback changes, create, merge and delete branches, activate continuous integration, and so on. You can also sync with remote repositories in portals like https://github.com/, or https://about.gitlab.com/why-gitlab/ . There are many tutorials, like https://swcarpentry.github.io/git-novice/ or https://learngitbranching.js.org/" 460 | ] 461 | }, 462 | { 463 | "cell_type": "markdown", 464 | "id": "1bac70b3", 465 | "metadata": {}, 466 | "source": [ 467 | "### Testing\n", 468 | "It is very important to write code that is testable, and to test constantly specially when introducing new changes To do so, you can use https://github.com/catchorg/Catch2, https://github.com/google/googletest , etc" 469 | ] 470 | }, 471 | { 472 | "cell_type": "markdown", 473 | "id": "a4859d4a", 474 | "metadata": {}, 475 | "source": [ 476 | "### Reproducible environments\n", 477 | "When you write a new program and want to distribute it, or run it on another machine, you must ensure that it runs as in the original development machine. To do so, the modern solution is to use containers. Learn how to use [docker](https://www.docker.com/) or [Podman](https://podman.io/). This will be required for the final project.\n", 478 | "\n", 479 | "### Documentation\n", 480 | "Use comments, and better, use something like [doxygen](https://www.doxygen.nl/)" 481 | ] 482 | }, 483 | { 484 | "cell_type": "code", 485 | "execution_count": null, 486 | "id": "88257dca", 487 | "metadata": {}, 488 | "outputs": [], 489 | "source": [] 490 | } 491 | ], 492 | "metadata": { 493 | "kernelspec": { 494 | "display_name": "Python 3 (ipykernel)", 495 | "language": "python", 496 | "name": "python3" 497 | }, 498 | "language_info": { 499 | "codemirror_mode": { 500 | "name": "ipython", 501 | "version": 3 502 | }, 503 | "file_extension": ".py", 504 | "mimetype": "text/x-python", 505 | "name": "python", 506 | "nbconvert_exporter": "python", 507 | "pygments_lexer": "ipython3", 508 | "version": "3.12.6" 509 | }, 510 | "toc": { 511 | "base_numbering": 1, 512 | "nav_menu": {}, 513 | "number_sections": true, 514 | "sideBar": true, 515 | "skip_h1_title": false, 516 | "title_cell": "Table of Contents", 517 | "title_sidebar": "Contents", 518 | "toc_cell": false, 519 | "toc_position": {}, 520 | "toc_section_display": true, 521 | "toc_window_display": false 522 | }, 523 | "varInspector": { 524 | "cols": { 525 | "lenName": 16, 526 | "lenType": 16, 527 | "lenVar": 40 528 | }, 529 | "kernels_config": { 530 | "python": { 531 | "delete_cmd_postfix": "", 532 | "delete_cmd_prefix": "del ", 533 | "library": "var_list.py", 534 | "varRefreshCmd": "print(var_dic_list())" 535 | }, 536 | "r": { 537 | "delete_cmd_postfix": ") ", 538 | "delete_cmd_prefix": "rm(", 539 | "library": "var_list.r", 540 | "varRefreshCmd": "cat(var_dic_list()) " 541 | } 542 | }, 543 | "types_to_exclude": [ 544 | "module", 545 | "function", 546 | "builtin_function_or_method", 547 | "instance", 548 | "_Feature" 549 | ], 550 | "window_display": false 551 | } 552 | }, 553 | "nbformat": 4, 554 | "nbformat_minor": 5 555 | } 556 | -------------------------------------------------------------------------------- /01-IntroCPP/Resources.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "f9e3ef15-8abb-4e10-8c03-9d217e0dbc49", 6 | "metadata": {}, 7 | "source": [ 8 | "# Resources\n", 9 | "\n", 10 | "\n", 11 | "## Presentations and resources\n", 12 | "- https://tinyurl.com/ProgCPP-Presentations\n", 13 | "- https://www.learncpp.com/\n", 14 | "- https://en.cppreference.com/w/\n", 15 | "- https://hackingcpp.com/cpp/cheat_sheets.html\n", 16 | "- https://quickref.me/cpp\n", 17 | "- https://www.udacity.com/course/c-for-programmers--ud210\n", 18 | "- https://iluvatar.bitbucket.io/ProgCPP/\n", 19 | "- https://github.com/federico-busato/Modern-CPP-Programming\n", 20 | "- https://nick-black.com/dankwiki/index.php/Book_list_for_streetfighting_computer_scientists\n", 21 | "- https://www.youtube.com/watch?v=l0qvxPPISuY&list=PLVlQHNRLflP8_DGKcMoRw-TYJJALgGu4J\n", 22 | "\n", 23 | "\n", 24 | "## Shell/bash/terminal\n", 25 | "\n", 26 | "- https://swcarpentry.github.io/shell-novice/\n", 27 | "- http://swcarpentry.github.io/shell-novice-es\n", 28 | "- https://github.com/phyver/GameShell\n", 29 | "- https://overthewire.org/wargames/bandit/\n", 30 | "- https://github.com/learnbyexample/TUI-apps/tree/main\n", 31 | "\n", 32 | "## git\n", 33 | "\n", 34 | "- https://swcarpentry.github.io/git-novice/\n", 35 | "- http://swcarpentry.github.io/git-novice-es\n", 36 | "- https://ohmygit.org/\n", 37 | "\n", 38 | "## About c++\n", 39 | "\n", 40 | "- https://survey.stackoverflow.co/2022/#technology-top-paying-technologies\n", 41 | "- https://survey.stackoverflow.co/2022/#most-popular-technologies-language-prof\n", 42 | "- https://www.codecademy.com/resources/blog/what-is-c-plus-plus-used-for/\n", 43 | "- https://github.com/fffaraz/awesome-cpp\n", 44 | "- https://theartofhpc.com/\n", 45 | "\n", 46 | "\n" 47 | ] 48 | }, 49 | { 50 | "cell_type": "code", 51 | "execution_count": null, 52 | "id": "8a88b008-cc1c-4471-a597-a8ac62f72b7c", 53 | "metadata": {}, 54 | "outputs": [], 55 | "source": [] 56 | } 57 | ], 58 | "metadata": { 59 | "kernelspec": { 60 | "display_name": "Python 3 (ipykernel)", 61 | "language": "python", 62 | "name": "python3" 63 | }, 64 | "language_info": { 65 | "codemirror_mode": { 66 | "name": "ipython", 67 | "version": 3 68 | }, 69 | "file_extension": ".py", 70 | "mimetype": "text/x-python", 71 | "name": "python", 72 | "nbconvert_exporter": "python", 73 | "pygments_lexer": "ipython3", 74 | "version": "3.12.5" 75 | } 76 | }, 77 | "nbformat": 4, 78 | "nbformat_minor": 5 79 | } 80 | -------------------------------------------------------------------------------- /02-derivatives/NumericalDifferentiation.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "987529ae-8105-40ef-8cc2-6024004c0c75", 6 | "metadata": { 7 | "tags": [] 8 | }, 9 | "source": [ 10 | "# Numerical differentiation\n", 11 | "\n", 12 | "REFS:\n", 13 | "- Ward; Kincaid; Numerical mathematics and computing\n", 14 | "- Wikipedia\n", 15 | "\n", 16 | "Computing derivatives is the core of many of the numerical work done in computational physics. But it is not a trivial problem to do so with good accuracy. Numerical derivatives are the core computation in finite difference methods, optimization problems, interpolations and many more. For instance, you need numerical derivatives to compute:\n", 17 | "- your speed based on position and time. This is done with your gps (google maps, waze, etc), or the [tracker](https://opensourcephysics.github.io/tracker-website/) software.\n", 18 | "- the rate of change of any quantity that changes in time: speedometers, weather models, finance, etc.\n", 19 | "- solutions for partial differential equations using \"finite differences\" .\n", 20 | "- solutions for ordinary differential equations." 21 | ] 22 | }, 23 | { 24 | "cell_type": "markdown", 25 | "id": "36793dbc-4eb4-4c0c-9a66-22376aa86da0", 26 | "metadata": { 27 | "tags": [] 28 | }, 29 | "source": [ 30 | "## First approach: forward difference\n", 31 | "The [Taylor expansion](https://en.wikipedia.org/wiki/Taylor_series?useskin=vector) for a given analytical function is given by (see an example at )\n", 32 | "\\begin{equation}\n", 33 | "f(x+h) = f(x) + h f'(x) + \\frac{h^2}{2!} f''(x) + \\frac{h^3}{3!} f'''(x) + \\dots,\n", 34 | "\\end{equation}\n", 35 | "If we stop at the second order, we can rewrite it as\n", 36 | "\\begin{equation}\n", 37 | "f(x+h) = f(x) + h f'(x) + O(h^2),\n", 38 | "\\end{equation}\n", 39 | "where $O(h^2)$ means that we stop expanding at the second order term, and , given that $h$ is small, then the dominant term is of order $h^2$. This equation can be used to both solve a ODE (where we already know the $f'(x)$, see ), or, to actually compute $f'(x)$ , as a way to compute the slope ():\n", 40 | "\n", 41 | "\\begin{equation}\n", 42 | "f'(x) \\simeq \\dfrac{f(x+h) - f(x)}{h} + O(h),\n", 43 | "\\end{equation}\n", 44 | "\n", 45 | "which shows that, mathematically, the error should decerease as $h$ (but, in the computer, there are more error sources). This approximation basically estimates the derivative using a linear interpolation, and assumes that you can compute $f(x)$ for arbitrary points.\n", 46 | "" 47 | ] 48 | }, 49 | { 50 | "cell_type": "markdown", 51 | "id": "bffe3348-72d1-490c-8655-af4c8a645ddf", 52 | "metadata": { 53 | "tags": [] 54 | }, 55 | "source": [ 56 | "## Implementing it in C++\n", 57 | "\n", 58 | "Think about a function declaration to implement the forward difference. What data type to return, what arguments? specially, should the function to be derived be an argument? For instance, if you want to derive the $\\sin$ function, you can use something that returns\n", 59 | "```c++\n", 60 | "...\n", 61 | "return (\\sin(x+h) - \\sin(x))/h;\n", 62 | "```\n", 63 | "That would work for that particular function, but if we want to derive other functions, then we would need to write more functions like this, maybe playing with the name to avoid name collisions. When programming, it is important to be generic. So it is much better to think about using a generic function $f$ that receives a double and returns a double. " 64 | ] 65 | }, 66 | { 67 | "cell_type": "markdown", 68 | "id": "6e9fdcab-57af-4ef3-8ccc-b18707e38f1f", 69 | "metadata": { 70 | "tags": [] 71 | }, 72 | "source": [ 73 | "## A better estimation with less error: Central difference\n", 74 | "We have used the forward derivative but there is nohing special about it. What if we played with the expansions both forward and backward?\n", 75 | "\n", 76 | "If you compute a forward ($+h$) expansion, you have\n", 77 | "\\begin{equation}\n", 78 | "f(x+h) = f(x) + f'(x) h + f''(x) h^2/2 + f'''(x) h^3/6 + O(h^4) + O(h^5),\n", 79 | "\\end{equation}\n", 80 | "and a backward ($-h$) Taylor expansion,\n", 81 | "\n", 82 | "\\begin{equation}\n", 83 | "f(x-h) = f(x) - f'(x) h + f''(x) h^2/2 - f'''(x) h^3/6 + O(h^4) - O(h^5),\n", 84 | "\\end{equation}\n", 85 | "and then you subtract the second from the first (notice that adding then allows you to compute the second order derivative), you get\n", 86 | "\n", 87 | "$$f'(x) \\simeq \\frac{f(x+h) - f(x-h)}{2h} + O(h^2)$$\n", 88 | "\n", 89 | "which is called the central difference. The order is improved and this version is better than the simple forward difference. See: \n", 90 | "\n", 91 | "|Comparison among methods| Dependence on $h$|\n", 92 | "|-|-|\n", 93 | "|||" 94 | ] 95 | }, 96 | { 97 | "cell_type": "markdown", 98 | "id": "4328831c-d092-416f-84a9-36b871e0eda5", 99 | "metadata": { 100 | "deletable": false, 101 | "editable": false, 102 | "nbgrader": { 103 | "cell_type": "markdown", 104 | "checksum": "27ca707416bc9109ff87478bac0b55e1", 105 | "grade": false, 106 | "grade_id": "cell-2efc63647d50b066", 107 | "locked": true, 108 | "schema_version": 3, 109 | "solution": false, 110 | "task": false 111 | } 112 | }, 113 | "source": [ 114 | "## Other important cases\n", 115 | "- Interpolating data and then estimating the derivative\n", 116 | "- Derivative of noisy data: first compute binned averages and then derive. \n", 117 | "- Higher order derivatives\n", 118 | "- N-dimensional derivatives. " 119 | ] 120 | }, 121 | { 122 | "cell_type": "markdown", 123 | "id": "70b54a98-9e28-45bb-b4c8-8197860a8e4e", 124 | "metadata": {}, 125 | "source": [ 126 | "## Implementing forward and central derivatives\n", 127 | "\n", 128 | "Implement functions to compute both the forward and central derivatives. \n", 129 | "\n", 130 | "The prototypes might be\n", 131 | "```c++\n", 132 | "double forward_diff(double x, double h);\n", 133 | "double central_diff(double x, double h);\n", 134 | "```\n", 135 | "\n", 136 | "Use modular implementation. " 137 | ] 138 | }, 139 | { 140 | "cell_type": "markdown", 141 | "id": "1a47cd8e-233c-4785-83a8-ed3650ec2078", 142 | "metadata": {}, 143 | "source": [ 144 | "### Error a as function of $h$\n", 145 | "Now fix $ = 1.454335$, and compute (using another main function) the relative error as a function of $h \\in [10^{-16}, 10^{-15}, 10^{-14}, \\ldots, 10^{-3}, 10^{-2}, 10^{-1}]$. Plot it.\n", 146 | "Explain the differences among forward and central results.\n", 147 | "\n", 148 | "You can plot using the following python script, but you have to adapt it and improve it:\n", 149 | "```python\n", 150 | "import matplotlib.pyplot as plt\n", 151 | "import numpy as np\n", 152 | "# import seaborn as sns\n", 153 | "# sns.set_context(\"poster\")\n", 154 | "\n", 155 | "# read data\n", 156 | "x, y = np.loadtxt(\"data.txt\", unpack=True)\n", 157 | "\n", 158 | "# plot \n", 159 | "fig, ax = plt.subplots()\n", 160 | "ax.plot(x, y, '-o', 'mylabel')\n", 161 | "ax.legend()\n", 162 | "fig.savefig('deriv.pdf')\n", 163 | "```" 164 | ] 165 | }, 166 | { 167 | "cell_type": "markdown", 168 | "id": "5394643b-6432-4f1d-ba9f-5344a3408c50", 169 | "metadata": {}, 170 | "source": [ 171 | "### File modularization\n", 172 | "\n", 173 | "Now try to modularize the code. Create headers and implementation files called `derivatives.h` and `derivatives.cpp`, where you are going to put declarations and implementations for both the forward and the central derivative methods. What happens now? where should the function to be derived go? We need a more generic approach. Use `using fptr = double(double)` as a function pointer, which is a construct that represents what a function returns and receives. The ideal is to use the functions as parameters\n", 174 | "```c++\n", 175 | "using fptr = double(double); // pointer(c++11) to a function which receives a double and returns a double\n", 176 | "double forward_diff(double x, double h, fptr fun);\n", 177 | "double central_diff(double x, double h, fptr fun);\n", 178 | "```\n", 179 | "\n", 180 | "We can even go further and try to use [C++ templates](https://hackingcpp.com/cpp/lang/templates.html), so we will have \n", 181 | "```c++\n", 182 | "template \n", 183 | "double forward_diff(double x, double h, funptr fun);\n", 184 | "template \n", 185 | "double central_diff(double x, double h, funptr fun);\n", 186 | "```\n", 187 | "Or even use functors or std::function. For now let's just keep this simple with `using`.\n" 188 | ] 189 | }, 190 | { 191 | "cell_type": "markdown", 192 | "id": "f185f75a-4aee-4815-b05d-d2f5b8fc4a5e", 193 | "metadata": {}, 194 | "source": [ 195 | "### Testing a first implementation\n", 196 | "Compute the derivative as a function of $x$, with fixed $h = 0.01$. Use $f(x) = \\sin(x^2)$. Compare with the exact derivative. Plot the relative difference." 197 | ] 198 | }, 199 | { 200 | "cell_type": "markdown", 201 | "id": "a07b2485-f909-466c-96d0-c08357bd681b", 202 | "metadata": {}, 203 | "source": [ 204 | "### Error as a function of both $h$ and $x$\n", 205 | "Is the error dependent on $x$ also? explore variations for both $x$ and $y$ and plot in a 3d picture." 206 | ] 207 | }, 208 | { 209 | "cell_type": "markdown", 210 | "id": "42f83fda-6043-495c-b3ff-dff6e20e9608", 211 | "metadata": {}, 212 | "source": [ 213 | "## Richardson extrapolation\n", 214 | "By using [Richardson extrapolation](https://en.wikipedia.org/wiki/Richardson_extrapolation), you can improve even more the central difference estimation, \n", 215 | "\n", 216 | "\\begin{equation}\n", 217 | "f'(x) = \\phi\\left(\\frac{h}{2}\\right) + \\frac{1}{3}\\left[\\phi\\left(\\frac{h}{2} \\right) - \\phi(h) \\right] + O(h^4),\n", 218 | "\\end{equation}\n", 219 | "\n", 220 | "where $\\phi(h)$ is the derivative estimation from the central difference with a given $h$ value. **NOTE**: This form is only for the central difference, since it depends on the algorithm order. " 221 | ] 222 | }, 223 | { 224 | "cell_type": "markdown", 225 | "id": "60a2884a-8c41-4941-b5f2-ca3b2d826c3f", 226 | "metadata": {}, 227 | "source": [ 228 | "## Implementing Richardson extrapolation\n", 229 | "Now, use the general expression for Richardson extrapolation applied to an algorithm of order $O(h^\\alpha)$, and also plot its relative differences for fixed $x$, (see https://en.wikipedia.org/wiki/Richardson_extrapolation?useskin=vector)\n", 230 | "\n", 231 | "\\begin{equation}\n", 232 | "I \\simeq \\dfrac{t^\\alpha I(\\frac{h}{t}) - I(h)}{t^\\alpha - 1},\n", 233 | "\\end{equation}\n", 234 | "\n", 235 | "where $t$ is a factor larger than 1 (tipically $t=2$), $\\alpha$ is the algorithm order, and $I$ is the value you are computing. This implies additions to both headers and implementation files, and a new main.\n" 236 | ] 237 | }, 238 | { 239 | "cell_type": "markdown", 240 | "id": "61869ba5-f9c7-4a5b-bcf6-c15bf4923591", 241 | "metadata": {}, 242 | "source": [ 243 | "As you can see, the Richardson implementation is very similar for both the central and the forward algorithms. Maybe there is some hope to decrease this duplication. Think about a new `using ...` construct. Implement it and plot all errors as a function of $h$" 244 | ] 245 | }, 246 | { 247 | "cell_type": "markdown", 248 | "id": "80e9fccb-ccaf-4f39-b71d-ff4f53743cba", 249 | "metadata": {}, 250 | "source": [ 251 | "## Modularizing the files with Richardson extrapolation\n", 252 | "\n", 253 | "Until now, we have used the simple `using fptr = double(double)` for modelling a generic function to be derived. In the case of Richardson extrapolation, we have two generics:\n", 254 | "- the actual function to be derived\n", 255 | "- the actual algorithm to be used (central, forward, etc)\n", 256 | "Our simple approach does not work in this case. We cannot use using inside using. Also, our approach does not work with other kind of functions, like templates or lambdas. Therefore, we need to use a more generic approach. In this case, using `std::function`, which is a generalization of an object behaving like a function (you need to `#include `), we can solve this and modularize our code.\n", 257 | "\n", 258 | "Our files will be like (fill in the `// todo`)" 259 | ] 260 | }, 261 | { 262 | "cell_type": "markdown", 263 | "id": "d914d530-a7fc-4450-b340-23572799748f", 264 | "metadata": {}, 265 | "source": [ 266 | "`derivatives.h`: To store the declarations\n", 267 | "```c++\n", 268 | "#pragma once\n", 269 | "\n", 270 | "#include \n", 271 | "#include \n", 272 | "\n", 273 | "using fptr = std::function;\n", 274 | "\n", 275 | "double deriv_central(fptr f, double x, double h);\n", 276 | "double deriv_forward(fptr f, double x, double h);\n", 277 | "\n", 278 | "// notice the fptr inside the algptr\n", 279 | "using algptr = std::function;\n", 280 | "\n", 281 | "double richardson(fptr f, double x, double h, algptr alg, int n); // n is the algorithm order\n", 282 | "\n", 283 | "```" 284 | ] 285 | }, 286 | { 287 | "cell_type": "markdown", 288 | "id": "1ff215a2-337b-4bd9-94f3-57ae05f232c3", 289 | "metadata": { 290 | "deletable": false, 291 | "editable": false, 292 | "nbgrader": { 293 | "cell_type": "markdown", 294 | "checksum": "cb6047e47692e26b8c869cda478c6d10", 295 | "grade": false, 296 | "grade_id": "cell-d7557d99f05f2163", 297 | "locked": true, 298 | "points": 0, 299 | "schema_version": 3, 300 | "solution": false, 301 | "task": true 302 | } 303 | }, 304 | "source": [ 305 | "`derivatives.cpp`: \n", 306 | "```c++\n", 307 | "#include \"deriv.h\"\n", 308 | "\n", 309 | "double deriv_central(fptr f, double x, double h) {\n", 310 | "\t// Central difference formula\n", 311 | " // todo\n", 312 | "}\n", 313 | "\n", 314 | "double deriv_forward(fptr f, double x, double h) {\n", 315 | "\t// Forward difference formula\n", 316 | " // todo\n", 317 | "}\n", 318 | "\n", 319 | "double richardson(fptr f, double x, double h, algptr alg, int n) // n is the algorithm order\n", 320 | "{\n", 321 | " // todo\n", 322 | "}\n", 323 | "\n", 324 | "```" 325 | ] 326 | }, 327 | { 328 | "cell_type": "markdown", 329 | "id": "a8ad69ff-f171-4c41-b3d6-3ea43b797f78", 330 | "metadata": {}, 331 | "source": [ 332 | "and our main function file `main_deriv.cpp`\n", 333 | "```c++\n", 334 | "#include \n", 335 | "\n", 336 | "#include \"deriv.h\"\n", 337 | "\n", 338 | "double fun(double x) {\n", 339 | "\treturn x * x*std::sin(x);\n", 340 | "}\n", 341 | "\n", 342 | "int main(int argc, char **argv) {\n", 343 | " std::cout.precision(16);\n", 344 | " std::cout.setf(std::ios::scientific);\n", 345 | "\tstd::cout << deriv_forward(fun, 1.0, 0.01) << std::endl;\n", 346 | "\tstd::cout << deriv_central(fun, 1.0, 0.01) << std::endl;\n", 347 | "\tstd::cout << deriv_central([](double x){ return x*x*std::sin(x);}, 1.0, 0.01) << std::endl; // works for a lambda function\n", 348 | "\tstd::cout << richardson(fun, 1.0, 0.01, deriv_central, 2) << std::endl;\n", 349 | "\n", 350 | "\treturn 0;\n", 351 | "}\n", 352 | "```" 353 | ] 354 | }, 355 | { 356 | "cell_type": "markdown", 357 | "id": "d7bc4c86-5b74-4dd4-ad47-c6ab34c31904", 358 | "metadata": {}, 359 | "source": [ 360 | "To compile, use wither full compilation (easy but not practical with many cpp files)\n", 361 | "```sh\n", 362 | "g++ -std=c++17 derivatives.cpp main_deriv.cpp\n", 363 | "```\n", 364 | "or the modularized one, which can be automated using a `Makefile`\n", 365 | "```sh\n", 366 | "g++ -std=c++17 -c derivatives.cpp # Produces the object deriv.o\n", 367 | "g++ -std=c++17 -c main_deriv.cpp # Produces the object main_deriv.o\n", 368 | "g++ -std=c++17 derivatives.o main_deriv.o # links both objects and produces the executable\n", 369 | "```" 370 | ] 371 | }, 372 | { 373 | "cell_type": "markdown", 374 | "id": "7f3e67f2-c086-4f06-9aeb-bb0173c65d49", 375 | "metadata": {}, 376 | "source": [ 377 | "## Testing\n", 378 | "Can you of some test to write for your derivatives? Implement some tests in another main file" 379 | ] 380 | }, 381 | { 382 | "cell_type": "markdown", 383 | "id": "8373571c", 384 | "metadata": {}, 385 | "source": [] 386 | } 387 | ], 388 | "metadata": { 389 | "kernelspec": { 390 | "display_name": "Python 3 (ipykernel)", 391 | "language": "python", 392 | "name": "python3" 393 | }, 394 | "language_info": { 395 | "codemirror_mode": { 396 | "name": "ipython", 397 | "version": 3 398 | }, 399 | "file_extension": ".py", 400 | "mimetype": "text/x-python", 401 | "name": "python", 402 | "nbconvert_exporter": "python", 403 | "pygments_lexer": "ipython3", 404 | "version": "3.12.10" 405 | } 406 | }, 407 | "nbformat": 4, 408 | "nbformat_minor": 5 409 | } 410 | -------------------------------------------------------------------------------- /04-vector-containers/ModernArrays.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "eb866408-5568-48d6-a3c4-b4f788397aee", 6 | "metadata": {}, 7 | "source": [ 8 | "# Modern arrays\n", 9 | "\n", 10 | "Arrays are useful to store large sets of data that share the same data type.\n", 11 | "Arrays are very fast to access and modify data, and are useful in several cases,\n", 12 | "like\n", 13 | "\n", 14 | "- Reading and storing data.\n", 15 | "- Applying the same operation to a large collection of data.\n", 16 | "- Store data in a systematic way instead of having many variables.\n", 17 | "- Model vectors, matrices, tensors.\n", 18 | "- Model vectorial and matrix operations.\n", 19 | "- Solve large linear problems, linear algebra problems, compute eigen values and\n", 20 | " eigen vectors.\n", 21 | "- Solve ODE systems.\n", 22 | "- Apply finite differences and finite elements.\n", 23 | "- Vectorize operations and use HPC.\n", 24 | "- Model data structs, from physical systems to graphical structs and so on.\n", 25 | "- Manipulate memory contents and program close to the metal.\n", 26 | "- …\n", 27 | "\n", 28 | "There are many more data structs or [containers](https://en.cppreference.com/w/cpp/container): lists, dictionaries(maps), queue, binary trees, etc (see\n", 29 | "). Arrays, in\n", 30 | "particular, are very fast to access and retrieve data from memory. But they are\n", 31 | "not fast if you need to insert and delete data in the middle. In general, for\n", 32 | "scientific computing, arrays are the default data struct, but you need always to\n", 33 | "consider which one would be the best for your case.\n", 34 | "\n", 35 | "Since c++11 it is possible to use modern data structs that are equivalent to the\n", 36 | "primitive data arrays but give a better user interface, also handling\n", 37 | "automatically the memory. Although there are two analog structures, [std::array](https://en.cppreference.com/w/cpp/container/array)\n", 38 | "and [std::vector](https://en.cppreference.com/w/cpp/container/vector) (and in the future we will use [std::valarray](https://en.cppreference.com/w/cpp/numeric/valarray)), we will focus\n", 39 | "mainly on the `std::vector` since it handles dynamic memory (`std::array` is for\n", 40 | "static arrays). The key here is that these data structures create a continuous\n", 41 | "block memory block that can be accessed very fast: https://hackingcpp.com/cpp/std/sequence_containers.html\n", 42 | "\n", 43 | "
\n", 44 | " \"Image\n", 45 | "
From: \"https://hackingcpp.com/cpp/std/vector.png\"
\n", 46 | "
" 47 | ] 48 | }, 49 | { 50 | "cell_type": "markdown", 51 | "id": "01bd1d48-06f3-48f3-a7ff-72c551942d13", 52 | "metadata": {}, 53 | "source": [ 54 | "The following example shows the basic features for both of them and also a new\n", 55 | "kind of `for`. It is recommended to run this on a graphical debugger , either\n", 56 | "locally in emacs or visual code, or online on the python tutor or [onlinegdb](https://www.onlinegdb.com/), at\n", 57 | "the link .\n", 58 | "\n", 59 | "```c++\n", 60 | "#include \n", 61 | "#include \n", 62 | "#include \n", 63 | "\n", 64 | "int main(void)\n", 65 | "{\n", 66 | " std::array data1;\n", 67 | " data1[5] = 9.87;\n", 68 | " data1[0] = -7.8765;\n", 69 | " data1[9] = 1000.343;\n", 70 | " std::cout << data1[5] << \"\\n\";\n", 71 | " for (auto val : data1) {\n", 72 | " std::cout << val << \"\\n\";\n", 73 | " }\n", 74 | "\n", 75 | " std::vector data2;\n", 76 | " data2.resize(4); // size = 4, capacity 4\n", 77 | " data2[3] = 9.87;\n", 78 | " data2[0] = -7.8765;\n", 79 | " data2[1] = 1000.343;\n", 80 | " std::cout << data2[2] << std::endl;\n", 81 | " for (auto & val : data2) { // reference\n", 82 | " val *= 2; // modify the value\n", 83 | " std::cout << val << \"\\n\";\n", 84 | " }\n", 85 | " data2.resize(5); // size = 5, capacity = 8 (double the initial, to avoid frequent mallocs)\n", 86 | " data2.push_back(0.987); // size = 6, capacity = 8\n", 87 | " data2.push_back(12343.987); // size = 7, capacity = 8\n", 88 | " data2.push_back(-0.000987); // size = 8, capacity = 8\n", 89 | " data2.push_back(3.986544); // size = 9, capacity = 16\n", 90 | "\n", 91 | " return 0;\n", 92 | "}\n", 93 | "```\n", 94 | "\n", 95 | "As you can see, a vector is a dynamc array of homogeneous contigous elements.\n", 96 | "\n", 97 | "\n", 98 | "" 99 | ] 100 | }, 101 | { 102 | "cell_type": "markdown", 103 | "id": "5a8f4b19-c791-4e36-bdda-2dcb60cceae6", 104 | "metadata": {}, 105 | "source": [ 106 | "## Initial exercises\n", 107 | "\n", 108 | "1. Find the maximum size you can use for a `std::array` and a `std::vector` .\n", 109 | " Are they the same?\n", 110 | "2. Print the address of the first and second elements in a `std::array` and\n", 111 | " `std::vector`. Are they contigous? To print the memory address of the first\n", 112 | " element use the `&` operator as `&data[0]`\n", 113 | "3. Use the algorithm [foreach](https://en.cppreference.com/w/cpp/algorithm/for_each) with a lambda function to divide by two each\n", 114 | " element in an array. Use also for each to print the elements and their memory\n", 115 | " address." 116 | ] 117 | }, 118 | { 119 | "cell_type": "markdown", 120 | "id": "62554028-925c-47bd-8984-646f359169cd", 121 | "metadata": { 122 | "deletable": false, 123 | "editable": false, 124 | "nbgrader": { 125 | "cell_type": "markdown", 126 | "checksum": "1bb7d9e971c18f32c3a6dfd2a0b2afb1", 127 | "grade": false, 128 | "grade_id": "cell-0a6b662e36c7aac8", 129 | "locked": true, 130 | "points": 0, 131 | "schema_version": 3, 132 | "solution": false, 133 | "task": true 134 | } 135 | }, 136 | "source": [ 137 | "\n", 138 | "\n", 139 | "## Using `std::array` : Fixed size, goes to the stack, automatic for\n", 140 | "\n", 141 | "```c++\n", 142 | "// g++ -g -fsanitize=address\n", 143 | "#include \n", 144 | "#include \n", 145 | "\n", 146 | "int main(void)\n", 147 | "{\n", 148 | " const int N = 10;\n", 149 | " //double data[N] {0};\n", 150 | " std::array data;\n", 151 | "\n", 152 | " std::cout << \"size: \" << data.size() << std::endl;\n", 153 | " std::cout << \"max_size: \" << data.max_size() << std::endl;\n", 154 | " std::cout << \"&data[0]: \" << &data[0] << std::endl;\n", 155 | " std::cout << \"&data[1]: \" << &data[1] << std::endl;\n", 156 | "\n", 157 | " //std::cout << data[-1] << std::endl; // detected by sanitizers address\n", 158 | "\n", 159 | "// initialize the array with even numbers\n", 160 | " for(int ii = 0; ii < N; ++ii) {\n", 161 | " data[ii] = 2*ii;\n", 162 | " }\n", 163 | "\n", 164 | "\n", 165 | "// print the array\n", 166 | " for(const auto & val : data) {\n", 167 | " std::cout << val << \" \";\n", 168 | " }\n", 169 | " std::cout << \"\\n\"; \n", 170 | "\n", 171 | "// TODO: compute the mean\n", 172 | " std::cout << \"Average = \" << sum/data.size() << std::endl;\n", 173 | "\n", 174 | " return 0;\n", 175 | "}\n", 176 | "```\n", 177 | "You might visualize this in the python/c++ tutor.\n" 178 | ] 179 | }, 180 | { 181 | "cell_type": "markdown", 182 | "id": "a39d1673-ebac-472c-accf-2fc75b4c89cb", 183 | "metadata": {}, 184 | "source": [ 185 | "And we can simplified the code even more if we use the standard library:\n", 186 | "```c++\n", 187 | "// g++ -g -fsanitize=address\n", 188 | "#include \n", 189 | "#include \n", 190 | "#include \n", 191 | "#include \n", 192 | "\n", 193 | "int main(void)\n", 194 | "{\n", 195 | " const int N = 10;\n", 196 | " //double data[N] {0};\n", 197 | " std::array data;\n", 198 | "\n", 199 | " std::cout << \"size: \" << data.size() << std::endl;\n", 200 | " std::cout << \"max_size: \" << data.max_size() << std::endl;\n", 201 | " std::cout << \"&data[0]: \" << &data[0] << std::endl;\n", 202 | " std::cout << \"&data[1]: \" << &data[1] << std::endl;\n", 203 | "\n", 204 | " //std::cout << data[-1] << std::endl; // detected by sanitizers address\n", 205 | "\n", 206 | "// initialize the array with even numbers\n", 207 | " int ii = 0 ;\n", 208 | " auto init = [&ii](double & x){ x = 2*ii; ii++; };\n", 209 | " std::for_each(data.begin(), data.end(), init);\n", 210 | "\n", 211 | "// print the array\n", 212 | " auto print = [](const int & x) { std::cout << x << \" \" ; };\n", 213 | " std::for_each(data.begin(), data.end(), print);\n", 214 | " std::cout << \"\\n\";\n", 215 | "\n", 216 | "// compute mean\n", 217 | " double avg = std::accumulate(data.begin(), data.end(), 0.0)/data.size();\n", 218 | " std::cout << \"Average = \" << avg << std::endl;\n", 219 | "}\n", 220 | "```" 221 | ] 222 | }, 223 | { 224 | "cell_type": "markdown", 225 | "id": "219d2273-32fd-4633-8120-bd455eb72f53", 226 | "metadata": {}, 227 | "source": [ 228 | "\n", 229 | "\n", 230 | "### Exercises\n", 231 | "\n", 232 | "1. Find the largest `std::array` size you can get in your system. Is it related\n", 233 | " to the ram size? check the command\n", 234 | " \n", 235 | " ulimit -s\n", 236 | "2. Write a program that computes the dot product between two `std::arrays`. You\n", 237 | " can use either indexes or the `inner_product` or `transform_reduce`\n", 238 | " algorithms.\n", 239 | "3. Can you read the `std::array` size from the command line using `argv`? try\n", 240 | " it.\n", 241 | "\n", 242 | "\n", 243 | "" 244 | ] 245 | }, 246 | { 247 | "cell_type": "markdown", 248 | "id": "ad5258d4-e353-4d71-823c-62768e45357c", 249 | "metadata": {}, 250 | "source": [ 251 | "## Using `std::vector` : Dynamic size, uses the heap\n", 252 | "\n", 253 | "Vectors allow to use dynamic size arrays very easily and are the recommend data\n", 254 | "structure for our current math vector and matrix applications. You can see more\n", 255 | "info here:\n", 256 | "\n", 257 | "- \n", 258 | "- \n", 259 | "- \n", 260 | "- \n", 261 | "- \n", 262 | "\n", 263 | "To declare a vector of `double`, you just use\n", 264 | "```c++\n", 265 | "...\n", 266 | "std::vector data1(1000); // 1000 doubles\n", 267 | "std::vector data2; // no size yet\n", 268 | "data2.resize(1200); // reserve space to store 1200 double\n", 269 | "std::vector data3 {1, 2, 3}; // 3 ints, type deduced\n", 270 | "```" 271 | ] 272 | }, 273 | { 274 | "cell_type": "markdown", 275 | "id": "75e88a2e-81c2-4c2b-bc88-4338f611dcce", 276 | "metadata": {}, 277 | "source": [ 278 | "### Exploration : Declaration and operation on a vector\n", 279 | "Declare a vector of double whose size is read from the command line as an argument. Fill it as \n", 280 | "\n", 281 | "\\begin{equation}\n", 282 | "x[i] = i\n", 283 | "\\end{equation}\n", 284 | "\n", 285 | "Compute the average." 286 | ] 287 | }, 288 | { 289 | "cell_type": "markdown", 290 | "id": "f3dc559f-2118-486d-92d5-1f623b0a879e", 291 | "metadata": {}, 292 | "source": [ 293 | "### Exploration: Vectors and functions \n", 294 | "Same as before, but write a function to fill the vector and another to compute the vector average. Print the average in scientific notation. Test it with several sizes." 295 | ] 296 | }, 297 | { 298 | "cell_type": "markdown", 299 | "id": "0092e555-5fe0-4621-87eb-798d974f8400", 300 | "metadata": {}, 301 | "source": [ 302 | "### Exploration: Vectors and lambda functions\n", 303 | "Same as before, but use a lambda function to fill the vector." 304 | ] 305 | }, 306 | { 307 | "cell_type": "markdown", 308 | "id": "f61a5c56-c530-4463-ab21-2f58acb53afe", 309 | "metadata": { 310 | "deletable": false, 311 | "editable": false, 312 | "nbgrader": { 313 | "cell_type": "markdown", 314 | "checksum": "b2fa45b6e288bca551d0ce415b27f15e", 315 | "grade": false, 316 | "grade_id": "cell-a2b281fa7c958b9e", 317 | "locked": true, 318 | "points": 0, 319 | "schema_version": 3, 320 | "solution": false, 321 | "task": true 322 | } 323 | }, 324 | "source": [ 325 | "### Exploration: Vectors and `std` algorithms\n", 326 | "Same as before, but use lambda functions and standar algorithms to do the same\n", 327 | "\n", 328 | "```c++\n", 329 | "// g++ -g -fsanitize=address\n", 330 | "#include \n", 331 | "#include \n", 332 | "#include \n", 333 | "#include \n", 334 | "\n", 335 | "int main(int argc, char **argv)\n", 336 | "{\n", 337 | "// TODO\n", 338 | " return 0;\n", 339 | " \n", 340 | "}\n", 341 | "```" 342 | ] 343 | }, 344 | { 345 | "cell_type": "markdown", 346 | "id": "fe6ff1bf-805d-4408-b3fc-d23f683dfcfd", 347 | "metadata": {}, 348 | "source": [ 349 | "## A short discussion about primitive arrays\n", 350 | "Primitive arrays in C++ are fixed-size collections of elements of the same type stored in contiguous memory locations. They can be declared as\n", 351 | "```c++\n", 352 | "// Declaration and initialization\n", 353 | "int numbers[5] = {1, 2, 3, 4, 5};\n", 354 | "char name[6] = {'C', 'l', 'a', 'u', 'd', 'e'};\n", 355 | "\n", 356 | "// Access elements using index\n", 357 | "int third_number = numbers[2]; // Gets 3 (zero-indexed)\n", 358 | "```\n", 359 | "\n", 360 | "**Characteristics of Primitive Arrays**:\n", 361 | "- Fixed size: Size must be known at compile time\n", 362 | "- Stack allocation: Usually stored on the stack (unless global)\n", 363 | "- No bounds checking: C++ doesn't prevent accessing invalid indices\n", 364 | "- No built-in size information: Size must be tracked separately\n", 365 | "- Cannot be returned directly from functions (decays to pointer)\n", 366 | "\n", 367 | "**Exercise**\n", 368 | "Declare a primitive array of doubles of large size. What is the maximum size that you can get?\n", 369 | "\n", 370 | "### Primitive arrays with dynamic memory\n", 371 | "Dynamic arrays allow you to determine array size at runtime using pointers and heap memory allocation. See https://hackingcpp.com/cpp/lang/memory_basics.html. In this case, you must use a `pointer`, which is a variable that stores a memory address, and then ask the OS for memory (and release it), all manually.\n", 372 | "\n", 373 | "```c++\n", 374 | "// Allocate memory for 10 integers\n", 375 | "int * dynamic_array = new int[10];\n", 376 | "// todo: check if memory was actually allocated\n", 377 | "\n", 378 | "// Use the array\n", 379 | "dynamic_array[0] = 42;\n", 380 | "dynamic_array[1] = 73;\n", 381 | "\n", 382 | "// IMPORTANT: Must deallocate manually\n", 383 | "delete[] dynamic_array;\n", 384 | "```\n", 385 | "\n", 386 | "**Characteristics of Dynamic Arrays**:\n", 387 | "- Runtime size determination: Size can be decided during execution\n", 388 | "- Heap allocation: Memory is allocated on the heap\n", 389 | "- Manual memory management: You must remember to `delete[]`\n", 390 | "- Raw pointers: No built-in bounds checking or size information\n", 391 | "- Potential memory leaks: If not properly deallocated\n", 392 | "\n", 393 | "### Comparison with `std::vector`\n", 394 | "`std::vector` from the C++ Standard Library provides a more robust, safe, and flexible alternative.\n", 395 | "```c++\n", 396 | "#include \n", 397 | "\n", 398 | "// Create a vector\n", 399 | "std::vector numbers = {1, 2, 3, 4, 5};\n", 400 | "\n", 401 | "// Add elements\n", 402 | "numbers.push_back(6);\n", 403 | "\n", 404 | "// Get size\n", 405 | "size_t size = numbers.size(); // Returns 6\n", 406 | "\n", 407 | "// Access with bounds checking\n", 408 | "int safe_access = numbers.at(2); // Throws exception for invalid index\n", 409 | "```\n", 410 | "\n", 411 | "**Advantages of `std::vector`:**\n", 412 | "- Dynamic sizing: Automatically resizes as elements are added\n", 413 | "- Automatic memory management: No manual deallocation required\n", 414 | "- Bounds checking: Option to use .at() method for safer access\n", 415 | "- Rich functionality: Includes methods for insertion, deletion, searching: `push_back`, `pop_back`, `insert`, `erase`, `clear`, `size`, `empty`, and more.\n", 416 | "- Compatible with algorithms: Works with the entire C++ Standard Library\n", 417 | "- Contiguous storage: Same performance characteristics as arrays\n", 418 | "- Size information: Built-in tracking of current element count\n", 419 | "- Iterator support: Can be used with standard iterators\n", 420 | "\n", 421 | "Almost always prefer to use `std::vector`. \n", 422 | "\n", 423 | "> **EXERCISE: Comparing primitive arrays, dynamics memory and `std::vector`**\n", 424 | "Please write two programs. The first one, using a primitive array and dynamic memory, that starts with 5 elemments like `{2, 3, 4, 5, 6}`; then, print the memory address of the first element (`&data[0]`), and then append the number 10 at the end. Print the final array. \n", 425 | "Now write the second program doing the same but using a `std::vector`. \n" 426 | ] 427 | }, 428 | { 429 | "cell_type": "markdown", 430 | "id": "92d370bb-b79a-476c-b5b1-c98fdd0070c4", 431 | "metadata": {}, 432 | "source": [ 433 | "## Exercises\n", 434 | "\n", 435 | "Always try to use the STL, and also use functions to implement the following:\n", 436 | "\n", 437 | "1. Compute the norm of a vector.\n", 438 | "2. Implement the Gauss 7 point method, storing the weights and the coordinates points in a vector.\n", 439 | "3. Compute the dot product between two vectors. Use `std::inner_product`.\n", 440 | "4. Assume that a vector represents the coefficients of a n-degree polynomial.\n", 441 | " Compute the derivative of the polynomial and save the coefficients in another\n", 442 | " vector.\n", 443 | " ```cpp\n", 444 | " data = {1 , 3, 4.5}; // 1*x^0 + 3*x^1 + 4.5*x^2\n", 445 | " newdata = {3, 9.0}; // 0 + 3*x^0 + 2*4.5*x^1\n", 446 | " ```\n", 447 | "5. Compute the min of a vector.\n", 448 | "6. Compute the max of a vector.\n", 449 | "7. Compute the argmin (index of the min) of a vector\n", 450 | "8. Compute the argmax (index of the max) of a vector\n", 451 | "9. Compute the pnorm\n", 452 | " \n", 453 | " \\begin{equation}\n", 454 | " \\left(\\sum_{i} x_{i}^{p}\\right)^{1/p} \\ .\n", 455 | " \\end{equation}\n", 456 | "10. Read the contents of a large file into a vector. Compute and print the mean,\n", 457 | " the median, the 25, 50, 75 percentiles, the min value, and the max value.\n", 458 | "11. Use the standard algorithm sort to sort a data array.\n", 459 | "12. Fill a vector with random numbers\n", 460 | " ```c++\n", 461 | " // llenar un vector con numeros aleatorios\n", 462 | " \n", 463 | " #include \n", 464 | " #include \n", 465 | " #include \n", 466 | " #include \"random_vector.h\"\n", 467 | " \n", 468 | " int main(int argc, char **argv) {\n", 469 | " \n", 470 | " // read variables\n", 471 | " if (argc != 2) {\n", 472 | " std::cerr << \"Usage: \" << argv[0] << \" N\" << std::endl;\n", 473 | " std::cerr << \"N: size of the vector\" << std::endl;\n", 474 | " return 1;\n", 475 | " }\n", 476 | " const int N = std::stoi(argv[1]);\n", 477 | " \n", 478 | " // set the vector\n", 479 | " std::vector data;\n", 480 | " data.resize(N);\n", 481 | " \n", 482 | " // fill the vector\n", 483 | " fill_randomly(data);\n", 484 | " \n", 485 | " // print the vector\n", 486 | " std::string fname = \"data.txt\";\n", 487 | " print(data, fname);\n", 488 | " \n", 489 | " return 0;\n", 490 | " }\n", 491 | " ```\n", 492 | "13. Create a vector of `ints`, and then use `std::shuffle` to randomly shuffle it.\n", 493 | "14. Use a vector to compute the counter histogram for some data read from a\n", 494 | " file.\n", 495 | "15. Histogram from random numbers, saving to file. Write a program that\n", 496 | " generates N random numbers, with the Weibull distribution and a given seed.\n", 497 | " Both N, the seed, and the Weibull parameters must read from the command\n", 498 | " line. Also, you must compute the histogram and print it to a file." 499 | ] 500 | }, 501 | { 502 | "cell_type": "code", 503 | "execution_count": null, 504 | "id": "f28c032a-85e9-45cc-9cd0-76900657966c", 505 | "metadata": {}, 506 | "outputs": [], 507 | "source": [] 508 | } 509 | ], 510 | "metadata": { 511 | "kernelspec": { 512 | "display_name": "Python 3 (ipykernel)", 513 | "language": "python", 514 | "name": "python3" 515 | }, 516 | "language_info": { 517 | "codemirror_mode": { 518 | "name": "ipython", 519 | "version": 3 520 | }, 521 | "file_extension": ".py", 522 | "mimetype": "text/x-python", 523 | "name": "python", 524 | "nbconvert_exporter": "python", 525 | "pygments_lexer": "ipython3", 526 | "version": "3.12.10" 527 | } 528 | }, 529 | "nbformat": 4, 530 | "nbformat_minor": 5 531 | } 532 | -------------------------------------------------------------------------------- /05-matrixI/fig/1d-2d-mapping.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/05-matrixI/fig/1d-2d-mapping.png -------------------------------------------------------------------------------- /05-matrixI/fig/2d-array-memory.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/05-matrixI/fig/2d-array-memory.png -------------------------------------------------------------------------------- /05-matrixI/fig/2d-array.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/05-matrixI/fig/2d-array.png -------------------------------------------------------------------------------- /06-ArrayComputing/ArrayComputing-Valarray.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "e944b540-bb84-4500-8e27-75d5c49f4d9e", 6 | "metadata": {}, 7 | "source": [ 8 | "\n", 9 | "\n", 10 | "# Vector operations: Coefficient-wise , array computing\n", 11 | "\n", 12 | "Coefficient-wise operations, like the vector sum (which operate component by\n", 13 | "component), are very common and useful. For instance, the whole `numpy` library\n", 14 | "is based on that ().\n", 15 | "In c++ you can also do it, and it simplifies a lot many operations related to\n", 16 | "vectors. You have two options: using the standard library valarray, or using\n", 17 | "`Eigen` array.\n", 18 | "\n", 19 | "This is, for instance, what you would like to have when adding two structures representing vectors:\n", 20 | "
\n", 21 | " \"Image\n", 22 | "
From: \"http://jalammar.github.io/images/numpy/numpy-arrays-adding-1.png\"
\n", 23 | "
\n", 24 | "\n", 25 | "or with more operations\n", 26 | "
\n", 27 | " \"Image\n", 28 | "
From: \"http://jalammar.github.io/images/numpy/numpy-array-subtract-multiply-divide.png\"
\n", 29 | "
\n", 30 | "\n", 31 | "or with scalars,\n", 32 | "
\n", 33 | " \"Image\n", 34 | "
From: \"https://miro.medium.com/v2/resize:fit:1400/format:webp/1*XbZqTBXZmnQtVZ_llbGJTw.png\"
\n", 35 | "
\n", 36 | "\n", 37 | "## Function evaluation\n", 38 | "Furthermore , mathematical function evaluated in this array computing approach means evaluating the function on each component, such as\n", 39 | "\\begin{equation}\n", 40 | "\\vec y = \\sin (\\vec x)\n", 41 | "\\end{equation}\n", 42 | "means \n", 43 | "\\begin{equation}\n", 44 | "y_i = \\sin x_i.\n", 45 | "\\end{equation}" 46 | ] 47 | }, 48 | { 49 | "cell_type": "markdown", 50 | "id": "04a81908-15b8-4042-954f-98d480e8f769", 51 | "metadata": {}, 52 | "source": [ 53 | "\n", 54 | "\n", 55 | "## C++ `valarray`\n", 56 | "\n", 57 | "You can find the reference implementation at\n", 58 | " .\n", 59 | "\n", 60 | "```c++\n", 61 | "#include \n", 62 | "#include \n", 63 | "#include \n", 64 | "\n", 65 | "int main()\n", 66 | "{\n", 67 | " std::valarray v = {1,2,3,4,5,6,7,8,9,10};\n", 68 | "\n", 69 | " double suma = v.sum();\n", 70 | "\n", 71 | " std::cout << suma << \"\\n\";\n", 72 | "\n", 73 | " return 0;\n", 74 | "}\n", 75 | "```" 76 | ] 77 | }, 78 | { 79 | "cell_type": "markdown", 80 | "id": "4a8d9d78-7fad-45c2-a9bc-1b054a797260", 81 | "metadata": {}, 82 | "source": [ 83 | "### Example: Using apply\n", 84 | "Cómo usar la utilidad apply para multiplicar todos los elementos por 2 si el numero es impar y por 3 si el numero es par? Piense en la solución usando `for` e `if` y luego puede mirar a [https://en.cppreference.com/w/cpp/numeric/valarray/apply](https://en.cppreference.com/w/cpp/numeric/valarray/apply)" 85 | ] 86 | }, 87 | { 88 | "cell_type": "code", 89 | "execution_count": null, 90 | "id": "797d11ec-f173-4923-87e3-4b8f5017bda5", 91 | "metadata": { 92 | "editable": true, 93 | "slideshow": { 94 | "slide_type": "" 95 | }, 96 | "tags": [] 97 | }, 98 | "outputs": [], 99 | "source": [] 100 | }, 101 | { 102 | "cell_type": "markdown", 103 | "id": "e4b45e5b-9956-4ddf-92f9-e92c5a51361d", 104 | "metadata": {}, 105 | "source": [ 106 | "### Indexing\n", 107 | "A simple example for indexing,\n", 108 | "is the following ()\n", 109 | "\n", 110 | "```c++\n", 111 | "#include \n", 112 | "#include \n", 113 | "#include \n", 114 | "#include \n", 115 | "\n", 116 | "void print(std::string msg, const std::valarray& v)\n", 117 | "{\n", 118 | " std::cout << msg << \" \";\n", 119 | " for (int n: v) { std::cout << std::setw(3) << n; }\n", 120 | " std::cout << '\\n';\n", 121 | "}\n", 122 | "\n", 123 | "int main()\n", 124 | "{\n", 125 | " std::valarray v1(3);\n", 126 | " v1 = -1; // (3) from a scalar\n", 127 | " print(\"assigned from scalar: \", v1);\n", 128 | "\n", 129 | " v1 = {1, 2, 3, 4, 5, 6}; // (8): from initializer list of different size\n", 130 | " print(\"assigned from initializer_list:\", v1);\n", 131 | "\n", 132 | " std::valarray v2(3);\n", 133 | " v2 = v1[std::slice(0,3,2)]; // (4): from slice array\n", 134 | " print(\"every 2nd element starting at pos 0:\", v2);\n", 135 | "\n", 136 | " v2 = v1[v1 % 2 == 0]; // (6): from mask array\n", 137 | " print(\"values that are even:\", v2);\n", 138 | "\n", 139 | " std::valarray idx = {0,1,2,4}; // index array\n", 140 | " v2.resize(4); // sizes must match when assigning from gen subscript\n", 141 | " v2 = v1[idx]; // (7): from indirect array\n", 142 | " print(\"values at positions 0, 1, 2, 4:\", v2);\n", 143 | "\n", 144 | " return 0;\n", 145 | "}\n", 146 | "```" 147 | ] 148 | }, 149 | { 150 | "cell_type": "code", 151 | "execution_count": null, 152 | "id": "5f9e08a3-9c65-4db2-a526-46b78314caed", 153 | "metadata": {}, 154 | "outputs": [], 155 | "source": [] 156 | }, 157 | { 158 | "cell_type": "markdown", 159 | "id": "b00653dc-cb1f-4e75-b7fd-666c764b60d3", 160 | "metadata": {}, 161 | "source": [ 162 | "### Masks\n", 163 | "\n", 164 | "As you can see, all operations are done at the element level. You can also\n", 165 | "define masks:\n", 166 | "```c++\n", 167 | "#include \n", 168 | "#include \n", 169 | "\n", 170 | "int main()\n", 171 | "{\n", 172 | " std::valarray data = {0,1,2,3,4,5,6,7,8,9};\n", 173 | "\n", 174 | " std::cout << \"Initial valarray: \";\n", 175 | " for(int n: data) std::cout << n << ' ';\n", 176 | " std::cout << '\\n';\n", 177 | "\n", 178 | " data[data > 5] = -1; // valarray overload of operator[]\n", 179 | " // the type of data>5 is std::valarray\n", 180 | " // the type of data[data>5] is std::mask_array\n", 181 | "\n", 182 | " std::cout << \"After v[v>5]=-1: \\n\";\n", 183 | " for(std::size_t n = 0; n < data.size(); ++n)\n", 184 | " std::cout << data[n] << ' '; // regular operator[]\n", 185 | " std::cout << '\\n';\n", 186 | "}\n", 187 | "```" 188 | ] 189 | }, 190 | { 191 | "cell_type": "code", 192 | "execution_count": null, 193 | "id": "415654f6-135b-497d-8d55-42cde0f85220", 194 | "metadata": {}, 195 | "outputs": [], 196 | "source": [] 197 | }, 198 | { 199 | "cell_type": "code", 200 | "execution_count": null, 201 | "id": "324ef396-2ca8-40f2-b64e-2e1fa40af345", 202 | "metadata": {}, 203 | "outputs": [], 204 | "source": [] 205 | }, 206 | { 207 | "cell_type": "code", 208 | "execution_count": null, 209 | "id": "f77a9bab-e1f5-4158-a19e-9cda4bd100fa", 210 | "metadata": {}, 211 | "outputs": [], 212 | "source": [] 213 | }, 214 | { 215 | "cell_type": "markdown", 216 | "id": "8be6b900-cf06-4f4a-bef0-33a4e77306df", 217 | "metadata": {}, 218 | "source": [ 219 | "\n", 220 | "\n", 221 | "## Exercises" 222 | ] 223 | }, 224 | { 225 | "cell_type": "markdown", 226 | "id": "32441fd8-58c4-4c26-84a9-d44d12289cc2", 227 | "metadata": {}, 228 | "source": [ 229 | "### Dot product\n", 230 | "Create a program that computes the dot product among two math vectors using\n", 231 | " valarray. Your program must read the vector size from the command line. Fill\n", 232 | " them using any function you want." 233 | ] 234 | }, 235 | { 236 | "cell_type": "markdown", 237 | "id": "5221e672-62b0-4825-9aa6-17850ef2ca49", 238 | "metadata": {}, 239 | "source": [ 240 | "### Heap or stack?\n", 241 | "Is a valarray in the heap or the stack? Verify (check\n", 242 | " )" 243 | ] 244 | }, 245 | { 246 | "cell_type": "markdown", 247 | "id": "cc0ea0e4-3b3f-48f7-90cc-09888dbc092e", 248 | "metadata": {}, 249 | "source": [ 250 | "### Filter data\n", 251 | "Using the overloaded operators create a valarray for N=1000 points between 0\n", 252 | " and $2\\pi$, then compute the $\\sin$ of those numbers and assing the result to\n", 253 | " a another valarray, and finally print only the values that fulfill that\n", 254 | " $|\\sin x| \\le 0.5$. All of this without using loops." 255 | ] 256 | }, 257 | { 258 | "cell_type": "markdown", 259 | "id": "35235db3-5a1b-47e0-85a7-924088f171a0", 260 | "metadata": {}, 261 | "source": [ 262 | "### Simulation\n", 263 | "If you discretize time in steps of size $\\delta t$, and you have the forces on\n", 264 | "a given ideal particle, you can compute the next position using the Euler\n", 265 | "algorithm,\n", 266 | " \n", 267 | "\\begin{align}\n", 268 | "\\vec R(t+\\delta t) &= \\vec R(t) + \\delta t \\vec V(t),\\\\\n", 269 | "\\vec V(t + \\delta t) &= \\vec V(t) + \\delta t \\vec F(t)/m.\\\\\n", 270 | "\\end{align}\n", 271 | " \n", 272 | "Use valarrays to model the vectors. Compute the trayectory of a\n", 273 | "particle of mass $m=0.987$, with initial conditions $\\vec R(0) = (0, 0, 4.3),\n", 274 | " V(0) = (0.123, 0.0, 0.98)$, under the influence of gravity. Plot it. Later add\n", 275 | "some damping. Later add some interaction with the ground." 276 | ] 277 | }, 278 | { 279 | "cell_type": "markdown", 280 | "id": "8e707f85-df10-4ffd-bf8a-b710ddec6a7f", 281 | "metadata": {}, 282 | "source": [ 283 | "### Extract odd values\n", 284 | "Fill an `std::valarray` with random integers numbers uniformly distributed in [1000, 2500], and then extract the even values and compute their mean. " 285 | ] 286 | }, 287 | { 288 | "cell_type": "markdown", 289 | "id": "3373ec88-5430-456a-b021-3c290031971c", 290 | "metadata": {}, 291 | "source": [ 292 | "### Cross product\n", 293 | "Implement a function to compute the cross product between two 3d vectors. Using it, implement a function to compute the angle between the vectors. Remember that \n", 294 | "\\begin{equation}\n", 295 | "|\\vec A \\times \\vec B| = A B \\sin\\theta.\n", 296 | "\\end{equation}\n", 297 | "Check test cases like $\\vec A \\times \\vec A = \\vec 0, \\hat i \\times \\hat j = \\hat k, \\ldots$" 298 | ] 299 | }, 300 | { 301 | "cell_type": "markdown", 302 | "id": "84b24686-4238-42c7-b599-e5d9b64a70cf", 303 | "metadata": {}, 304 | "source": [ 305 | "### Perpendicular vector\n", 306 | "Use the previous cross product function to find a unit vector perpendicular to two vectors." 307 | ] 308 | }, 309 | { 310 | "cell_type": "markdown", 311 | "id": "be7e40dd-bfc3-4ad5-916d-46a61a774524", 312 | "metadata": {}, 313 | "source": [ 314 | "### Plane equation\n", 315 | "Find the equation of the plane in the form $ax + by + cz + d = 0$, saving the result in a 4d `std::vector`, given three 3D points represented using `std::valarray`." 316 | ] 317 | }, 318 | { 319 | "cell_type": "markdown", 320 | "id": "706c05bc-ab2c-4eff-b223-50b1ef86bd06", 321 | "metadata": {}, 322 | "source": [ 323 | "### Vector product\n", 324 | "Write a function that returns the vector product\n", 325 | "\\begin{equation}\n", 326 | "\\vec A \\cdot (\\vec B \\times \\vec C)\n", 327 | "\\end{equation}" 328 | ] 329 | }, 330 | { 331 | "cell_type": "markdown", 332 | "id": "2d79f6fb-479a-4f51-9ef2-c8c13a92e8fa", 333 | "metadata": {}, 334 | "source": [ 335 | "### Classical angular momentum and centripetal acceleration\n", 336 | "Given a mass $m$, a position $\\vec r$, and a velocity $\\vec v = \\omega \\times \\vec r $, compute both the angular momentum $\\vec L = m \\vec r \\times (\\vec r \\times \\vec \\omega)$ and the centripetal acceleration $\\vec a = \\vec \\omega \\times (\\vec \\omega \\times \\vec r)$, using two different functions" 337 | ] 338 | }, 339 | { 340 | "cell_type": "code", 341 | "execution_count": null, 342 | "id": "f5e1d161-4178-4ae7-8dab-3bd4c26ba08d", 343 | "metadata": {}, 344 | "outputs": [], 345 | "source": [] 346 | }, 347 | { 348 | "cell_type": "markdown", 349 | "id": "3f0e958c", 350 | "metadata": {}, 351 | "source": [ 352 | "## Other libraries\n", 353 | "- \n", 354 | "- \n", 355 | "- \n", 356 | "\n", 357 | "### Eigen arrays: coefficient wise computation\n", 358 | "This library also implements element-wise operations and data structs,\n", 359 | "https://eigen.tuxfamily.org/dox/group__TutorialArrayClass.html ,\n", 360 | "https://eigen.tuxfamily.org/dox/group__QuickRefPage.html#title6 . There are many\n", 361 | "overloaded operations that you can use. Plase check the docs.\n", 362 | "\n", 363 | "This is an example of a sum, element-wise\n", 364 | "```c++\n", 365 | "#include \n", 366 | "#include \n", 367 | "\n", 368 | "int main()\n", 369 | "{\n", 370 | " Eigen::ArrayXXf a(3,3);\n", 371 | " Eigen::ArrayXXf b(3,3);\n", 372 | " a << 1,2,3,\n", 373 | " 4,5,6,\n", 374 | " 7,8,9;\n", 375 | " b << 1,2,3,\n", 376 | " 1,2,3,\n", 377 | " 1,2,3;\n", 378 | "\n", 379 | " // Adding two arrays\n", 380 | " std::cout << \"a + b = \" << std::endl << a + b << std::endl << std::endl;\n", 381 | "\n", 382 | " // Subtracting a scalar from an array\n", 383 | " std::cout << \"a - 2 = \" << std::endl << a - 2 << std::endl;\n", 384 | "}\n", 385 | "```\n", 386 | "\n", 387 | "and this an example for vector product\n", 388 | "```c++\n", 389 | "#include \n", 390 | "#include \n", 391 | "\n", 392 | "int main()\n", 393 | "{\n", 394 | " Eigen::ArrayXXf a(2,2);\n", 395 | " Eigen::ArrayXXf b(2,2);\n", 396 | " a << 1,2,\n", 397 | " 3,4;\n", 398 | " b << 5,6,\n", 399 | " 7,8;\n", 400 | " std::cout << \"a * b = \" << std::endl << a * b << std::endl;\n", 401 | "}\n", 402 | "\n", 403 | "```\n", 404 | "\n", 405 | "More operations:\n", 406 | "```c++\n", 407 | "#include \n", 408 | "#include \n", 409 | "\n", 410 | "int main()\n", 411 | "{\n", 412 | " Eigen::ArrayXf a = Eigen::ArrayXf::Random(5);\n", 413 | " a *= 2;\n", 414 | " std::cout << \"a =\" << std::endl\n", 415 | " << a << std::endl;\n", 416 | " std::cout << \"a.abs() =\" << std::endl\n", 417 | " << a.abs() << std::endl;\n", 418 | " std::cout << \"a.abs().sqrt() =\" << std::endl\n", 419 | " << a.abs().sqrt() << std::endl;\n", 420 | " std::cout << \"a.min(a.abs().sqrt()) =\" << std::endl\n", 421 | " << a.min(a.abs().sqrt()) << std::endl;\n", 422 | "}\n", 423 | "```\n" 424 | ] 425 | } 426 | ], 427 | "metadata": { 428 | "kernelspec": { 429 | "display_name": "Python 3 (ipykernel)", 430 | "language": "python", 431 | "name": "python3" 432 | }, 433 | "language_info": { 434 | "codemirror_mode": { 435 | "name": "ipython", 436 | "version": 3 437 | }, 438 | "file_extension": ".py", 439 | "mimetype": "text/x-python", 440 | "name": "python", 441 | "nbconvert_exporter": "python", 442 | "pygments_lexer": "ipython3", 443 | "version": "3.12.8" 444 | } 445 | }, 446 | "nbformat": 4, 447 | "nbformat_minor": 5 448 | } 449 | -------------------------------------------------------------------------------- /07-LinearAlgebra/fig/linear-example-01.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/07-LinearAlgebra/fig/linear-example-01.pdf -------------------------------------------------------------------------------- /07-LinearAlgebra/fig/linear-example-01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/07-LinearAlgebra/fig/linear-example-01.png -------------------------------------------------------------------------------- /07-LinearAlgebra/fig/linear-example-03.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/07-LinearAlgebra/fig/linear-example-03.pdf -------------------------------------------------------------------------------- /07-LinearAlgebra/fig/linear-example-03.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/07-LinearAlgebra/fig/linear-example-03.png -------------------------------------------------------------------------------- /07-LinearAlgebra/fig/linear-example-04-T-B.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/07-LinearAlgebra/fig/linear-example-04-T-B.pdf -------------------------------------------------------------------------------- /07-LinearAlgebra/fig/linear-example-04-T-B.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/07-LinearAlgebra/fig/linear-example-04-T-B.png -------------------------------------------------------------------------------- /07-LinearAlgebra/fig/linear-example-04-T.pdf: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/07-LinearAlgebra/fig/linear-example-04-T.pdf -------------------------------------------------------------------------------- /07-LinearAlgebra/fig/linear-example-04-T.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/07-LinearAlgebra/fig/linear-example-04-T.png -------------------------------------------------------------------------------- /07-LinearAlgebra/fig/problem-05.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/07-LinearAlgebra/fig/problem-05.png -------------------------------------------------------------------------------- /07-LinearAlgebra/fig/problem-06.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/07-LinearAlgebra/fig/problem-06.png -------------------------------------------------------------------------------- /07-LinearAlgebra/fig/problem-08.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/07-LinearAlgebra/fig/problem-08.png -------------------------------------------------------------------------------- /09-ODE-IVP-OOP-MolecularDynamics/fig/sfml.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/09-ODE-IVP-OOP-MolecularDynamics/fig/sfml.png -------------------------------------------------------------------------------- /10-RandomSystems/RandomNumbersInSimulations.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "a520db74-90df-463a-abea-49ff07165a80", 6 | "metadata": {}, 7 | "source": [ 8 | "# Random numbers in simulations\n", 9 | "---\n", 10 | "REFS: \n", 11 | "- Boudreau, Applied Computational Physics\n", 12 | "- Heath, Scientific Computing\n", 13 | "- Landau y Paez, Computational physics, problem solving with computers\n", 14 | "- Anagnostoupulos, A practical introduction to computational physics and scientific computing\n", 15 | "- Ward, Numerical Mathematicas and Computing\n", 16 | "- Beu, Introduction to Numerical Programming - A practical guide for scientist and engineers using python and C/C++ \n", 17 | "\n", 18 | "The so-called [MonteCarlo methods](https://en.wikipedia.org/wiki/Monte_Carlo_method) are computational methods that use random numbers to perform computations or simulations. Applications are immense, from traffic simulations, to atomic systems, to pedestrian crowds, to probabilistic computations, to neutron scattering in nuclear shielding, to materials design, and so on. \n" 19 | ] 20 | }, 21 | { 22 | "cell_type": "markdown", 23 | "id": "a050eab8-98d5-47bb-b6b7-e06f1bc12bbf", 24 | "metadata": { 25 | "deletable": false, 26 | "editable": false, 27 | "nbgrader": { 28 | "cell_type": "markdown", 29 | "checksum": "0b6039cba006a71186f37231891873d0", 30 | "grade": false, 31 | "grade_id": "cell-ecbb686dc7865acd", 32 | "locked": true, 33 | "points": 0, 34 | "schema_version": 3, 35 | "solution": false, 36 | "task": true 37 | } 38 | }, 39 | "source": [ 40 | "## Loaded dice (Ward)\n", 41 | "Imagine that you have a loaded dice, where each face has different probability to appear (for a fair dice, it should be equal prob). For the present example, let's assume the following\n", 42 | "\n", 43 | "|Outcome|1|2|3|4|5|6|\n", 44 | "|-|-|-|-|-|-|-|\n", 45 | "|Probability|0.2|0.14|0.22|0.16|0.17|0.11|\n", 46 | "\n", 47 | "Think of a way to simulate the loaded dice (hint: using a uniform random number in $[0, 1)$, you can split the unit interval in terms of the previous probabilities to choose each face at each throw). Launch the simulated die 10000 times and print the prob per face. \n", 48 | "\n", 49 | "```c++\n", 50 | "#include \n", 51 | "#include \n", 52 | "#include \n", 53 | "#include \n", 54 | "#include \n", 55 | "\n", 56 | "void check_args(int argc, char **argv);\n", 57 | "void generate_samples_loaded_dice(const int seed, const int nsamples, const std::string & fname);\n", 58 | "\n", 59 | "int main(int argc, char **argv)\n", 60 | "{\n", 61 | "\tcheck_args(argc, argv);\n", 62 | "\n", 63 | "\tconst int SEED = std::stoi(argv[1]);\n", 64 | "\tconst int SAMPLES = std::stoi(argv[2]);\n", 65 | "\tconst std::string FNAME = argv[3];\n", 66 | " // MAYBE LOADED PROBS CAN ALSO BE READ\n", 67 | "\n", 68 | "\tgenerate_samples_loaded_dice(SEED, SAMPLES, FNAME);\n", 69 | "\n", 70 | "\treturn 0;\n", 71 | "}\n", 72 | "\n", 73 | "void check_args(int argc, char **argv)\n", 74 | "{\n", 75 | "\tif (4 != argc) {\n", 76 | "\t\tstd::cerr << \"Error. Usage: \\n\" << argv[0] << \" SEED SAMPLES FNAME\\n\";\n", 77 | "\t\texit(1);\n", 78 | "\t}\n", 79 | "}\n", 80 | "\n", 81 | "void generate_samples_loaded_dice(const int seed, int const nsamples, const std::string & fname)\n", 82 | "{\n", 83 | " // TODO\n", 84 | "}\n", 85 | "\n", 86 | "```\n", 87 | "\n", 88 | "
EXERCISE
\n", 89 | "\n", 90 | "- [ ] Read the loaded probs from the command line.\n", 91 | "- [ ] Read the loaded probs from a file. Maybe a configuration file using something like toml, yaml or json. \n" 92 | ] 93 | }, 94 | { 95 | "cell_type": "markdown", 96 | "id": "ccfd07df-5faf-44e3-b58f-0da7327ff2a4", 97 | "metadata": { 98 | "deletable": false, 99 | "editable": false, 100 | "nbgrader": { 101 | "cell_type": "markdown", 102 | "checksum": "fe0c8a2055dad17a2d695286144d4a0a", 103 | "grade": false, 104 | "grade_id": "cell-77bbde0fd7bd004d", 105 | "locked": true, 106 | "points": 0, 107 | "schema_version": 3, 108 | "solution": false, 109 | "task": true 110 | } 111 | }, 112 | "source": [ 113 | "## Buffon needle problem\n", 114 | "\"In probability theory, Buffon's needle problem is a question first posed in the 18th century by Georges-Louis Leclerc, Comte de Buffon:[1]\n", 115 | "\n", 116 | " Suppose we have a floor made of parallel strips of wood, each the same width, and we drop a needle onto the floor. What is the probability that the needle will lie across a line between two strips?\"\n", 117 | "\n", 118 | "From: \n", 119 | "\n", 120 | "For this problem, we will use a needle shorter than the lines' separation. We will put the needle center as a random variable, and its orientation will be another random variable. \n", 121 | "\n", 122 | "\"Needle\n", 123 | "\n", 124 | "From: Ward\n", 125 | "\n", 126 | "The theoretical solution predicts that \n", 127 | "\\begin{equation}\n", 128 | "p = \\frac{2}{\\pi}\\frac{l}{t},\n", 129 | "\\end{equation}\n", 130 | "where $l$ is the needle lenght and $t$ the lines separation. \n", 131 | "\n", 132 | "Let's use $l= t= 1$. Simulate `nsamples` (at least 50000) throws, and check the numerical probability compared with the expected one. From symmetry, let's choose $u \\in [0, 1/2)$, and $v \\in [0, \\pi/2)$. The needle intersects one of the lines if and only if $u \\le \\frac{1}{2} \\sin v$. The probability will be the number of times the condition is fulfilled, over the \n", 133 | "\n", 134 | "```c++\n", 135 | "#include \n", 136 | "#include \n", 137 | "#include \n", 138 | "#include \n", 139 | "#include \n", 140 | "#include \n", 141 | "\n", 142 | "void check_args(int argc, char **argv);\n", 143 | "void generate_samples_needle(const int seed, const int nsamples);\n", 144 | "\n", 145 | "int main(int argc, char **argv)\n", 146 | "{\n", 147 | "\tcheck_args(argc, argv);\n", 148 | "\n", 149 | "\tconst int SEED = std::stoi(argv[1]);\n", 150 | "\tconst int SAMPLES = std::stoi(argv[2]);\n", 151 | "\n", 152 | "\tgenerate_samples_needle(SEED, SAMPLES);\n", 153 | "\n", 154 | "\treturn 0;\n", 155 | "}\n", 156 | "\n", 157 | "void check_args(int argc, char **argv)\n", 158 | "{\n", 159 | "\tif (3 != argc) {\n", 160 | "\t\tstd::cerr << \"Error. Usage: \\n\" << argv[0] << \" SEED SAMPLES\\n\";\n", 161 | "\t\texit(1);\n", 162 | "\t}\n", 163 | "}\n", 164 | "\n", 165 | "void generate_samples_needle(const int seed, int const nsamples)\n", 166 | "{\n", 167 | " // TODO\n", 168 | "}\n", 169 | "\n", 170 | "```\n", 171 | "\n", 172 | "
EXERCISE
\n", 173 | "\n", 174 | "- [ ] Plot the percentual diff between the expected and computed value as a function of the number of samples.\n", 175 | "- [ ] How many samples will be needed to get a $10^{-8}$ relative precision?\n", 176 | "\n" 177 | ] 178 | }, 179 | { 180 | "attachments": {}, 181 | "cell_type": "markdown", 182 | "id": "409dc303-2f54-49f0-9288-0751fcb323c1", 183 | "metadata": {}, 184 | "source": [ 185 | "## Neutron shielding\n", 186 | "Imagine a flux of neutrons penetrating a lead wall of a given thick. Your task is to estimate the fraction of neutrons that crossed the wall. \n", 187 | "\n", 188 | "\"Neutron\n", 189 | "\n", 190 | "Neutrons enter the wall perpendicularly, but then they rebound in random directions, advancing a unit distance after each collision. Each collision dissipates kinetic energy, and we will assume that it is zero after 8 collisions. Compute the fraction of neutrons that cross the wall.\n", 191 | "\n", 192 | "\n", 193 | "\n", 194 | "\n", 195 | "
EXERCISE
\n", 196 | "\n", 197 | "- [ ] Compute the fraction as a function of the distance.\n", 198 | "- [ ] Compute the fraction as a function of the number of collisions to loose all kinetic energy, with fixed distance. \n", 199 | "\n" 200 | ] 201 | }, 202 | { 203 | "cell_type": "markdown", 204 | "id": "253b545b-3309-4c48-b194-9890ef28b122", 205 | "metadata": { 206 | "deletable": false, 207 | "editable": false, 208 | "nbgrader": { 209 | "cell_type": "markdown", 210 | "checksum": "c6b5585bb8b7fceb69ce6b3597949304", 211 | "grade": false, 212 | "grade_id": "cell-86b82d5c2b4738f2", 213 | "locked": true, 214 | "points": 0, 215 | "schema_version": 3, 216 | "solution": false, 217 | "task": true 218 | } 219 | }, 220 | "source": [ 221 | "## Integrals using Monte Carlo (again)\n", 222 | "Monte Carlo methods are well suited to compute multi-dimensional integrals, like \n", 223 | "\\begin{equation}\n", 224 | "I = \\int dx_1\\int dx_2\\int dx_3 \\ldots \\int x_D f(\\vec x),\n", 225 | "\\end{equation}\n", 226 | "where its numerical form can be written as\n", 227 | "\\begin{equation}\n", 228 | "I \\simeq \\sum_{i_1}^n \\sum_{i_2}^n \\sum_{i_3}^n \\ldots \\sum_{i_D}^n w_1 w_2 \\ldots w_D f(x_1, x_2, x_3, \\ldots , x_D).\n", 229 | "\\end{equation}\n", 230 | "The total number of points needed for this is about $N = n^D$. And the error, for a typical quadrature, goes like $\\epsilon_{\\text{math}} = (1/n)^p = N^{-p/D}$. This is impractical. For $D = 4$, this makes the Simpson method a first order approximation.\n", 231 | "\n", 232 | "In Monte Carlo integration, we choose points uniformly in the given region and then compute the integral. The result quality depends on the actual points chosen and its representativity on the function to be integrated. The numerical integral can be written as \n", 233 | "\\begin{equation}\n", 234 | "\\int_D f dV \\simeq V \\langle f \\rangle \\pm\\ \\sigma, \n", 235 | "\\end{equation}\n", 236 | "where \n", 237 | "\\begin{equation}\n", 238 | "\\sigma = V \\sqrt{\\frac{\\langle f^2 \\rangle - \\langle f \\rangle^2}{n}} = \\frac{V}{\\sqrt{n}} \\sigma_f\n", 239 | "\\end{equation}\n", 240 | "is the standard deviation ($\\sigma^2$ is called the variance). The error decreases as $n^{-1/2}$ regardless the dimension, which is very advantageous for $D \\ge 4$.\n", 241 | "\n", 242 | "\n", 243 | "\n", 244 | "### Importance sampling\n", 245 | "For $n=20$ and $D = 20$, computing the equipartition function\n", 246 | "\\begin{equation}\n", 247 | "Z = \\int \\ldots \\int d^3 r_1 \\ldots d^3 r_N \\exp\\left[ -\\frac{1}{k_B T}E(\\vec r_1, \\ldots, \\vec r_N)\\right]\n", 248 | "\\end{equation}\n", 249 | "requires $10^{60}$ operations, which, in a petascale supercomputer (more than $10^{16}$ flops), will take around $10^{36}$ years. Also, the actual choice of points is important. For instance, to compute points inside an hypersphere in $D$ dimensions, we sample points uniformly in the hyper cube, and the probability is \n", 250 | "\n", 251 | "\\begin{equation}\n", 252 | "P(D) = \\frac{2}{\\Gamma(D/2)} \\left(\\frac{\\sqrt{\\pi}}{2} \\right)^D, \n", 253 | "\\end{equation}\n", 254 | "which, for $D = 100$, is about $10^{-68}$, so basically all points are rejected.\n", 255 | "\n", 256 | "\n", 257 | "Therefore, it is advisable to have a procedure that allows to select points inside the region where the function is more representative. To do so, we rewritte the integral as\n", 258 | "\n", 259 | "\\begin{equation}\n", 260 | "\\int f(\\vec x) d\\vec x = \\int h(\\vec x) w(\\vec x) d\\vec x,\n", 261 | "\\end{equation}\n", 262 | "where $w(\\vec x)$ is a weight function to choose the points, and must be normalized. After that,$n$ random points are generated according to the weight function, and the integral is simply given as \n", 263 | "\n", 264 | "\\begin{equation}\n", 265 | "\\int d\\vec x f(\\vec x) \\simeq \\bar h,\n", 266 | "\\end{equation}\n", 267 | "\n", 268 | "with error\n", 269 | "\\begin{equation}\n", 270 | "\\sigma = \\sqrt{\\frac{\\bar{h^2} - (\\bar h)^2}{N-1}}.\n", 271 | "\\end{equation}\n", 272 | "\n", 273 | "There is some freedom to chose the weight function. The idea is to focus the variation in the weight function, so to make the $h$ function as constant as possible. \n", 274 | "\n", 275 | "Example (Boudreau): Let's compute the following\n", 276 | "\\begin{equation}\n", 277 | "I = \\int_0^\\infty dx\\ x^2 e^{-x},\n", 278 | "\\end{equation}\n", 279 | "\n", 280 | "Using three weight functions as follows:\n", 281 | "|$w(x)$|$h(x)$|\n", 282 | "|-|-|\n", 283 | "|$e^{-x}$|$x^2$|\n", 284 | "|$xe^{-x}$|$x$|\n", 285 | "|$x^2e^{-x}$|1|\n", 286 | "\n", 287 | "Implement a program that prints the result, and the error, comparing with the actual value of 2.\n", 288 | "\n", 289 | "```c++\n", 290 | "#include \n", 291 | "#include \n", 292 | "#include \n", 293 | "#include \n", 294 | "#include \n", 295 | "#include \n", 296 | "\n", 297 | "void check_args(int argc, char **argv);\n", 298 | "void importance_sampling0(const int seed, const int nsamples);\n", 299 | "void importance_sampling1(const int seed, const int nsamples);\n", 300 | "void importance_sampling2(const int seed, const int nsamples);\n", 301 | "\n", 302 | "int main(int argc, char **argv)\n", 303 | "{\n", 304 | "\tcheck_args(argc, argv);\n", 305 | "\n", 306 | "\tconst int SEED = std::stoi(argv[1]);\n", 307 | "\tconst int SAMPLES = std::stoi(argv[2]);\n", 308 | "\n", 309 | "\timportance_sampling0(SEED, SAMPLES);\n", 310 | "\timportance_sampling1(SEED, SAMPLES);\n", 311 | "\timportance_sampling2(SEED, SAMPLES);\n", 312 | "\n", 313 | "\treturn 0;\n", 314 | "}\n", 315 | "\n", 316 | "void check_args(int argc, char **argv)\n", 317 | "{\n", 318 | "\tif (3 != argc) {\n", 319 | "\t\tstd::cerr << \"Error. Usage: \\n\" << argv[0] << \" SEED SAMPLES\\n\";\n", 320 | "\t\texit(1);\n", 321 | "\t}\n", 322 | "}\n", 323 | "\n", 324 | "void importance_sampling0(const int seed, int const nsamples)\n", 325 | "{\n", 326 | " // TODO\n", 327 | " // define aux random number generators\n", 328 | "\tstd::mt19937 gen(seed); // random bit generator\n", 329 | "\tstd::exponential_distribution w(1.0); // first weight function to test\n", 330 | "\tauto h = [](double x){ return x*x; }; // its integrand\n", 331 | "\tdouble sum = 0.0, sum_2 = 0.0;\n", 332 | "\tfor (int ii = 0; ii < nsamples; ++ii) {\n", 333 | "\t\tdouble x = w(gen); // generate a random number\n", 334 | "\t\tdouble val = h(x); // evaluate the integrand\n", 335 | "\t\tsum += val; // accumulate the sum\n", 336 | "\t\tsum_2 += val*val; // accumulate the sum\n", 337 | "\t}\n", 338 | "\tdouble mean = sum / nsamples; // compute the mean\n", 339 | "\tdouble var = sum_2 / nsamples - mean * mean; // compute the variance\n", 340 | "\tdouble sigma = std::sqrt(var/(nsamples-1)); // compute the standard deviation\n", 341 | "\tdouble rel_err = std::fabs(1.0 - mean/2.0);\n", 342 | "\tstd::printf(\"%20.16e +- %20.16e\\t%20.16e\\n\", mean, sigma, rel_err);\n", 343 | "\n", 344 | "}\n", 345 | "\n", 346 | "void importance_sampling1(const int seed, int const nsamples)\n", 347 | "{\n", 348 | " // TODO\n", 349 | " // define aux random number generators\n", 350 | "\tstd::mt19937 gen(seed); // random bit generator\n", 351 | "}\n", 352 | "\n", 353 | "\n", 354 | "void importance_sampling2(const int seed, int const nsamples)\n", 355 | "{\n", 356 | " // TODO\n", 357 | " // define aux random number generators\n", 358 | "\tstd::mt19937 gen(seed); // random bit generator\n", 359 | "}\n", 360 | "```\n" 361 | ] 362 | }, 363 | { 364 | "cell_type": "markdown", 365 | "id": "485e539d-d934-4e06-918a-882899359722", 366 | "metadata": {}, 367 | "source": [ 368 | "## The random walk\n", 369 | "The [random walk](https://en.wikipedia.org/wiki/Random_walk), is an example of [random process](https://en.wikipedia.org/wiki/Stochastic_process). It has been used in several applications: \n", 370 | "\n", 371 | "\"random\n", 372 | "\n", 373 | "\n", 374 | "We will define a grid, and our walker will choose the next position at random. We are interested in computing the mean squared distance as function of time, which is related with a diffusion process. Since we are using four next neighbors, we need to choose those directions with equal probability, with a \"fair\" dice.\n", 375 | "\n", 376 | "Write a program to simulate the random walk in 2D. Use a grid of variable sixe (read it from the command line), and perform `NSTEPS`. Print the mean square distance as a function of the iteration. What do you find?\n", 377 | "\n", 378 | "
EXERCISE
\n", 379 | "\n", 380 | "- [ ] Create a random walk in 3 and 4 dimensions. Also plot the distance as a function of time.\n", 381 | "- [ ] Self avoiding random walk: Perform a 2D random walk BUT avoid moving to a site that was already visited. Is the diffusion constant the same? what do you expect? See \n", 382 | "- [ ] Create a slight load to the positive x direction. What happens with the random walk?\n", 383 | "- [ ] Create an ensemble of random walkers. Compute the system total entropy as\n", 384 | " \\begin{equation}\n", 385 | " S = -\\sum p_i\\ln p_i,\n", 386 | " \\end{equation}\n", 387 | " where $p_i = n_i/N$ is the total number $n_i$ of walkers in cell $i$, and $N$ is the total number of walkers. Plot it as a function of time, starting from all the walkers in the center. What do you see?\n", 388 | " " 389 | ] 390 | }, 391 | { 392 | "cell_type": "code", 393 | "execution_count": null, 394 | "id": "fae87249-8a1d-4fd2-9c3f-3880fb0789ff", 395 | "metadata": {}, 396 | "outputs": [], 397 | "source": [] 398 | } 399 | ], 400 | "metadata": { 401 | "kernelspec": { 402 | "display_name": "Python 3 (ipykernel)", 403 | "language": "python", 404 | "name": "python3" 405 | }, 406 | "language_info": { 407 | "codemirror_mode": { 408 | "name": "ipython", 409 | "version": 3 410 | }, 411 | "file_extension": ".py", 412 | "mimetype": "text/x-python", 413 | "name": "python", 414 | "nbconvert_exporter": "python", 415 | "pygments_lexer": "ipython3", 416 | "version": "3.12.5" 417 | } 418 | }, 419 | "nbformat": 4, 420 | "nbformat_minor": 5 421 | } 422 | -------------------------------------------------------------------------------- /10-RandomSystems/fig-RandomNumbers/bad-lcg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/10-RandomSystems/fig-RandomNumbers/bad-lcg.png -------------------------------------------------------------------------------- /10-RandomSystems/fig-RandomNumbers/ellipse-bad.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/10-RandomSystems/fig-RandomNumbers/ellipse-bad.png -------------------------------------------------------------------------------- /10-RandomSystems/fig-RandomNumbers/ellipse-good.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/10-RandomSystems/fig-RandomNumbers/ellipse-good.png -------------------------------------------------------------------------------- /10-RandomSystems/fig-RandomNumbers/good-lcg.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/10-RandomSystems/fig-RandomNumbers/good-lcg.png -------------------------------------------------------------------------------- /10-RandomSystems/fig-RandomNumbers/triangle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/10-RandomSystems/fig-RandomNumbers/triangle.png -------------------------------------------------------------------------------- /10-RandomSystems/fig-RandomSimulations/needle.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/10-RandomSystems/fig-RandomSimulations/needle.png -------------------------------------------------------------------------------- /10-RandomSystems/fig-RandomSimulations/neutron.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/10-RandomSystems/fig-RandomSimulations/neutron.png -------------------------------------------------------------------------------- /11-IntroPython/01-IntroProgrammingPython.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "db249f1b", 6 | "metadata": { 7 | "slideshow": { 8 | "slide_type": "slide" 9 | } 10 | }, 11 | "source": [ 12 | "# Python Programming (very fast) Introduction\n", 13 | "\n", 14 | "## Importing modules\n", 15 | "Python has an extensive standard library (https://docs.python.org/3/library/) to perform several task in optimized and easy-to-use way. For basic mathematical operations you can just use the normal operators, but for other standard functions, like `sin`, you could import the standard `math` module, or , much better, use either `numpy` or `scipy` modules\n", 16 | "```python\n", 17 | "import math as m # imports the math module with an alias m\n", 18 | "# import math # imports math module but you need to use math.sin or math.cos\n", 19 | "# from math import * # DO NOT do this: exposes all inners from math\n", 20 | "\n", 21 | "x = 5.2\n", 22 | "y = m.sin(x)\n", 23 | "print(x, y)\n", 24 | "```\n", 25 | "\n", 26 | "
\n", 27 | "Exercise: Copy and execute the previous code in the following cell (use shift+enter to execute) \n", 28 | "
" 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": null, 34 | "id": "d678ca14", 35 | "metadata": { 36 | "deletable": false, 37 | "nbgrader": { 38 | "cell_type": "code", 39 | "checksum": "013f937e702eceac3ba76eed805f13eb", 40 | "grade": false, 41 | "grade_id": "cell-1d206d3930590507", 42 | "locked": false, 43 | "schema_version": 3, 44 | "solution": true, 45 | "task": false 46 | }, 47 | "slideshow": { 48 | "slide_type": "fragment" 49 | } 50 | }, 51 | "outputs": [], 52 | "source": [ 53 | "# YOUR CODE HERE\n", 54 | "raise NotImplementedError()" 55 | ] 56 | }, 57 | { 58 | "cell_type": "markdown", 59 | "id": "e764d184", 60 | "metadata": { 61 | "slideshow": { 62 | "slide_type": "slide" 63 | } 64 | }, 65 | "source": [ 66 | "
\n", 67 | "Exercise: Now replace math by numpy and execute it. Is there any difference?\n", 68 | "
" 69 | ] 70 | }, 71 | { 72 | "cell_type": "code", 73 | "execution_count": null, 74 | "id": "ae71e6e5", 75 | "metadata": { 76 | "deletable": false, 77 | "nbgrader": { 78 | "cell_type": "code", 79 | "checksum": "9da8f546de4900093f1745c47b9f3c1b", 80 | "grade": false, 81 | "grade_id": "cell-d2ac73e7587d20db", 82 | "locked": false, 83 | "schema_version": 3, 84 | "solution": true, 85 | "task": false 86 | } 87 | }, 88 | "outputs": [], 89 | "source": [ 90 | "# YOUR CODE HERE\n", 91 | "raise NotImplementedError()" 92 | ] 93 | }, 94 | { 95 | "cell_type": "markdown", 96 | "id": "a43061ac", 97 | "metadata": { 98 | "slideshow": { 99 | "slide_type": "slide" 100 | } 101 | }, 102 | "source": [ 103 | "## Looking for help\n", 104 | "What are the units of the argument for the `sin` function? Are there any other functions provided by the `numpy` module? Check the documentation using either google or, inside a notebook\n", 105 | "```\n", 106 | "help(np.sin)\n", 107 | "help(np)\n", 108 | "np.sin?\n", 109 | "```" 110 | ] 111 | }, 112 | { 113 | "cell_type": "code", 114 | "execution_count": null, 115 | "id": "fcbb3796", 116 | "metadata": { 117 | "slideshow": { 118 | "slide_type": "fragment" 119 | } 120 | }, 121 | "outputs": [], 122 | "source": [ 123 | "import numpy as np\n", 124 | "help(np.sin)" 125 | ] 126 | }, 127 | { 128 | "cell_type": "markdown", 129 | "id": "9325c476", 130 | "metadata": { 131 | "slideshow": { 132 | "slide_type": "slide" 133 | } 134 | }, 135 | "source": [ 136 | "## Printing and reading to and from the screen\n", 137 | "\n", 138 | "You have already seen how to print to the screen. To read, you can use the function call ```input```. Try it:" 139 | ] 140 | }, 141 | { 142 | "cell_type": "code", 143 | "execution_count": null, 144 | "id": "9f802577", 145 | "metadata": { 146 | "slideshow": { 147 | "slide_type": "subslide" 148 | } 149 | }, 150 | "outputs": [], 151 | "source": [ 152 | "var = input(\"Please write something :\\t\")\n", 153 | "print(\"You have written : \" + var)\n", 154 | "print(f\"You have written : {var}\") # uses a f-string: https://realpython.com/python-f-strings/" 155 | ] 156 | }, 157 | { 158 | "cell_type": "markdown", 159 | "id": "a3661b56", 160 | "metadata": { 161 | "slideshow": { 162 | "slide_type": "slide" 163 | } 164 | }, 165 | "source": [ 166 | "You can also format the printing string, like you have done in c/c++ . For example, you can write something like" 167 | ] 168 | }, 169 | { 170 | "cell_type": "code", 171 | "execution_count": null, 172 | "id": "ef0a991d", 173 | "metadata": { 174 | "slideshow": { 175 | "slide_type": "fragment" 176 | } 177 | }, 178 | "outputs": [], 179 | "source": [ 180 | "x = 5\n", 181 | "y = 2.34\n", 182 | "print(\"x = %04d \\t y = %.1f \\n y=%20.16e\\n\"%(x, y, y))\n", 183 | "print(f\"x = {x:04d} \\t y = {y:.1f} \\n y={y:20.16e}\")" 184 | ] 185 | }, 186 | { 187 | "cell_type": "markdown", 188 | "id": "a524a70e", 189 | "metadata": { 190 | "slideshow": { 191 | "slide_type": "skip" 192 | } 193 | }, 194 | "source": [ 195 | "Note: if you need to manipulate strings and numbers, you should cast the number to string by using ```str```, as in ```str(x)``` ." 196 | ] 197 | }, 198 | { 199 | "cell_type": "markdown", 200 | "id": "38bfdca5", 201 | "metadata": {}, 202 | "source": [ 203 | "
\n", 204 | "Exercise: Print the sum of two numbers with 5 decimals, filled with 0, and in field of 10 spaces \n", 205 | "
" 206 | ] 207 | }, 208 | { 209 | "cell_type": "code", 210 | "execution_count": null, 211 | "id": "ada119c8", 212 | "metadata": { 213 | "deletable": false, 214 | "nbgrader": { 215 | "cell_type": "code", 216 | "checksum": "466c25d15691e643883b9259e27f0a3c", 217 | "grade": false, 218 | "grade_id": "squares", 219 | "locked": false, 220 | "schema_version": 3, 221 | "solution": true 222 | }, 223 | "tags": [] 224 | }, 225 | "outputs": [], 226 | "source": [ 227 | "x = 32.6\n", 228 | "y = -4.7\n", 229 | "# YOUR CODE HERE\n", 230 | "raise NotImplementedError()" 231 | ] 232 | }, 233 | { 234 | "cell_type": "markdown", 235 | "id": "d86019ad", 236 | "metadata": { 237 | "slideshow": { 238 | "slide_type": "slide" 239 | } 240 | }, 241 | "source": [ 242 | "## Selection structures : `if`, `if else`\n", 243 | "\n", 244 | "This is a simple example on how to use if to select from several options" 245 | ] 246 | }, 247 | { 248 | "cell_type": "code", 249 | "execution_count": null, 250 | "id": "7dfc52e0", 251 | "metadata": { 252 | "slideshow": { 253 | "slide_type": "fragment" 254 | } 255 | }, 256 | "outputs": [], 257 | "source": [ 258 | "m = 5\n", 259 | "if m < 1:\n", 260 | " print (f\"{m} is smaller than 1\")\n", 261 | "elif 1 <= m <= 4:\n", 262 | " print (f\"{m} is in between 1 and 4\")\n", 263 | "else :\n", 264 | " print (f\"{m} is larger than 4\")" 265 | ] 266 | }, 267 | { 268 | "cell_type": "markdown", 269 | "id": "733dc92b", 270 | "metadata": { 271 | "slideshow": { 272 | "slide_type": "subslide" 273 | } 274 | }, 275 | "source": [ 276 | "You can also compare values directly, or even compare several values" 277 | ] 278 | }, 279 | { 280 | "cell_type": "code", 281 | "execution_count": null, 282 | "id": "a754eb61", 283 | "metadata": { 284 | "ExecuteTime": { 285 | "end_time": "2018-09-13T19:07:18.645052Z", 286 | "start_time": "2018-09-13T19:07:18.625357Z" 287 | }, 288 | "slideshow": { 289 | "slide_type": "fragment" 290 | } 291 | }, 292 | "outputs": [], 293 | "source": [ 294 | "print(2 == 3)\n", 295 | "print(2 == 2 and 3 > 9)\n", 296 | "print([2, 3] == [3, 2])\n", 297 | "print([2, 3] == [2, 2])\n", 298 | "print([2, 3] == [2, 3])" 299 | ] 300 | }, 301 | { 302 | "cell_type": "markdown", 303 | "id": "660801e8", 304 | "metadata": {}, 305 | "source": [ 306 | "
\n", 307 | "Exercise: Read a number and indicate if the number is even or odd \n", 308 | "
" 309 | ] 310 | }, 311 | { 312 | "cell_type": "code", 313 | "execution_count": null, 314 | "id": "6cc9dedc", 315 | "metadata": { 316 | "deletable": false, 317 | "nbgrader": { 318 | "cell_type": "code", 319 | "checksum": "a5ec35ebd41df13616479519c30fb84e", 320 | "grade": false, 321 | "grade_id": "cell-8ccf3fbf15c165e4", 322 | "locked": false, 323 | "schema_version": 3, 324 | "solution": true, 325 | "task": false 326 | } 327 | }, 328 | "outputs": [], 329 | "source": [ 330 | "# YOUR CODE HERE\n", 331 | "raise NotImplementedError()" 332 | ] 333 | }, 334 | { 335 | "cell_type": "markdown", 336 | "id": "1c8de545", 337 | "metadata": { 338 | "slideshow": { 339 | "slide_type": "slide" 340 | } 341 | }, 342 | "source": [ 343 | "## Loop structures: for and while" 344 | ] 345 | }, 346 | { 347 | "cell_type": "code", 348 | "execution_count": null, 349 | "id": "1a551dfe", 350 | "metadata": { 351 | "slideshow": { 352 | "slide_type": "fragment" 353 | } 354 | }, 355 | "outputs": [], 356 | "source": [ 357 | "N = 5\n", 358 | "i = 0\n", 359 | "while i < N:\n", 360 | " print (i, end=\" \")\n", 361 | " i = i+1" 362 | ] 363 | }, 364 | { 365 | "cell_type": "code", 366 | "execution_count": null, 367 | "id": "9bfd3b21", 368 | "metadata": {}, 369 | "outputs": [], 370 | "source": [ 371 | "for ii in range(1, 10):\n", 372 | " print(f\"{ii}\", end=\" \")" 373 | ] 374 | }, 375 | { 376 | "cell_type": "code", 377 | "execution_count": null, 378 | "id": "2283e079", 379 | "metadata": { 380 | "slideshow": { 381 | "slide_type": "fragment" 382 | } 383 | }, 384 | "outputs": [], 385 | "source": [ 386 | "name = \"My name\" # a string is an array for characters\n", 387 | "for c in name:\n", 388 | " print (c, end=\"-\")\n", 389 | "print()\n", 390 | "print(name[0])\n", 391 | "print(name[-1])" 392 | ] 393 | }, 394 | { 395 | "cell_type": "markdown", 396 | "id": "e69a4278", 397 | "metadata": {}, 398 | "source": [ 399 | "
\n", 400 | "Exercise: Print values from 0.0, to 1.0 (exclusive), in steps of 0.05 \n", 401 | "
" 402 | ] 403 | }, 404 | { 405 | "cell_type": "code", 406 | "execution_count": null, 407 | "id": "a65204a7", 408 | "metadata": { 409 | "deletable": false, 410 | "nbgrader": { 411 | "cell_type": "code", 412 | "checksum": "3a81dc7c34d9e4c7b7882e47d39744bc", 413 | "grade": false, 414 | "grade_id": "cell-a83db8b3e865fef8", 415 | "locked": false, 416 | "schema_version": 3, 417 | "solution": true, 418 | "task": false 419 | } 420 | }, 421 | "outputs": [], 422 | "source": [ 423 | "# ii = 0.0\n", 424 | "# while ii < 1.0:\n", 425 | "# print(ii)\n", 426 | "# ii = ii + 0.05\n", 427 | "# YOUR CODE HERE\n", 428 | "raise NotImplementedError()" 429 | ] 430 | }, 431 | { 432 | "cell_type": "markdown", 433 | "id": "6068369a", 434 | "metadata": {}, 435 | "source": [ 436 | "
\n", 437 | "Exercise: Now use numpy to do the same (check for the linspace function) \n", 438 | "
" 439 | ] 440 | }, 441 | { 442 | "cell_type": "code", 443 | "execution_count": null, 444 | "id": "ca6d48dd", 445 | "metadata": { 446 | "deletable": false, 447 | "nbgrader": { 448 | "cell_type": "code", 449 | "checksum": "736337b68b68d7d3c52bc14f5b4adb5d", 450 | "grade": false, 451 | "grade_id": "cell-4d62b200c665b8ab", 452 | "locked": false, 453 | "schema_version": 3, 454 | "solution": true, 455 | "task": false 456 | } 457 | }, 458 | "outputs": [], 459 | "source": [ 460 | "# YOUR CODE HERE\n", 461 | "raise NotImplementedError()" 462 | ] 463 | }, 464 | { 465 | "cell_type": "markdown", 466 | "id": "6933e7c3", 467 | "metadata": { 468 | "slideshow": { 469 | "slide_type": "slide" 470 | } 471 | }, 472 | "source": [ 473 | "## How to declare functions\n", 474 | "Functions are the next construct necessary for the a good program design. A function should be defined by using the keyword ```def``` ." 475 | ] 476 | }, 477 | { 478 | "cell_type": "code", 479 | "execution_count": null, 480 | "id": "b73ea2a6", 481 | "metadata": { 482 | "slideshow": { 483 | "slide_type": "fragment" 484 | } 485 | }, 486 | "outputs": [], 487 | "source": [ 488 | "def my_function() : \n", 489 | " print (\"I am the function\")\n", 490 | " \n", 491 | "my_function() # this calls the function \n" 492 | ] 493 | }, 494 | { 495 | "cell_type": "code", 496 | "execution_count": null, 497 | "id": "65b0bb39", 498 | "metadata": { 499 | "slideshow": { 500 | "slide_type": "subslide" 501 | } 502 | }, 503 | "outputs": [], 504 | "source": [ 505 | "# this shows how to pass arguments\n", 506 | "def my_function(x):\n", 507 | " print (f\"Value of argument is {x}\")\n", 508 | " \n", 509 | "#my_function() # error, requires argument\n", 510 | "my_function(-3)\n", 511 | "my_function(0.9)\n" 512 | ] 513 | }, 514 | { 515 | "cell_type": "code", 516 | "execution_count": null, 517 | "id": "ec9123b1", 518 | "metadata": { 519 | "slideshow": { 520 | "slide_type": "subslide" 521 | } 522 | }, 523 | "outputs": [], 524 | "source": [ 525 | "# this shows how to pass arguments, and assign default values\n", 526 | "def my_function(x = 0):\n", 527 | " print (f\"Value of argument is {x}\")\n", 528 | " \n", 529 | "my_function() # no longer an error\n", 530 | "my_function(-3)" 531 | ] 532 | }, 533 | { 534 | "cell_type": "code", 535 | "execution_count": null, 536 | "id": "b309a7ed", 537 | "metadata": { 538 | "slideshow": { 539 | "slide_type": "subslide" 540 | } 541 | }, 542 | "outputs": [], 543 | "source": [ 544 | "# this shows how to pass arguments, assign default values, and also calls by named arguments\n", 545 | "def my_function(x = 0, y = 1):\n", 546 | " print (\"Calling my_function\")\n", 547 | " print (\"x \" + str(x))\n", 548 | " print (\"y \" + str(y))\n", 549 | " \n", 550 | "my_function() # no longer an error\n", 551 | "my_function(-3, 2) # x = -3, y = -2\n", 552 | "my_function(y=-3, x=2) # x = 2, y = -3" 553 | ] 554 | }, 555 | { 556 | "cell_type": "markdown", 557 | "id": "32e324e1", 558 | "metadata": {}, 559 | "source": [ 560 | "## Exercises" 561 | ] 562 | }, 563 | { 564 | "cell_type": "markdown", 565 | "id": "ad127444", 566 | "metadata": { 567 | "tags": [] 568 | }, 569 | "source": [ 570 | "### Convert from Farenheit to Celcius\n", 571 | "Write a function that receives a temperature in F and prints it in C " 572 | ] 573 | }, 574 | { 575 | "cell_type": "code", 576 | "execution_count": null, 577 | "id": "37a2ed2c", 578 | "metadata": { 579 | "deletable": false, 580 | "nbgrader": { 581 | "cell_type": "code", 582 | "checksum": "102dd30e077fdbba266c1887ec95ad50", 583 | "grade": false, 584 | "grade_id": "cell-6d72db8e857ab57e", 585 | "locked": false, 586 | "schema_version": 3, 587 | "solution": true, 588 | "task": false 589 | } 590 | }, 591 | "outputs": [], 592 | "source": [ 593 | "def FtoC(f):\n", 594 | "# YOUR CODE HERE\n", 595 | "raise NotImplementedError()" 596 | ] 597 | }, 598 | { 599 | "cell_type": "code", 600 | "execution_count": null, 601 | "id": "d521b907", 602 | "metadata": { 603 | "deletable": false, 604 | "editable": false, 605 | "nbgrader": { 606 | "cell_type": "code", 607 | "checksum": "8673e7b1bc643c30c3531a223ea15e18", 608 | "grade": true, 609 | "grade_id": "cell-0764b89cea883781", 610 | "locked": true, 611 | "points": 0, 612 | "schema_version": 3, 613 | "solution": false, 614 | "task": false 615 | } 616 | }, 617 | "outputs": [], 618 | "source": [ 619 | "assert FtoC(0) == \"The temperature 0 F is equivalent to -17.78 C\"\n", 620 | "assert FtoC(10.3) == \"The temperature 10.3 F is equivalent to -12.06 C\"" 621 | ] 622 | }, 623 | { 624 | "cell_type": "markdown", 625 | "id": "45050b4b", 626 | "metadata": {}, 627 | "source": [ 628 | "### Triangle vertexes\n", 629 | "The coordinates for the vertexes of a given triangle are written into a file in the form \\begin{align*}x_1\\ \\ \\ y_1\\\\x_2\\ \\ \\ y_2\\\\x_3\\ \\ \\ y_3 \\end{align*} Write a program that reads this values, and computes the area of the triangle, defined as $$ A = \\frac{1}{2}[x_2y_3 - x_3y_2 - x_1y_3 + x_3y_1 + x_1y_2 - x_2y_1]$$. Use functions." 630 | ] 631 | }, 632 | { 633 | "cell_type": "markdown", 634 | "id": "2e09c8b2-6520-462c-b9a3-f0a96d824b1c", 635 | "metadata": {}, 636 | "source": [ 637 | "### RC circuit\n", 638 | "Write a Python program that uses a loop to simulate the behavior of an RC circuit. The program should ask the user for the resistance and capacitance values of the circuit and should calculate the voltage across the capacitor as a function of time. The program should then create a plot of the voltage across the capacitor versus time." 639 | ] 640 | }, 641 | { 642 | "cell_type": "markdown", 643 | "id": "aa4f189f-5587-4dc9-8878-3e1766f204a5", 644 | "metadata": {}, 645 | "source": [ 646 | "### Spring system\n", 647 | "Write a Python program that uses a loop to simulate the motion of a mass-spring system. The program should ask the user for the mass of the object, the spring constant, and the initial displacement from equilibrium. The program should then calculate the position of the object as a function of time and create a plot of the position versus time." 648 | ] 649 | }, 650 | { 651 | "cell_type": "markdown", 652 | "id": "e6384411-9c0c-470e-a170-b0f57de59042", 653 | "metadata": {}, 654 | "source": [ 655 | "### Projectile\n", 656 | "Write a Python program that uses a loop to simulate the motion of a projectile under the influence of gravity. The program should ask the user for the initial velocity and launch angle of the projectile, and should calculate the trajectory of the projectile over time. The program should then create a plot of the trajectory of the projectile. Use the Euler integration algorithm to compute the next position and velocity. Compare adding a damping linear force with air. " 657 | ] 658 | }, 659 | { 660 | "cell_type": "markdown", 661 | "id": "e0f3e175-48e7-4e29-8103-a7b4b5d06179", 662 | "metadata": {}, 663 | "source": [ 664 | "### Random numbers\n", 665 | "Write a Python program that reads three integers N, lower, upper, and generates a list of N random integers between lower and upper, inclusive. The program should then print out the number of integers in the list that are even and the number of integers that are odd. Finally, the program should create a bar chart that shows the number of even and odd integers in the list. Then create 4 plots with increasing N showing that limit distribution of even and odd numbers." 666 | ] 667 | }, 668 | { 669 | "cell_type": "markdown", 670 | "id": "bccef613-630c-4df5-8cd7-a08c88c96993", 671 | "metadata": {}, 672 | "source": [ 673 | "### Heatmap\n", 674 | "\n", 675 | "Write a Python function that takes an integer n as input and returns a NumPy array of size n x n, where the elements of the array are random integers between lower and upper, which are also arguments of the function. Write a second function that takes the NumPy array as input and creates a heatmap of the array. Use these functions to create a program that generates a mxm NumPy array of random integers and displays it as a heatmap. Use several m\n" 676 | ] 677 | }, 678 | { 679 | "cell_type": "markdown", 680 | "id": "d24e7a08-aced-4f59-a25f-e5622419892e", 681 | "metadata": {}, 682 | "source": [ 683 | "### Fitting with scipy\n", 684 | "Here we will learn how to perform a non-linear fit. To do so, we will generate some random data and then fit it. First, create a function that represents the theoretical trend that you want to fit. Now create two numpy arrays, xdata and ydata. For xdata use the linspace function on the range you are interested in. For ydata use the theoretical function and add a gaussian noise for each point. Now use the scipy.curve_fit function to fit the data, and print the fit parameters and their errors. Plot both the data and the fit." 685 | ] 686 | }, 687 | { 688 | "cell_type": "code", 689 | "execution_count": null, 690 | "id": "eb44e16e-1b88-49b3-b72f-154cb332b25e", 691 | "metadata": {}, 692 | "outputs": [], 693 | "source": [] 694 | } 695 | ], 696 | "metadata": { 697 | "kernelspec": { 698 | "display_name": "Python 3 (ipykernel)", 699 | "language": "python", 700 | "name": "python3" 701 | }, 702 | "language_info": { 703 | "codemirror_mode": { 704 | "name": "ipython", 705 | "version": 3 706 | }, 707 | "file_extension": ".py", 708 | "mimetype": "text/x-python", 709 | "name": "python", 710 | "nbconvert_exporter": "python", 711 | "pygments_lexer": "ipython3", 712 | "version": "3.12.6" 713 | }, 714 | "latex_envs": { 715 | "LaTeX_envs_menu_present": true, 716 | "autoclose": true, 717 | "autocomplete": true, 718 | "bibliofile": "biblio.bib", 719 | "cite_by": "apalike", 720 | "current_citInitial": 1, 721 | "eqLabelWithNumbers": true, 722 | "eqNumInitial": 1, 723 | "hotkeys": { 724 | "equation": "Ctrl-E", 725 | "itemize": "Ctrl-I" 726 | }, 727 | "labels_anchors": false, 728 | "latex_user_defs": false, 729 | "report_style_numbering": false, 730 | "user_envs_cfg": false 731 | }, 732 | "toc": { 733 | "base_numbering": 1, 734 | "nav_menu": {}, 735 | "number_sections": true, 736 | "sideBar": true, 737 | "skip_h1_title": false, 738 | "title_cell": "Table of Contents", 739 | "title_sidebar": "Contents", 740 | "toc_cell": false, 741 | "toc_position": {}, 742 | "toc_section_display": true, 743 | "toc_window_display": true 744 | }, 745 | "varInspector": { 746 | "cols": { 747 | "lenName": 16, 748 | "lenType": 16, 749 | "lenVar": 40 750 | }, 751 | "kernels_config": { 752 | "python": { 753 | "delete_cmd_postfix": "", 754 | "delete_cmd_prefix": "del ", 755 | "library": "var_list.py", 756 | "varRefreshCmd": "print(var_dic_list())" 757 | }, 758 | "r": { 759 | "delete_cmd_postfix": ") ", 760 | "delete_cmd_prefix": "rm(", 761 | "library": "var_list.r", 762 | "varRefreshCmd": "cat(var_dic_list()) " 763 | } 764 | }, 765 | "types_to_exclude": [ 766 | "module", 767 | "function", 768 | "builtin_function_or_method", 769 | "instance", 770 | "_Feature" 771 | ], 772 | "window_display": false 773 | } 774 | }, 775 | "nbformat": 4, 776 | "nbformat_minor": 5 777 | } 778 | -------------------------------------------------------------------------------- /11-IntroPython/fig/chelsea-zoom-green.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/11-IntroPython/fig/chelsea-zoom-green.jpg -------------------------------------------------------------------------------- /11-IntroPython/fig/kitty-bad-gray.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/11-IntroPython/fig/kitty-bad-gray.jpg -------------------------------------------------------------------------------- /11-IntroPython/fig/kitty-blue.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/11-IntroPython/fig/kitty-blue.jpg -------------------------------------------------------------------------------- /11-IntroPython/fig/kitty-good-gray.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/11-IntroPython/fig/kitty-good-gray.jpg -------------------------------------------------------------------------------- /11-IntroPython/fig/kitty.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/11-IntroPython/fig/kitty.jpg -------------------------------------------------------------------------------- /11-IntroPython/fig/slicing.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/11-IntroPython/fig/slicing.png -------------------------------------------------------------------------------- /11-IntroPython/fig/subplots.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/iluvatar1/ProgCPP-lectures-jupyter/7370820c76eef13426376c04edbc04c02c4d8927/11-IntroPython/fig/subplots.png -------------------------------------------------------------------------------- /A-01-Git/VersionControlGit.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "98c2f707-bcdd-4b31-a8e5-7065ea21659b", 6 | "metadata": {}, 7 | "source": [ 8 | "# Git introduction\n", 9 | "\n", 10 | "A version control system allows to keep record of every change done on a\n", 11 | "given set of files, and also encourages and easies collaboration. It\n", 12 | "works better for plain text files (source code, latex, txt, etc).\n", 13 | "\n", 14 | "In this module we will learn the basic of version control by using git.\n", 15 | "At the end, the user will be able to use git for source code version\n", 16 | "control with a bitbucket repository.\n", 17 | "\n", 18 | "REFS:\n", 19 | "\n", 20 | "- [Git the simple guide](http://rogerdudler.github.io/git-guide/)\n", 21 | "- \n", 22 | "\n", 23 | "## Introduction\n", 24 | "\n", 25 | "Git:\n", 26 | "\n", 27 | "- is a de-centralized version control system. Every contributor has a\n", 28 | " copy of the repository and performs local changes on it. Then, he\n", 29 | " tries to commit the changes to the master repository, and if no\n", 30 | " conflicts appear then the changes are merged and can be propagated\n", 31 | " to the other developers.\n", 32 | "- was started by Linus Torvalds to manage the linux kernel\n", 33 | " development, after the original system, BitKeeper, was\n", 34 | " license-restricted.\n", 35 | "- is very fast and branches are just a natural thing.\n", 36 | "- is kind of a file system which offers snapshots of the current files\n", 37 | " version.\n", 38 | "- Every commit is marked with a hash SHA-1 like\n", 39 | " 24b9da6552252987aa493b52f8696cd6d3b00373 .\n", 40 | "- The typical workflow is (on an already git repo): edit, stage,\n", 41 | " commit.\n", 42 | "\n", 43 | "> NOTE: Getting help If you want to read the manual for a given `git`\n", 44 | "> command, like `commit`, you should use\n", 45 | "```bash\n", 46 | " git help commit\n", 47 | "```" 48 | ] 49 | }, 50 | { 51 | "cell_type": "markdown", 52 | "id": "6b08bfd4-090b-483d-a8fa-641455df6f22", 53 | "metadata": {}, 54 | "source": [ 55 | "## The first repo\n", 56 | "\n", 57 | "Open the terminal. Create a directory for this first example repository:\n", 58 | "```bash\n", 59 | " $ mkdir myfirstrepo\n", 60 | " $ cd myfirstrepo\n", 61 | "``` \n", 62 | "Now just start your git repo\n", 63 | "```bash\n", 64 | " $ git init\n", 65 | "```\n", 66 | "That’s all. You now have a git repository ready to be used. What is\n", 67 | "inside the repo?\n", 68 | "```bash\n", 69 | " $ ls\n", 70 | "```\n", 71 | "Nothing? what about\n", 72 | "```bash\n", 73 | " $ ls -a\n", 74 | "```\n", 75 | "There should be a sub-directory called .git, which includes all the\n", 76 | "information about your repo. You are not supposed to directly modify\n", 77 | "**any** content of that hidden repository.\n", 78 | "\n", 79 | "What does this mean?\n", 80 | "```bash\n", 81 | " $ git init \n", 82 | "```\n", 83 | "You can also clone an existing repository with\n", 84 | "```bash\n", 85 | " $ git clone https://github.com/path/to/my-project.git\n", 86 | "```\n", 87 | "This will clone the my-project.git repo into the my-project directory.\n", 88 | "Cloning a repository is the most natural way to start using a remote\n", 89 | "repository, locally. For example, let’s assume you have a local\n", 90 | "repository at the University. Then you commit and send it to a remote\n", 91 | "repository, stored, for example, at bitbucket or github. Then you go to home. At\n", 92 | "home, you want a copy of the remote repository to keep working on it:\n", 93 | "you clone it. After successful cloning, you will have three copies of\n", 94 | "your repository: one at the university, one at your home, and one at the\n", 95 | "remote location. Then you could make some changes at home, send them to\n", 96 | "the remote repository (with `git push`), and then, when at the\n", 97 | "University, get those updates from the remote (with `git pull`). At that\n", 98 | "point, you will have all repositories correctly synced. This way you\n", 99 | "will able to have several copies of your remote repository and all of\n", 100 | "them synced. Do not forget to start your work with a `git pull`, and end\n", 101 | "it with a `git push`.\n" 102 | ] 103 | }, 104 | { 105 | "cell_type": "markdown", 106 | "id": "78782bdc-8211-442c-a5d3-dfaa4b2fa38b", 107 | "metadata": {}, 108 | "source": [ 109 | "## Configuring git (individual repo or installation)\n", 110 | "\n", 111 | "The `git config` command allows to configure the individual repository\n", 112 | "preferences or the global options for the installations. To read the\n", 113 | "help, please write\n", 114 | "```bash\n", 115 | " $ git help config\n", 116 | "```\n", 117 | "Some examples:\n", 118 | "\n", 119 | "- Configures the user name for the current repository:\n", 120 | "\n", 121 | "```bash\n", 122 | " $ git config user.name \n", 123 | "```\n", 124 | "Or for the current user (globally, not just this repo)\n", 125 | "```bash\n", 126 | " $ git config --global user.name \n", 127 | "```\n", 128 | "> NOTE : Local config is stored at `.git/config`. Global config for the\n", 129 | "> user is stored at `~/.gitconfig`. Finally, the file\n", 130 | "> `$(prefix)/etc/gitconfig` stores the system-wide settings.\n", 131 | "\n", 132 | "> NOTE : The file `.gitignore` allows to specify files of patterns of\n", 133 | "> files to be ignored.\n", 134 | "\n", 135 | "> NOTE : All this files are plain text files. You can directly edit them\n", 136 | "> (not recommended) or use the `config` command o edit them.\n", 137 | "\n", 138 | "- Configure the email\n", 139 | "\n", 140 | "```bash\n", 141 | " $ git config --global user.email \n", 142 | "```\n", 143 | "- Opens the global config options in the default editor\n", 144 | "```bash\n", 145 | " $ git config --global --edit\n", 146 | "```\n", 147 | "Examples:\n", 148 | "```bash\n", 149 | " $ # Tell Git who you are\n", 150 | " $ git config --global user.name \"John Smith\"\n", 151 | " $ git config --global user.email john@example.com\n", 152 | "\n", 153 | " $ # Select your favorite text editor\n", 154 | " $ git config --global core.editor vim\n", 155 | "\n", 156 | " $ # Add some SVN-like aliases\n", 157 | " $ git config --global alias.st status\n", 158 | " $ git config --global alias.co checkout\n", 159 | " $ git config --global alias.br branch\n", 160 | " $ git config --global alias.up rebase\n", 161 | " $ git config --global alias.ci commit\n", 162 | "```\n", 163 | "The typical appearance of a configuration file is (DO NOT EDIT IT)\n", 164 | "```bash\n", 165 | " [user] \n", 166 | " name = John Smith\n", 167 | " email = john@example.com\n", 168 | " [alias]\n", 169 | " st = status\n", 170 | " co = checkout\n", 171 | " br = branch\n", 172 | " up = rebase\n", 173 | " ci = commit\n", 174 | " [core]\n", 175 | " editor = vim\n", 176 | "```" 177 | ] 178 | }, 179 | { 180 | "cell_type": "markdown", 181 | "id": "106db023-a64d-4f98-b5e3-a0bbbcd538b9", 182 | "metadata": {}, 183 | "source": [ 184 | "## Committing files to the repo\n", 185 | "\n", 186 | "The typical pattern for working inside a repo is edit/stage/commit. You\n", 187 | "perform some edits, then you select some of them as logically related\n", 188 | "and working and then put them inside the staging area, and finally you\n", 189 | "commit them to the repository. Therefore, you can have files in three\n", 190 | "different states: edited but not staged, staged but not committed, and\n", 191 | "committed. The command `git add` allows to put files into the staging\n", 192 | "area, in other words, to prepare them to be committed.\n", 193 | "```bash\n", 194 | " $ git add # adds file to the stagging area, is not yet commited\n", 195 | "```\n", 196 | "or\n", 197 | "```bash\n", 198 | " git add # adds all files inside directory to the stagging area\n", 199 | "```\n", 200 | "For this case, create a new file called `Readme.txt`, and add any\n", 201 | "content to it (like “Hello World” ;)\n", 202 | "```bash\n", 203 | " $ code Readme.txt\n", 204 | "```\n", 205 | "\n", 206 | "Currently, `Readme.txt` is just a file inside our repository but is not\n", 207 | "in the repository itself. Let’s check the repository status\n", 208 | "```bash\n", 209 | " $ git status \n", 210 | "```\n", 211 | "\n", 212 | "Read the output, what does it mean?\n", 213 | "\n", 214 | "Now let’s add the file to the repo:\n", 215 | "```bash\n", 216 | " $ git add Readme.txt\n", 217 | "```\n", 218 | "Now the file is in the staging area. We have marked it to be added to\n", 219 | "the repository, but it is still **not** in the repo. We need to commit\n", 220 | "it.\n", 221 | "```bash\n", 222 | " $ git commit -m \"First commit. Adding Readme.txt file\"\n", 223 | "```\n", 224 | "\n", 225 | "This command will commit the file Readme.txt to the repo with the log\n", 226 | "message stated (after the `-m` flag). You can also add many stagged\n", 227 | "files or changes with the `-a` flag. Check `git help commit`.\n", 228 | "\n", 229 | "> TIP: Always make small and frequent commits. Do not make large commits\n", 230 | "> with many changes since it will lead to difficulties when you want to\n", 231 | "> revert or track a problematic change, among other possible\n", 232 | "> difficulties. Commit as much as possible.\n", 233 | "\n", 234 | "> NOTE : The staged area allows to group related changes, possibly\n", 235 | "> distributed across several files, to a single commit. The staged area\n", 236 | "> is kind of a buffer in the space of changes. NOTE : Git performs\n", 237 | "> snapshots when it commits. That is, it stores the full files, no just\n", 238 | "> files diffs.\n", 239 | "\n", 240 | "> NOTE : Check the output of `git log`. Read its manual. What is it\n", 241 | "> useful for?\n", 242 | "\n", 243 | "**Exercise** \\> Perform several changes to the Readme.txt files, and for\n", 244 | "each change perform some commits with an appropiate log message.\n", 245 | "Possibly, add another file and then commit it to the repository." 246 | ] 247 | }, 248 | { 249 | "cell_type": "markdown", 250 | "id": "b41ad6fb-ee65-465e-8e41-2ec191db1669", 251 | "metadata": {}, 252 | "source": [ 253 | "## The `git log` command\n", 254 | "\n", 255 | "Allows to explore the history of commits. In contrast, `git status`\n", 256 | "gives information of the current status of the repo: staged files,\n", 257 | "changes, new files, etc.\n", 258 | "\n", 259 | "Usage:\n", 260 | "```bash\n", 261 | " $ git log # Normal usage\n", 262 | "\n", 263 | " $ git log -n # Print only the last commits \n", 264 | "\n", 265 | " $ git log --oneline # Condense each commit to a single line\n", 266 | "\n", 267 | " $ git log --grep=\"\" # search for commits with pattern \n", 268 | "\n", 269 | "```" 270 | ] 271 | }, 272 | { 273 | "cell_type": "markdown", 274 | "id": "29f0bad5-455a-4fbd-90eb-b79dd0804319", 275 | "metadata": {}, 276 | "source": [ 277 | "## Undoing changes\n", 278 | "\n", 279 | "One of the advantages of a version control system is the possibility to\n", 280 | "revert to a previous version of a file if a commit is found to be\n", 281 | "faulty. There are several ways to do that. For example, to get an\n", 282 | "specific revision of a file, we could use\n", 283 | "```bash\n", 284 | " git checkout # this affects the repo since it gets the file from the specific commit\n", 285 | "```\n", 286 | "\n", 287 | "\n", 288 | "To checkout an specific revision, use\n", 289 | "```bash\n", 290 | " git checkout \n", 291 | "```\n", 292 | "This last one is a read-only version which does not affect the repo (you\n", 293 | "can revert back to the original last state with `git checkout master`,\n", 294 | "which moves you to the master branch.)\n", 295 | "\n", 296 | "If you want to undo a specific commit, use\n", 297 | "```bash\n", 298 | " git revert \n", 299 | "```\n", 300 | "\n", 301 | "This generates a new commit which undoes all changes introduced in\n", 302 | "commit ``, and applies it to the current branch. Note that this\n", 303 | "could imply a possible conflict if you are not undoing the previous\n", 304 | "commit but other intermediate commits.\n", 305 | "\n", 306 | "> NOTE: Another option, not advised, is to use the `git reset `\n", 307 | "> command. This reset **ALL** commits until revision `` which\n", 308 | "> deletes possible correct changes. In contrast, `git revert `\n", 309 | "> preserves the history and the commits between the current revision and\n", 310 | "> the one which is going to be reverted. Git reset, in turns, has also a\n", 311 | "> very useful use: to remove all current modifications and restart in\n", 312 | "> the current repo status, after using `git reset`. Furthermore, it\n", 313 | "> allows to remove specific files from the staging area.\n", 314 | "\n", 315 | "In order to remove untracked changes in the current repository, you can\n", 316 | "use the `git clean command`. **This is not undoable**, the untracked\n", 317 | "files will be deleted forever.\n", 318 | "\n", 319 | "**Exercise** \\> After performing several commits, revert the last commit\n", 320 | ". What happened to the other files (if you added other ones)? check the\n", 321 | "log. You can also revert to the first revision of that file." 322 | ] 323 | }, 324 | { 325 | "cell_type": "markdown", 326 | "id": "b9676741-22fc-4a3a-9944-59acd1beadd3", 327 | "metadata": {}, 328 | "source": [ 329 | "## Git branches\n", 330 | "\n", 331 | "Branches in git are a natural part of the daily job, and allow to keep\n", 332 | "several development paths that can be merged info the main branch at any\n", 333 | "time. They are very handful for experimental testing and development of\n", 334 | "new features. Commits, staging areas, and history are independent for\n", 335 | "each branch, before merge. Three basic commands are needed here:\n", 336 | "`git branch`, `git checkout`, and `git merge`.\n", 337 | "\n", 338 | "Examples :\n", 339 | "```bash\n", 340 | " $ git branch # lists all branch in the repository\n", 341 | " $ git branch # creates a branch called \n", 342 | " $ git branch -d # deletes an specific branch\n", 343 | " $ git branch -m # renames the current branch to \n", 344 | "```\n", 345 | "To select a specific branch, use the command `git checkout `.\n", 346 | "Other uses:\n", 347 | "```bash\n", 348 | " $ git checkout -b # create and checkout the new branch\n", 349 | " $ git checkout -b # creates and checkout but re-base with some existing-branch\n", 350 | "```\n", 351 | "Example/Exercise:\n", 352 | "```bash\n", 353 | " $ git branch new-feature\n", 354 | " $ git checkout new-feature\n", 355 | " $ # Edit some files\n", 356 | " $ git add \n", 357 | " $ git commit -m \"Started work on a new feature\"\n", 358 | " $ # Repeat\n", 359 | " $ git checkout master\n", 360 | "```\n", 361 | "After you have decided that the work in an experimental branch is good\n", 362 | "enough to be used, you can merge the changes from that branch into the\n", 363 | "any branch of reference (like the master one). To do so, use\n", 364 | "```bash\n", 365 | " git merge \n", 366 | "```\n", 367 | "This will merge the changes from branch `` into the the current\n", 368 | "one. Hopefully, this wont generate any inconsistencies. Otherwise, you\n", 369 | "will be forced to sove them manually. Merges can be fast-forward (if\n", 370 | "history is linear) or three-way (if not).\n", 371 | "\n", 372 | "\\*\\* Resolving conflicts \\*\\* Sometimes a file is edited in the same\n", 373 | "part by two commits. This will generate a merge conflict. Since git\n", 374 | "cannot figure out what part to commit, it stops and the conflict should\n", 375 | "be resolved manually. After you finish the modification, you can use\n", 376 | "`git add` on the conflicting file to tell git you have resolved the\n", 377 | "problem. Then you run a normal `git commit` .\n", 378 | "\n", 379 | "Example for a fast-forward merge:\n", 380 | "\n", 381 | "```bash\n", 382 | " # Start a new feature\n", 383 | " git checkout -b new-feature master\n", 384 | "\n", 385 | " # Edit some files\n", 386 | " git add \n", 387 | " git commit -m \"Start a feature\"\n", 388 | "\n", 389 | " # Edit some files\n", 390 | " git add \n", 391 | " git commit -m \"Finish a feature\"\n", 392 | "\n", 393 | " # Merge in the new-feature branch\n", 394 | " git checkout master\n", 395 | " git merge new-feature\n", 396 | " git branch -d new-feature\n", 397 | "```\n", 398 | "\n", 399 | "```bash\n", 400 | " # Start a new feature\n", 401 | " git checkout -b new-feature master\n", 402 | "\n", 403 | " # Edit some files\n", 404 | " git add \n", 405 | " git commit -m \"Start a feature\"\n", 406 | "\n", 407 | " # Edit some files\n", 408 | " git add \n", 409 | " git commit -m \"Finish a feature\"\n", 410 | "\n", 411 | " # Develop the master branch\n", 412 | " git checkout master\n", 413 | "\n", 414 | " # Edit some files\n", 415 | " git add \n", 416 | " git commit -m \"Make some super-stable changes to master\"\n", 417 | "\n", 418 | " # Merge in the new-feature branch\n", 419 | " git merge new-feature\n", 420 | " git branch -d new-feature\n", 421 | "```\n", 422 | "> TIP : There are several graphical clients which allows to follow the\n", 423 | "> branch commits visually. One example is gitk. There are several\n", 424 | "> others. But you should be able to manage from the plain command line.\n", 425 | "\n", 426 | "\n", 427 | "> TIP : Another visual option is to use the bitbucket page for your repo\n", 428 | "> where all the code. commits, branches, etc can be visualized." 429 | ] 430 | }, 431 | { 432 | "cell_type": "markdown", 433 | "id": "624f55ec-34d1-4750-bf04-71d3a51345bb", 434 | "metadata": {}, 435 | "source": [ 436 | "## Modifying the history\n", 437 | "\n", 438 | "It is possible to amend a commit by using the command\n", 439 | "`git commit --amend`. This allows to either combine the staged changes\n", 440 | "with the previous commit or to simply modify the log message. An amended\n", 441 | "commit is a completely new commit. The original commit is removed from\n", 442 | "history. Other commands to check : `git rebase`, `git rebase -i`,\n", 443 | "`git reflog`." 444 | ] 445 | }, 446 | { 447 | "cell_type": "markdown", 448 | "id": "9de71bc1-d19d-465d-b3db-079330a1e1f8", 449 | "metadata": {}, 450 | "source": [ 451 | "## Remote repositories\n", 452 | "\n", 453 | "Git\n", 454 | "de-centralized approach allows you to have your own copy of the\n", 455 | "repository where you can develop new commits and/or branches and then\n", 456 | "push them to remote repositories while also allowing you to pull changes\n", 457 | "other developers could have performed.\n", 458 | "\n", 459 | "In this regard, the `git remote` command allows you create, view, and\n", 460 | "delete connections to other repositories. First, let check the help\n", 461 | "```bash\n", 462 | " git help remote\n", 463 | "```\n", 464 | "The command `git remote` alone will list all connections you have in\n", 465 | "your repo to other repos. The command\n", 466 | "```bash\n", 467 | " git remote add \n", 468 | "```\n", 469 | "will create a new connection to another repo located at ``, and\n", 470 | "allows you to use `` as a convenient shortcut.\n", 471 | "\n", 472 | "What does the following do?\n", 473 | "```bash\n", 474 | " git remote rm \n", 475 | " git remote rename \n", 476 | "```\n", 477 | "> NOTE : When you clone a remote repository, it automatically creates a\n", 478 | "> remote connection called origin which points to the remote repository." 479 | ] 480 | }, 481 | { 482 | "cell_type": "markdown", 483 | "id": "7c09e817-60f3-4894-9453-5f12989ec6fb", 484 | "metadata": {}, 485 | "source": [ 486 | "### Fetching updates\n", 487 | "\n", 488 | "If you want to get some remote changes from the remote repo but do not\n", 489 | "want yet to merge them into your local repo, you can use\n", 490 | "```bash\n", 491 | " git fetch \n", 492 | "```\n", 493 | "or\n", 494 | "```bash\n", 495 | " git fetch \n", 496 | "```\n", 497 | "The latter will fetch only an specific branch. If you think that the\n", 498 | "remote changes are appropriate, you can merge them into your local\n", 499 | "repository with `git merge`." 500 | ] 501 | }, 502 | { 503 | "cell_type": "markdown", 504 | "id": "33a80255-d3fb-4e8e-8c74-6c0b23fe1e1d", 505 | "metadata": {}, 506 | "source": [ 507 | "### Pulling updates\n", 508 | "\n", 509 | "You can also fetch and merge at the same time with a simple\n", 510 | "```bash\n", 511 | " git pull \n", 512 | "```\n", 513 | "which is equivalent to `git fetch ` followed by\n", 514 | "`git merge origin/`." 515 | ] 516 | }, 517 | { 518 | "cell_type": "markdown", 519 | "id": "0c9eef9f-f057-4e0c-8cac-009c9a19a1f9", 520 | "metadata": {}, 521 | "source": [ 522 | "### Pushing updates\n", 523 | "\n", 524 | "The inverse process, where you publish your result to the remote repo,\n", 525 | "is done by\n", 526 | "```bash\n", 527 | " git push \n", 528 | "```\n", 529 | "From the previous, you can see that if you already have a local repo\n", 530 | "connected to a remote one, the basic work loop is : pull (to update your\n", 531 | "local repo), edit, add, commit, edit, add, commit, …, edit, add, commit,\n", 532 | "and push." 533 | ] 534 | }, 535 | { 536 | "cell_type": "code", 537 | "execution_count": null, 538 | "id": "1f6b4b22-9b06-408c-b9c8-b126d6fc1fc4", 539 | "metadata": {}, 540 | "outputs": [], 541 | "source": [] 542 | } 543 | ], 544 | "metadata": { 545 | "kernelspec": { 546 | "display_name": "Python 3 (ipykernel)", 547 | "language": "python", 548 | "name": "python3" 549 | }, 550 | "language_info": { 551 | "codemirror_mode": { 552 | "name": "ipython", 553 | "version": 3 554 | }, 555 | "file_extension": ".py", 556 | "mimetype": "text/x-python", 557 | "name": "python", 558 | "nbconvert_exporter": "python", 559 | "pygments_lexer": "ipython3", 560 | "version": "3.12.9" 561 | } 562 | }, 563 | "nbformat": 4, 564 | "nbformat_minor": 5 565 | } 566 | -------------------------------------------------------------------------------- /A-02-Containers/Docker.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "15537ed5-6b6c-4108-9430-1d6fd9507bae", 6 | "metadata": {}, 7 | "source": [ 8 | "# Docker Containers - Introductory Lesson\n", 9 | "\n", 10 | "\n", 11 | "\n", 12 | "\n", 13 | "## What are Containers?\n", 14 | "\n", 15 | "Containers are lightweight, portable, and isolated environments that package applications along with their dependencies. Think of them as:\n", 16 | "\n", 17 | "- **Virtual machines** but much more efficient and less resource hungry.\n", 18 | "- **Shipping containers** for software - they work the same way everywhere\n", 19 | "- **Isolated bubbles** where your application runs independently\n", 20 | "\n", 21 | "### Key Benefits:\n", 22 | "- **Consistency**: \"It works on my machine\" becomes \"It works everywhere\"\n", 23 | "- **Isolation**: Applications don't interfere with each other\n", 24 | "- **Portability**: Run the same container on development, testing, and production\n", 25 | "- **Efficiency**: Share the host OS kernel, unlike traditional VMs\n", 26 | "\n", 27 | "## Docker Basics\n", 28 | "\n", 29 | "Docker is the most popular containerization platform. It uses:\n", 30 | "\n", 31 | "- **Images**: Read-only templates used to create containers\n", 32 | "- **Containers**: Running instances of images\n", 33 | "- **Dockerfile**: Text file with instructions to build an image\n", 34 | "- **Docker Hub**: Public registry for sharing images\n", 35 | "- **Docker Compose**: Tool for defining and running multi-container Docker applications\n", 36 | "\n", 37 | "### Architecture Overview\n", 38 | "```\n", 39 | "┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐\n", 40 | "│ Application │ │ Application │ │ Application │\n", 41 | "├─────────────────┤ ├─────────────────┤ ├─────────────────┤\n", 42 | "│ Container │ │ Container │ │ Container │\n", 43 | "├─────────────────┤ ├─────────────────┤ ├─────────────────┤\n", 44 | "│ Docker Engine │\n", 45 | "├───────────────────────────────────────────────────────────────┤\n", 46 | "│ Host Operating System │\n", 47 | "└───────────────────────────────────────────────────────────────┘\n", 48 | "```\n", 49 | "\n", 50 | "\n", 51 | "
\n", 52 | "
\n", 53 | "\n", 54 | "
Docker arquitecture
\n", 55 | "
\n", 56 | "
\n" 57 | ] 58 | }, 59 | { 60 | "cell_type": "markdown", 61 | "id": "a241f9e8-073b-427b-882c-9061022d5ef3", 62 | "metadata": {}, 63 | "source": [ 64 | "## Working with Docker Images\n", 65 | "\n", 66 | "### Pulling Images from Docker Hub\n", 67 | "\n", 68 | "```bash\n", 69 | "# Pull the official Ubuntu image\n", 70 | "docker pull ubuntu:22.04\n", 71 | "\n", 72 | "# Pull the latest Ubuntu (defaults to latest tag)\n", 73 | "docker pull ubuntu\n", 74 | "\n", 75 | "# List downloaded images\n", 76 | "docker images\n", 77 | "```\n", 78 | "\n", 79 | "### Understanding Image Tags\n", 80 | "- `ubuntu:22.04` - Specific version\n", 81 | "- `ubuntu:latest` - Latest stable version\n", 82 | "- `ubuntu` - Defaults to latest" 83 | ] 84 | }, 85 | { 86 | "cell_type": "markdown", 87 | "id": "8788e0f7-df5b-4aa6-94fe-4f4ec0af4309", 88 | "metadata": {}, 89 | "source": [ 90 | "## Running Your First Container\n", 91 | "\n", 92 | "### Basic Container Execution\n", 93 | "\n", 94 | "```bash\n", 95 | "# Run a simple hello-world container\n", 96 | "docker run hello-world\n", 97 | "\n", 98 | "# Run a simple command in Ubuntu container\n", 99 | "docker run ubuntu:22.04 echo \"Hello, Docker!\"\n", 100 | "\n", 101 | "# Run an interactive terminal session\n", 102 | "docker run -it ubuntu:22.04 /bin/bash\n", 103 | "\n", 104 | "# Run container in background (detached mode)\n", 105 | "docker run -d ubuntu:22.04 sleep 3600\n", 106 | "\n", 107 | "# List running containers\n", 108 | "docker ps\n", 109 | "\n", 110 | "# List all containers (including stopped)\n", 111 | "docker ps -a\n", 112 | "```\n", 113 | "\n", 114 | "```bash\n", 115 | "CONTAINER ID IMAGE COMMAND CREATED STATUS PORTS NAMES\n", 116 | "2fa15b7ae800 ubuntu \"/bin/bash\" 8 seconds ago Exited (0) 4 seconds ago naughty_curran\n", 117 | "fbcfe62bfcdb ubuntu \"/bin/bash\" 26 seconds ago Exited (0) 9 seconds ago adoring_dhawan\n", 118 | "c5fe4f91519a hello-world \"/hello\" 49 seconds ago Exited (0) 48 seconds ago vibrant_bhaskara\n", 119 | "```\n", 120 | "\n", 121 | "### Command Breakdown:\n", 122 | "- `docker run`: Create and start a new container\n", 123 | "- `-it`: Interactive mode with TTY (terminal)\n", 124 | "- `-d`: Detached mode (run in background)\n", 125 | "- `ubuntu:22.04`: Image name and tag\n", 126 | "- `/bin/bash`: Command to run inside container\n" 127 | ] 128 | }, 129 | { 130 | "cell_type": "markdown", 131 | "id": "15054694-2886-4063-bb11-d46aef91292f", 132 | "metadata": {}, 133 | "source": [ 134 | "## Example: Installing Libraries in Containers\n", 135 | "\n", 136 | "### Method 1: Install During Runtime\n", 137 | "\n", 138 | "```bash\n", 139 | "# Start an interactive Ubuntu container\n", 140 | "docker run -it ubuntu:22.04 /bin/bash\n", 141 | "\n", 142 | "# Inside the container, update package list\n", 143 | "apt update\n", 144 | "\n", 145 | "# Install development tools and Eigen library\n", 146 | "apt install -y build-essential libeigen3-dev\n", 147 | "\n", 148 | "# Verify installation\n", 149 | "pkg-config --modversion eigen3\n", 150 | "```\n", 151 | "\n", 152 | "All this changes will be deleted after exiting the container.\n", 153 | "\n", 154 | "\n", 155 | "### Method 2: Create a Custom Dockerfile\n", 156 | "\n", 157 | "Create a file named `Dockerfile`:\n", 158 | "\n", 159 | "```dockerfile\n", 160 | "# Use Ubuntu 24.04 as base image\n", 161 | "FROM ubuntu:24.04\n", 162 | "\n", 163 | "# Avoid interactive prompts during installation\n", 164 | "ENV DEBIAN_FRONTEND=noninteractive\n", 165 | "\n", 166 | "# Update package list and install dependencies\n", 167 | "RUN apt update && apt install -y \\\n", 168 | " build-essential \\\n", 169 | " libeigen3-dev \\\n", 170 | " cmake \\\n", 171 | " pkg-config \\\n", 172 | " && rm -rf /var/lib/apt/lists/*\n", 173 | "\n", 174 | "# # Updating gcc/g++\n", 175 | "# RUN apt-get update\n", 176 | "# RUN apt install software-properties-common -y\n", 177 | "# RUN apt install g++-14 -y\n", 178 | "\n", 179 | "# # Installing starship: https://starship.rs/guide/\n", 180 | "# RUN apt install curl\n", 181 | "# RUN cd /tmp && curl -sS https://starship.rs/install.sh > install_starship.sh && sh install_starship.sh --yes\n", 182 | "# RUN echo 'eval \"$(starship init bash)\"' >> ~/.bashrc\n", 183 | "\n", 184 | "# Exercise: Install git\n", 185 | "\n", 186 | "# Exercise: Install lazygit\n", 187 | "\n", 188 | "# Exercise: Install uv for python management: https://docs.astral.sh/uv/#highlights\n", 189 | "\n", 190 | "\n", 191 | "# Set working directory\n", 192 | "WORKDIR /workspace\n", 193 | "\n", 194 | "# Default command\n", 195 | "CMD [\"/bin/bash\"]\n", 196 | "```\n", 197 | "\n", 198 | "Build the custom image:\n", 199 | "\n", 200 | "```bash\n", 201 | "# Build image with tag 'cpp-dev'\n", 202 | "docker build -t cpp-dev .\n", 203 | "\n", 204 | "# Chek the available images\n", 205 | "docker image ls\n", 206 | "\n", 207 | "# Run container from custom image\n", 208 | "docker run -it cpp-dev\n", 209 | "```" 210 | ] 211 | }, 212 | { 213 | "cell_type": "markdown", 214 | "id": "45a2817c-9c67-4708-a278-6b6154e2928d", 215 | "metadata": {}, 216 | "source": [ 217 | "## Sharing Local Directories with Containers\n", 218 | "\n", 219 | "### Volume Mounting\n", 220 | "\n", 221 | "Volume mounting allows you to share files between your host system and the container.\n", 222 | "\n", 223 | "```bash\n", 224 | "# Mount current directory to /workspace in container\n", 225 | "docker run -it -v $(pwd):/workspace ubuntu:22.04 /bin/bash\n", 226 | "\n", 227 | "# On Windows PowerShell, use:\n", 228 | "docker run -it -v ${PWD}:/workspace ubuntu:22.04 /bin/bash\n", 229 | "\n", 230 | "# On Windows Command Prompt, use:\n", 231 | "docker run -it -v %cd%:/workspace ubuntu:22.04 /bin/bash\n", 232 | "```\n", 233 | "\n", 234 | "### Volume Mount Syntax:\n", 235 | "- `-v host_path:container_path`\n", 236 | "- `-v $(pwd):/workspace` - Mount current directory to /workspace\n", 237 | "- `-v /home/user/data:/data` - Mount specific host directory\n", 238 | "\n", 239 | "### Read-Only Mounts:\n", 240 | "```bash\n", 241 | "# Mount as read-only\n", 242 | "docker run -it -v $(pwd):/workspace:ro ubuntu:22.04\n", 243 | "```" 244 | ] 245 | }, 246 | { 247 | "cell_type": "markdown", 248 | "id": "074736af-98ff-48d8-a171-a4a0c1b031c1", 249 | "metadata": {}, 250 | "source": [ 251 | "## Practical Example: C++ Development with Eigen\n", 252 | "\n", 253 | "Let's create a complete example that demonstrates using Docker for C++ development with the Eigen library.\n", 254 | "\n", 255 | "### Step 1: Create Project Structure\n", 256 | "\n", 257 | "```bash\n", 258 | "mkdir docker-cpp-example\n", 259 | "cd docker-cpp-example\n", 260 | "```\n", 261 | "\n", 262 | "### Step 2: Create a Simple C++ Program\n", 263 | "\n", 264 | "Create `main.cpp`:\n", 265 | "\n", 266 | "```c++\n", 267 | "#include \n", 268 | "#include \n", 269 | "\n", 270 | "int main() {\n", 271 | " // Create a 3x3 matrix\n", 272 | " Eigen::Matrix3d matrix;\n", 273 | " matrix << 1, 2, 3,\n", 274 | " 4, 5, 6,\n", 275 | " 7, 8, 9;\n", 276 | " \n", 277 | " std::cout << \"Matrix:\\n\" << matrix << std::endl;\n", 278 | " \n", 279 | " // Calculate determinant\n", 280 | " double det = matrix.determinant();\n", 281 | " std::cout << \"Determinant: \" << det << std::endl;\n", 282 | " \n", 283 | " // Create a vector and multiply\n", 284 | " Eigen::Vector3d vector(1, 2, 3);\n", 285 | " Eigen::Vector3d result = matrix * vector;\n", 286 | " \n", 287 | " std::cout << \"Matrix * Vector result:\\n\" << result << std::endl;\n", 288 | " \n", 289 | " return 0;\n", 290 | "}\n", 291 | "```\n", 292 | "\n", 293 | "### Step 3: Enhanced Dockerfile\n", 294 | "\n", 295 | "Create `Dockerfile`:\n", 296 | "\n", 297 | "```dockerfile\n", 298 | "FROM ubuntu:22.04\n", 299 | "\n", 300 | "ENV DEBIAN_FRONTEND=noninteractive\n", 301 | "\n", 302 | "# Install development tools\n", 303 | "RUN apt update && apt install -y \\\n", 304 | " build-essential \\\n", 305 | " cmake \\\n", 306 | " libeigen3-dev \\\n", 307 | " pkg-config \\\n", 308 | " && rm -rf /var/lib/apt/lists/*\n", 309 | "\n", 310 | "# Avoid running as root\n", 311 | "# RUN useradd -m -s /bin/bash developer\n", 312 | "# USER developer\n", 313 | "\n", 314 | "WORKDIR /workspace\n", 315 | "\n", 316 | "# Copy source files (optional, we'll use volume mounting)\n", 317 | "# COPY . /workspace\n", 318 | "\n", 319 | "CMD [\"/bin/bash\"]\n", 320 | "```\n", 321 | "\n", 322 | "### Step 5: Build and Run\n", 323 | "\n", 324 | "```bash\n", 325 | "# Build the Docker image\n", 326 | "docker build -t cpp-eigen-dev .\n", 327 | "\n", 328 | "# Run container with volume mounting\n", 329 | "docker run -it -v $(pwd):/workspace cpp-eigen-dev\n", 330 | "\n", 331 | "# Inside the container, build the project\n", 332 | "g++ -I /usr/include/eigen3/ main.cpp -o eigen_example.x\n", 333 | "\n", 334 | "# Run the program\n", 335 | "./eigen_example.x\n", 336 | "```\n", 337 | "\n", 338 | "### Expected Output:\n", 339 | "```\n", 340 | "Matrix:\n", 341 | "1 2 3\n", 342 | "4 5 6\n", 343 | "7 8 9\n", 344 | "Determinant: 0\n", 345 | "Matrix * Vector result:\n", 346 | "14\n", 347 | "32\n", 348 | "50\n", 349 | "```" 350 | ] 351 | }, 352 | { 353 | "cell_type": "markdown", 354 | "id": "aa41f695-a2bb-48c0-a0c7-908b7de79f35", 355 | "metadata": {}, 356 | "source": [ 357 | "## **IMPORTANT NOTE: File permissions**\n", 358 | "Notice that you are running as root inside the container, so any file produced will belong to root. On other words, you, as a normal user, will not be able to edit those files in the local host. In this case it will be better to run as the local user, like\n", 359 | "```bash\n", 360 | "docker run -it -v $(pwd):/workspace --rm --user \"$(id -u):$(id -g)\" cpp-eigen-dev\n", 361 | "```\n", 362 | "\n", 363 | "**WARNING**: Abusing this root permission will bring consequences.\n", 364 | "\n", 365 | "In this case you can run docker using explicit args for the user, like:\n", 366 | "```dockerfile\n", 367 | "FROM ubuntu:latest\n", 368 | "\n", 369 | "# Replace 1000 with your host user's UID/GID\n", 370 | "ARG USER_UID=1000\n", 371 | "ARG GROUP_GID=1000\n", 372 | "\n", 373 | "# Create a group and user with matching IDs\n", 374 | "RUN groupadd -g ${GROUP_GID} appgroup && \\\n", 375 | " useradd -u ${USER_UID} -g appgroup -s /bin/bash -m appuser\n", 376 | "\n", 377 | "# Set ownership for application directory\n", 378 | "RUN mkdir /app && chown appuser:appgroup /app\n", 379 | "\n", 380 | "# Switch to the non-root user\n", 381 | "USER appuser\n", 382 | "\n", 383 | "WORKDIR /app\n", 384 | "\n", 385 | "# Copy your application code\n", 386 | "COPY . .\n", 387 | "\n", 388 | "CMD [\"/bin/bash\"] # Or your application's command\n", 389 | "```\n", 390 | "\n", 391 | "And then build and run as\n", 392 | "```bash\n", 393 | "docker build --build-arg USER_UID=$(id -u) --build-arg GROUP_GID=$(id -g) -t my-app .\n", 394 | "docker run -it --rm -v /host/path:/app my-app\n", 395 | "```\n", 396 | "\n", 397 | "\n", 398 | "### Solution with apptainer/singularity\n", 399 | "In the HPC and scientific computing world it is better to use , like\n", 400 | "```bash\n", 401 | "apptainer shell docker://alpine\n", 402 | "```\n", 403 | "\n", 404 | "You can create a sif apptainer image using \n", 405 | "```bash\n", 406 | "# get image name and tag\n", 407 | "docker images\n", 408 | "\n", 409 | "# build the sif image\n", 410 | "apptainer build cpp-eigen-dev.sif docker-daemon:cpp-eigen-dev:latest\n", 411 | "```\n", 412 | "\n", 413 | "and then run a shell as\n", 414 | "```bash\n", 415 | "apptainer shell cpp-eigen-dev.sif\n", 416 | "```\n", 417 | "\n", 418 | "You can also use your Dockerfile to create an apptainer `def` file, using spython\n", 419 | "```bash\n", 420 | "# install the utility\n", 421 | "pip3 install spython\n", 422 | "\n", 423 | "# Create the def file\n", 424 | "spython recipe Dockerfile > cpp-eigen-dev.def\n", 425 | "\n", 426 | "# Build your image\n", 427 | "apptainer build cpp-eigen-dev.sif cpp-eigen-dev.def\n", 428 | "\n", 429 | "# Easier way but requires more recent apptainer\n", 430 | "# apptainer build --oci your_image.sif dockerfile://./Dockerfile\n", 431 | "```" 432 | ] 433 | }, 434 | { 435 | "cell_type": "markdown", 436 | "id": "f2a2fd44-d1b9-467b-9e14-9c3c0f6f7d75", 437 | "metadata": {}, 438 | "source": [ 439 | "## Common Docker Commands\n", 440 | "\n", 441 | "### Container Management\n", 442 | "```bash\n", 443 | "# Start a stopped container\n", 444 | "docker start \n", 445 | "\n", 446 | "# Stop a running container\n", 447 | "docker stop \n", 448 | "\n", 449 | "# Remove a container\n", 450 | "docker rm \n", 451 | "\n", 452 | "# Remove all stopped containers\n", 453 | "docker container prune\n", 454 | "```\n", 455 | "\n", 456 | "### Image Management\n", 457 | "```bash\n", 458 | "# List images\n", 459 | "docker images\n", 460 | "\n", 461 | "# Remove an image\n", 462 | "docker rmi \n", 463 | "\n", 464 | "# Remove unused images\n", 465 | "docker image prune\n", 466 | "\n", 467 | "# View image history\n", 468 | "docker history \n", 469 | "```\n", 470 | "\n", 471 | "### Debugging and Inspection\n", 472 | "```bash\n", 473 | "# View container logs\n", 474 | "docker logs \n", 475 | "\n", 476 | "# Execute command in running container\n", 477 | "docker exec -it /bin/bash\n", 478 | "\n", 479 | "# Inspect container details\n", 480 | "docker inspect \n", 481 | "\n", 482 | "# View container resource usage\n", 483 | "docker stats\n", 484 | "```\n", 485 | "\n", 486 | "## Best Practices\n", 487 | "\n", 488 | "### 1. Use Specific Image Tags\n", 489 | "```bash\n", 490 | "# Good\n", 491 | "FROM ubuntu:22.04\n", 492 | "\n", 493 | "# Avoid\n", 494 | "FROM ubuntu:latest\n", 495 | "```\n", 496 | "\n", 497 | "### 2. Minimize Image Layers\n", 498 | "```dockerfile\n", 499 | "# Good - Single RUN command\n", 500 | "RUN apt update && apt install -y \\\n", 501 | " package1 \\\n", 502 | " package2 \\\n", 503 | " && rm -rf /var/lib/apt/lists/*\n", 504 | "\n", 505 | "# Avoid - Multiple RUN commands\n", 506 | "RUN apt update\n", 507 | "RUN apt install -y package1\n", 508 | "RUN apt install -y package2\n", 509 | "```\n", 510 | "\n", 511 | "### 3. Use .dockerignore\n", 512 | "Create `.dockerignore` to exclude unnecessary files:\n", 513 | "```\n", 514 | ".git\n", 515 | ".gitignore\n", 516 | "README.md\n", 517 | "Dockerfile\n", 518 | ".dockerignore\n", 519 | "node_modules\n", 520 | "*.log\n", 521 | "```\n", 522 | "\n", 523 | "### 4. Don't Run as Root\n", 524 | "```dockerfile\n", 525 | "# Create non-root user\n", 526 | "RUN useradd -m -s /bin/bash developer\n", 527 | "USER developer\n", 528 | "```\n", 529 | "\n", 530 | "### 5. Clean Up Package Caches\n", 531 | "```dockerfile\n", 532 | "RUN apt update && apt install -y \\\n", 533 | " package1 \\\n", 534 | " package2 \\\n", 535 | " && rm -rf /var/lib/apt/lists/*\n", 536 | "```" 537 | ] 538 | }, 539 | { 540 | "cell_type": "markdown", 541 | "id": "d7f5c56d-5420-4766-b14a-26c8f76b14a6", 542 | "metadata": {}, 543 | "source": [ 544 | "## Exercises\n", 545 | "\n", 546 | "### Exercise 1: Basic Container Operations\n", 547 | "1. Pull the Python 3.9 image from Docker Hub\n", 548 | "2. Run a Python container and execute: `python -c \"print('Hello from Docker!')\"`\n", 549 | "3. Start an interactive Python session in a container\n", 550 | "\n", 551 | "### Exercise 2: Volume Mounting Practice\n", 552 | "1. Create a local directory with a text file\n", 553 | "2. Mount it to a container and read the file from inside the container\n", 554 | "3. Create a new file inside the container and verify it appears on your host\n", 555 | "\n", 556 | "### Exercise 3: Custom Development Environment\n", 557 | "1. Create a Dockerfile for a Node.js development environment\n", 558 | "2. Include Node.js, npm, and git\n", 559 | "3. Set up a working directory\n", 560 | "4. Build and test your custom image\n", 561 | "\n", 562 | "### Exercise 4: Multi-Step Build\n", 563 | "1. Extend the C++ Eigen example\n", 564 | "2. Add additional mathematical operations\n", 565 | "3. Build and run everything in Docker\n", 566 | "\n", 567 | "### Exercise 5: Container Networking\n", 568 | "1. Run a web server (like nginx) in a container\n", 569 | "2. Map port 80 in the container to port 8080 on your host\n", 570 | "3. Access the web server from your browser\n", 571 | "\n", 572 | "### Solutions Hints:\n", 573 | "\n", 574 | "**Exercise 1:**\n", 575 | "```bash\n", 576 | "docker pull python:3.9\n", 577 | "docker run python:3.9 python -c \"print('Hello from Docker!')\"\n", 578 | "docker run -it python:3.9 python\n", 579 | "```\n", 580 | "\n", 581 | "**Exercise 2:**\n", 582 | "```bash\n", 583 | "mkdir test-data\n", 584 | "echo \"Hello from host\" > test-data/hello.txt\n", 585 | "docker run -it -v $(pwd)/test-data:/data ubuntu:22.04 /bin/bash\n", 586 | "# Inside container: cat /data/hello.txt\n", 587 | "# Inside container: echo \"Hello from container\" > /data/container.txt\n", 588 | "```\n", 589 | "\n", 590 | "**Exercise 5:**\n", 591 | "```bash\n", 592 | "docker run -d -p 8080:80 nginx:alpine\n", 593 | "# Open browser to http://localhost:8080\n", 594 | "```" 595 | ] 596 | }, 597 | { 598 | "cell_type": "markdown", 599 | "id": "6b1252f1-be03-47c8-883c-73f769fccbd6", 600 | "metadata": {}, 601 | "source": [ 602 | "## Conclusion\n", 603 | "\n", 604 | "Docker containers provide a powerful way to:\n", 605 | "- Standardize development environments\n", 606 | "- Ensure consistent deployments\n", 607 | "- Isolate applications and dependencies\n", 608 | "- Share and distribute software easily\n", 609 | "\n", 610 | "Key concepts covered:\n", 611 | "- Images vs. Containers\n", 612 | "- Volume mounting for file sharing\n", 613 | "- Installing libraries and dependencies\n", 614 | "- Building custom images with Dockerfiles\n", 615 | "- Practical C++ development example\n", 616 | "\n", 617 | "Continue practicing with different base images, programming languages, and use cases to master containerization!\n", 618 | "\n", 619 | "ROOTLESS containers" 620 | ] 621 | }, 622 | { 623 | "cell_type": "code", 624 | "execution_count": null, 625 | "id": "a4cb7760-6726-486d-b527-cb905596e3c0", 626 | "metadata": {}, 627 | "outputs": [], 628 | "source": [] 629 | } 630 | ], 631 | "metadata": { 632 | "kernelspec": { 633 | "display_name": "Python 3 (ipykernel)", 634 | "language": "python", 635 | "name": "python3" 636 | }, 637 | "language_info": { 638 | "codemirror_mode": { 639 | "name": "ipython", 640 | "version": 3 641 | }, 642 | "file_extension": ".py", 643 | "mimetype": "text/x-python", 644 | "name": "python", 645 | "nbconvert_exporter": "python", 646 | "pygments_lexer": "ipython3", 647 | "version": "3.12.10" 648 | } 649 | }, 650 | "nbformat": 4, 651 | "nbformat_minor": 5 652 | } 653 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | # See docs : https://mybinder.readthedocs.io/en/latest/tutorials/dockerfile.html 2 | #FROM python:3.11.8-slim-bookworm 3 | FROM ubuntu:24.04 4 | LABEL maintainer="William Oquendo " 5 | #ARG CACHEBUST=0 # reset cache at this point, change to 1 to reset cache 6 | 7 | # Install packages 8 | RUN apt-get update && \ 9 | apt-get install -y --no-install-recommends \ 10 | python3 \ 11 | #python3-pip \ # handled by uv 12 | #python3-dev \ # handled by uv 13 | #python3-venv \ # handled by uv 14 | libffi-dev \ 15 | g++-14 \ 16 | make \ 17 | cmake \ 18 | clang \ 19 | libeigen3-dev \ 20 | bat \ 21 | emacs-nox \ 22 | #vim \ 23 | gnuplot-nox \ 24 | nano \ 25 | git \ 26 | htop \ 27 | curl \ 28 | unzip \ 29 | sudo \ 30 | cpplint \ 31 | #valgrind \ 32 | gdb \ 33 | libspdlog-dev \ 34 | ca-certificates \ 35 | && apt-get clean && \ 36 | rm -rf /var/lib/apt/lists/* 37 | 38 | RUN ln -s /usr/bin/g++-14 /usr/bin/g++ 39 | RUN ln -s /usr/bin/gcc-14 /usr/bin/gcc 40 | RUN ln -s /usr/bin/python3 /usr/bin/python 41 | RUN ln -s /usr/bin/aarch64-linux-gnu-gcc-14 /usr/bin/aarch64-linux-gnu-gcc 42 | 43 | # Install catch2 44 | RUN git clone https://github.com/catchorg/Catch2.git 45 | RUN cd Catch2 && \ 46 | cmake -Bbuild -H. -DBUILD_TESTING=OFF && \ 47 | sudo cmake --build build/ --target install --parallel $(nproc) 48 | 49 | # Install fmt 50 | RUN git clone https://github.com/fmtlib/fmt.git 51 | RUN cd fmt && \ 52 | cmake -Bbuild -H. -DBUILD_SHARED_LIBS=TRUE -DFMT_TEST=OFF && \ 53 | sudo cmake --build build/ --target install --parallel $(nproc) 54 | 55 | # Install starship to show git branch in prompt plus some other stuff 56 | RUN curl -fsSL https://starship.rs/install.sh | sh -s -- -y 57 | 58 | # Fix timezone 59 | ENV TZ=America/Bogota 60 | RUN ln -snf /usr/share/zoneinfo/$TZ /etc/localtime && echo $TZ > /etc/timezone 61 | 62 | # Set the SHELL environment variable to /bin/bash 63 | ENV SHELL=/bin/bash 64 | 65 | # Remove the default user to free id 1000 66 | RUN userdel -r ubuntu 67 | 68 | # create user with a home directory 69 | ARG NB_USER=jovyan 70 | ARG NB_UID=1000 71 | ARG NB_HOME=/home/${NB_USER} 72 | 73 | RUN adduser --disabled-password \ 74 | --gecos "Default user" \ 75 | --shell /bin/bash \ 76 | --uid ${NB_UID} \ 77 | ${NB_USER} 78 | 79 | #USER ${NB_USER} 80 | ## move to home 81 | #WORKDIR ${HOME} 82 | 83 | 84 | # Work as NB_USER 85 | WORKDIR ${NB_HOME} 86 | USER ${NB_USER} 87 | 88 | # Clone the source code repo 89 | RUN git clone https://github.com/iluvatar1/ProgCPP-lectures-jupyter.git 90 | 91 | # Setup starship 92 | RUN echo 'eval "$(starship init bash)"' >> ${NB_HOME}/.bashrc 93 | # setup venv for user 94 | RUN echo "source ~/.venv/bin/activate" >> ${NB_HOME}/.bashrc 95 | 96 | # ########################################################################################################### 97 | # Install python packges 98 | # ########################################################################################################### 99 | # Copy only the requirements file first 100 | COPY requirements.txt . 101 | 102 | # USING pip 103 | # create venv, activate and run pip install 104 | #RUN python3 -m venv ${HOME}/.venv 105 | #RUN . ${HOME}/.venv/bin/activate && pip install -r requirements.txt 106 | 107 | # USING uv from astral (very fast) 108 | # Download and run the uv installer 109 | RUN curl -Lsf https://astral.sh/uv/install.sh | sh 110 | # Set the PATH to include both cargo bin and current directory 111 | #ENV PATH="$NB_HOME/.cargo/bin:/usr/local/bin:$PATH" 112 | RUN ${HOME}/.cargo/bin/uv venv --python 3.12 && ${HOME}/.cargo/bin/uv pip install -r requirements.txt 113 | RUN echo 'source $HOME/.cargo/env' >> ${HOME}/.bashrc 114 | RUN echo "source .venv/bin/activate" >> ${HOME}/.bashrc 115 | RUN echo 'export PATH=$HOME/.cargo/bin:$HOME/.venv/bin:$PATH' >> ${HOME}/.bashrc 116 | 117 | # Fix the path for jupyter to make this work with binder 118 | USER root 119 | RUN ln -s /home/jovyan/.venv/bin/jupyter /usr/local/bin/jupyter 120 | USER ${NB_USER} 121 | 122 | ## Run matplotlib config to generate the font cache 123 | #RUN . .venv/bin/activate && MPLBACKEND=Agg python3 -c "import matplotlib.pyplot" 124 | 125 | ENV USER=${NB_USER} 126 | ENV HOME=/home/${NB_USER} 127 | -------------------------------------------------------------------------------- /Makefile: -------------------------------------------------------------------------------- 1 | 2 | .PHONY: book clean actions repo2docker binder devcontainer 3 | 4 | book: 5 | @echo "Building book with jupyter-book" 6 | jupyter-book build -v ./ 7 | 8 | # Check https://github.com/nektos/act/issues/1658 9 | actions: 10 | @echo "Running local actions" 11 | @echo "Do not forget to have docker running and also : sudo ln -s ~/.docker/run/docker.sock /var/run/docker.sock" 12 | act # act --secret-file .secrets -v --container-architecture linux/amd64 13 | 14 | binder: 15 | @echo "Building binder image" 16 | docker build ./ -f ./Dockerfile -t bindertest 17 | docker run -it --rm -p 8888:8888 bindertest jupyter notebook --NotebookApp.default_url=/lab/ --ip=0.0.0.0 --port=8888 --allow-root 18 | 19 | repo2docker: 20 | @echo "Building docker image with repo2docker" 21 | repo2docker --user-id 1000 --user-name jovyan --debug --image-name r2d ./ 22 | 23 | devcontainer: 24 | @echo "Building and running devcontainer image " 25 | devcontainer build --workspace-folder ./ --image-name devcontest 26 | docker run -it devcontest /bin/bash 27 | 28 | clean: 29 | rm -f *~ #_build 30 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Introduction to C++ and Numerical Methods 2 | 3 | These lecture notes are a complement to the class and hopefully a good resource for the students. 4 | 5 | [Lecture Notes](https://iluvatar1.github.io/ProgCPP-lectures-jupyter/README.html) 6 | 7 | [![Binder](https://mybinder.org/badge_logo.svg)](https://mybinder.org/v2/gh/iluvatar1/ProgCPP-lectures-jupyter/HEAD) 8 | 9 | [Google Collab](https://colab.research.google.com/) [Google Collab](https://colab.research.google.com/) 10 | 11 | 12 | 13 | 14 | ```{tableofcontents} 15 | ``` 16 | -------------------------------------------------------------------------------- /_config.yml: -------------------------------------------------------------------------------- 1 | ####################################################################################### 2 | # A default configuration that will be loaded for all jupyter books 3 | # See the documentation for help and more options: 4 | # https://jupyterbook.org/customize/config.html 5 | 6 | ####################################################################################### 7 | # Book settings 8 | title : Introduction to C++ and Numerical Methods # The title of the book. Will be placed in the left navbar. 9 | author : William Oquendo # The author of the book 10 | email : wfoquendop@unal.edu.co # An email address to contact the author 11 | copyright : "2024" # Copyright year to be placed in the footer 12 | logo : https://upload.wikimedia.org/wikipedia/commons/1/18/ISO_C%2B%2B_Logo.svg # A path to the book logo 13 | # Patterns to skip when building the book. Can be glob-style (e.g. "*skip.ipynb") 14 | exclude_patterns : [_build, Thumbs.db, .DS_Store, 15 | "**.ipynb_checkpoints", "VisualizationGL", "00-IntroCourse**", "**.virtual_documents**"] 16 | # Auto-exclude files not in the toc 17 | only_build_toc_files : true 18 | # Force re-execution of notebooks on each build. 19 | # See https://jupyterbook.org/content/execute.html 20 | ####################################################################################### 21 | # Execution settings 22 | execute: 23 | execute_notebooks : auto # Whether to execute notebooks at build time. Must be one of ("auto", "force", "cache", "off") 24 | cache : "" # A path to the jupyter cache that will be used to store execution artifacts. Defaults to `_build/.jupyter_cache/` 25 | exclude_patterns : [] # A list of patterns to *skip* in execution (e.g. a notebook that takes a really long time) 26 | timeout : 40 # The maximum time (in seconds) each notebook cell is allowed to run. 27 | run_in_temp : false # If `True`, then a temporary directory will be created and used as the command working directory (cwd), 28 | # otherwise the notebook's parent directory will be the cwd. 29 | allow_errors : false # If `False`, when a code cell raises an error the execution is stopped, otherwise all cells are always run. 30 | stderr_output : show # One of 'show', 'remove', 'remove-warn', 'warn', 'error', 'severe' 31 | 32 | # Define the name of the latex output file for PDF builds 33 | latex: 34 | latex_documents: 35 | targetname: book.tex 36 | 37 | ## Add a bibtex file so that we can create citations 38 | #bibtex_bibfiles: 39 | # - references.bib 40 | 41 | ####################################################################################### 42 | # Launch button settings 43 | launch_buttons: 44 | use_binder_button : true # Add a binder button to pages (requires the repository to run on Binder) 45 | notebook_interface : jupyterlab # The interface interactive links will activate ["classic", "jupyterlab"] 46 | binderhub_url : "https://mybinder.org" # The URL of the BinderHub (e.g., https://mybinder.org) 47 | binder_repo_base : "https://github.com/" # The site on which the textbook repository is hosted 48 | binder_repo_org : "iluvatar1" # The username or organization that owns this repository 49 | binder_repo_name : "ProgCPP-lectures-jupyter" # The name of the repository on the web 50 | binder_repo_branch : "gh-pages" # The branch on which your textbook is hosted. 51 | binderhub_interact_text : "Interact" # The text that interact buttons will contain. 52 | jupyterhub_url : "" # The URL of the JupyterHub (e.g., https://datahub.berkeley.edu) 53 | thebe : false # Add a thebe button to pages (requires the repository to run on Binder) 54 | colab_url : "https://colab.research.google.com" # The URL of Google Colab (https://colab.research.google.com) 55 | # Information about where the book exists on the web 56 | repository: 57 | url: https://github.com/iluvatar1/ProgCPP-lectures-jupyter # Online location of your book 58 | #path_to_book: docs # Optional path to your book, relative to the repository root 59 | branch: master # Which branch of the repository should be used when creating links (optional) 60 | 61 | # Add GitHub buttons to your book 62 | # See https://jupyterbook.org/customize/config.html#add-a-link-to-your-repository 63 | html: 64 | use_issues_button: true 65 | use_repository_button: true 66 | 67 | # Parsing math blocks 68 | parse: 69 | myst_enable_extensions: ["dollarmath", "amsmath", "html_image"] 70 | # Displaying interactive plotly figures 71 | sphinx: 72 | config: 73 | html_js_files: 74 | - https://cdnjs.cloudflare.com/ajax/libs/require.js/2.3.4/require.min.js 75 | -------------------------------------------------------------------------------- /_static/styles.css: -------------------------------------------------------------------------------- 1 | .centerimg50 { 2 | display: block; 3 | margin-left: auto; 4 | margin-right: auto; 5 | width: 50%; /* this is the size of the image */ 6 | } 7 | 8 | .centerimg80 { 9 | display: block; 10 | margin-left: auto; 11 | margin-right: auto; 12 | width: 80%; 13 | } 14 | -------------------------------------------------------------------------------- /_toc.yml: -------------------------------------------------------------------------------- 1 | # Table of contents 2 | # Learn more at https://jupyterbook.org/customize/toc.html 3 | # 4 | 5 | format: jb-book 6 | root: README 7 | title: Introduction to C++ and Numerical Methods 8 | 9 | parts: 10 | - caption: "Introduction to C++" 11 | numbered: false 12 | chapters: 13 | - file: 01-IntroCPP/IntroProgrammingCourse.ipynb 14 | - file: 01-IntroCPP/Resources.ipynb 15 | - file: 01-IntroCPP/CPP-FastPacedIntro.ipynb 16 | - caption: "Numerical Calculus" 17 | numbered: false 18 | chapters: 19 | - file: 02-derivatives/NumericalDifferentiation.ipynb 20 | - file: 03-integration/NumericalIntegration_Basics.ipynb 21 | - caption: "Modern and primitive arrays, and basic Linear Algebra" 22 | numbered: false 23 | chapters: 24 | - file: 04-vector-containers/ModernArrays.ipynb 25 | - file: 05-matrixI/2D-matrices-to-1D-arrays.ipynb 26 | - file: 06-ArrayComputing/ArrayComputing-Valarray.ipynb 27 | - caption: "Linear Algebra and Numerical Libraries" 28 | numbered: false 29 | chapters: 30 | - file: 07-LinearAlgebra/LinearAlgebraEigen.ipynb 31 | - caption: "Ordinary differential equations: Initial value problems" 32 | numbered: false 33 | chapters: 34 | - file: 08-ODE-IVP/InitialValueProblem.ipynb 35 | - file: 09-ODE-IVP-OOP-MolecularDynamics/IntroMolecularDynamics.ipynb 36 | - caption: "Random Numbers and Applications" 37 | numbered: false 38 | chapters: 39 | - file: 10-RandomSystems/RandomNumbers.ipynb 40 | - file: 10-RandomSystems/RandomNumbersInSimulations.ipynb 41 | - caption: "Python introduction" 42 | numbered: false 43 | chapters: 44 | - file: 11-IntroPython/01-IntroProgrammingPython.ipynb 45 | - file: 11-IntroPython/02-IntroProgrammingPython-DataStructs.ipynb 46 | - file: 11-IntroPython/03-matplotlib-intro.ipynb 47 | - file: 11-IntroPython/04-numpy-basic-reduced.ipynb 48 | - file: 11-IntroPython/05-Scipy.ipynb 49 | - caption: "Appendix" 50 | numbered: false 51 | chapters: 52 | - file: A-01-Git/VersionControlGit.ipynb 53 | - file: A-02-Containers/Docker.ipynb 54 | 55 | -------------------------------------------------------------------------------- /header.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "id": "6bdb43a8-bbf2-4f7d-9ad4-c42fdd92de00", 6 | "metadata": {}, 7 | "source": [ 8 | "Before you turn this problem in, make sure everything runs as expected. First, **restart the kernel** (in the menubar, select Kernel$\\rightarrow$Restart) and then **run all cells** (in the menubar, select Cell$\\rightarrow$Run All).\n", 9 | "\n", 10 | "Make sure you fill in any place that says `YOUR CODE HERE` or \"YOUR ANSWER HERE\", as well as your name and collaborators below:" 11 | ] 12 | }, 13 | { 14 | "cell_type": "code", 15 | "execution_count": null, 16 | "id": "cba1c46c-bbc6-446d-b610-8095fc85ffb0", 17 | "metadata": {}, 18 | "outputs": [], 19 | "source": [ 20 | "NAME = \"\"\n", 21 | "COLLABORATORS = \"NONE\"" 22 | ] 23 | } 24 | ], 25 | "metadata": { 26 | "kernelspec": { 27 | "display_name": "Python 3 (ipykernel)", 28 | "language": "python", 29 | "name": "python3" 30 | }, 31 | "language_info": { 32 | "codemirror_mode": { 33 | "name": "ipython", 34 | "version": 3 35 | }, 36 | "file_extension": ".py", 37 | "mimetype": "text/x-python", 38 | "name": "python", 39 | "nbconvert_exporter": "python", 40 | "pygments_lexer": "ipython3", 41 | "version": "3.10.6" 42 | } 43 | }, 44 | "nbformat": 4, 45 | "nbformat_minor": 5 46 | } 47 | -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | #jupyter-book==0.15.1 2 | jupyter-book==1.0.3 3 | notebook 4 | jupyterlab 5 | matplotlib 6 | numpy 7 | ghp-import 8 | #jupyterlab-lsp 9 | jupyterlab-git 10 | pandas 11 | vpython 12 | ipython 13 | seaborn 14 | RISE 15 | pylint 16 | autopep8 17 | #jupyter-collaboration 18 | #jupyterlab-link-share 19 | jupyterlab_vpython 20 | #python-lsp-server 21 | pyright 22 | nb-js-diagrammers 23 | nbgrader 24 | jupyter-repo2docker 25 | -------------------------------------------------------------------------------- /utils/Makefile: -------------------------------------------------------------------------------- 1 | CXX = g++ 2 | #CXXFLAGS = -std=c++11 -Wall -Wextra -Werror -pedantic -O3 3 | CXXFLAGS = -std=c++17 -O3 4 | 5 | %.x: %.o 6 | $(CXX) $(CXXFLAGS) -o $@ $< 7 | 8 | %.o: %.cpp 9 | $(CXX) $(CXXFLAGS) -c -o $@ $< 10 | 11 | clean: 12 | rm -f *.o *.x *.out 13 | -------------------------------------------------------------------------------- /utils/deploy-local-push-remote.yml: -------------------------------------------------------------------------------- 1 | name: deploy-book 2 | on: 3 | push: 4 | branches: 5 | - master 6 | env: 7 | BASE_URL: /${{ github.event.repository.name || 'local-test' }} 8 | concurrency: 9 | group: "pages" 10 | cancel-in-progress: false 11 | jobs: 12 | deploy-book: 13 | runs-on: ubuntu-latest 14 | permissions: 15 | pages: write 16 | id-token: write 17 | steps: 18 | - name: Checkout repository 19 | uses: actions/checkout@v3 20 | 21 | - name: Set up Python 3.11 22 | uses: actions/setup-python@v4 23 | with: 24 | python-version: 3.11 25 | 26 | - name: Install dependencies 27 | run: | 28 | pip install -r requirements.txt 29 | 30 | - name: Build the book 31 | run: | 32 | jupyter-book build . 33 | 34 | # For GitHub environment 35 | - name: Deploy to GitHub Pages 36 | if: ${{ !env.ACT }} 37 | uses: peaceiris/actions-gh-pages@v3.5.9 38 | with: 39 | personal_token: ${{ secrets.ACTIONS_FOR_BOOK_ACCESS_TOKEN }} 40 | publish_dir: ./_build/html 41 | publish_branch: gh-pages 42 | 43 | # Simple direct push for local testing 44 | - name: Direct push to gh-pages 45 | if: ${{ env.ACT }} 46 | run: | 47 | echo "Performing direct push to gh-pages..." 48 | 49 | # Configure git with token 50 | git config --global user.name "GitHub Actions Bot" 51 | git config --global user.email "actions@github.com" 52 | 53 | # Get the repository URL with token 54 | REPO_URL="https://${{ secrets.ACTIONS_FOR_BOOK_ACCESS_TOKEN }}@github.com/${GITHUB_REPOSITORY}.git" 55 | 56 | # Create and switch to gh-pages branch 57 | git checkout -b gh-pages || git checkout gh-pages 58 | 59 | # Remove existing files but keep .git 60 | find . -maxdepth 1 ! -name '.git' ! -name '.' ! -name '..' -exec rm -rf {} + 61 | 62 | # Copy built files to root 63 | cp -r _build/html/* . 64 | 65 | # Add and commit 66 | git add -A 67 | git commit -m "Deploy book to gh-pages" 68 | 69 | # Push directly to gh-pages 70 | git push -f "$REPO_URL" gh-pages 71 | -------------------------------------------------------------------------------- /utils/reset_notebook_theme.sh: -------------------------------------------------------------------------------- 1 | jt -r 2 | -------------------------------------------------------------------------------- /utils/setup_notebook_theme.sh: -------------------------------------------------------------------------------- 1 | THEME=${1:-grade3} 2 | jt -t ${THEME} -fs 115 -altp -tfs 11 -nfs 115 -cellw 88% -T -N 3 | --------------------------------------------------------------------------------