├── .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 | " \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",
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",
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 | "\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 | "\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 | "\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 | "
\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 | "