├── .gitignore ├── 01_introduction.ipynb ├── 02_workspace.ipynb ├── 03_numbers.ipynb ├── 04_python_types.ipynb ├── 05_python_flow.ipynb ├── 06_python_ex1.ipynb ├── 07_pthon_obj.ipynb ├── 08_bundles_ex2.ipynb ├── 09_algorithms.ipynb ├── 10_alg_parity_max.ipynb ├── 11_alg_binary_search.ipynb ├── 12_alg_combinatorics.ipynb ├── 13_bisections_newton.ipynb ├── 14_numpy.ipynb ├── 15_pandas.ipynb ├── 16_vizualization.ipynb ├── 17_linear_reg.ipynb ├── 18_linear_prog.ipynb ├── 19_black_market.ipynb ├── 20_markov.ipynb ├── 21_stationary.ipynb ├── 22_succ_aprx.ipynb ├── 23_mutivariate_newton.ipynb ├── 24_discretization.ipynb ├── 25_newton_bounds.ipynb ├── 26_polyline_class.ipynb ├── 27_dp_intro.ipynb ├── 28_zurcher.ipynb ├── 29_zurcher_code.ipynb ├── 30_cake_ongrid.ipynb ├── 31_approximation.ipynb ├── 32_cake_discretized.ipynb ├── 33_stochastic.ipynb ├── 34_integration.ipynb ├── 35_consumption_savings.ipynb ├── 36_simulations.ipynb ├── 37_dp_theory.ipynb ├── 38_optimization.ipynb ├── 39_euler_timeiter.ipynb ├── 40_cons_sav_continious.ipynb ├── 41_egm.ipynb ├── 42_egm_code.ipynb ├── 43_policy_iter.ipynb ├── 44_newton_kantorovich.ipynb ├── 45_msm_estimation.ipynb ├── 46_nfxp_estimation.ipynb ├── 47_exam_prep.ipynb ├── LICENSE ├── README.md ├── _static ├── data │ ├── beijin_data.dta │ └── recent-grads.csv ├── img │ ├── MCIntegration.png │ ├── PythonLogo.jpg │ ├── bigO.png │ ├── binary.png │ ├── bit_map.gif │ ├── bitshift.png │ ├── bitwise.png │ ├── broadcasting.png │ ├── cake.png │ ├── chicago-booth-oeystein-daljord.jpg │ ├── complexity_classes.png │ ├── complexity_classes_board.png │ ├── composite_simpsons.png │ ├── dag3logo.png │ ├── dataframe.jpg │ ├── float_map.jpg │ ├── github.png │ ├── graph1.png │ ├── graph2.png │ ├── half-precision-floating-point.jpg │ ├── invcdf.png │ ├── kantorovich.jpg │ ├── lab.png │ ├── language_verbosity.png │ ├── lecture.png │ ├── lp1.png │ ├── markov3.png │ ├── nedlermead.png │ ├── newton-cotes.jpg │ ├── newton_fractal.png │ ├── nfxp_manual.png │ ├── numpy_logo.png │ ├── oop.png │ ├── pimc.jpg │ ├── polyhedron2.png │ ├── polyhedron3.png │ ├── python_growth.png │ ├── python_projections.png │ ├── python_usage.png │ ├── randbitmap_computer.png │ ├── randbitmap_true.png │ ├── runtime1.png │ ├── runtime2.png │ ├── th.jpg │ ├── tile1.jpg │ ├── tile2.jpg │ ├── tile3.jpg │ ├── tile4.jpg │ ├── tile5.jpg │ ├── tile6.jpg │ ├── tradeoffs.png │ ├── transportation.png │ ├── viz │ │ ├── 5stage_eqb.png │ │ ├── CDF_2.png │ │ ├── ConsT3NumQuad_sigma0IncVar0.01.png │ │ ├── cpu_vs_N.png │ │ ├── dcegm_value.png │ │ ├── distribution_earnings.png │ │ ├── eqb2bw_pureA.png │ │ ├── eqb2bw_symm.png │ │ ├── eqb_map.png │ │ ├── eqb_n5_randtech-eps-converted-to.png │ │ ├── fig_moments2.png │ │ ├── fig_moments_lastrun.png │ │ ├── map.jpg │ │ ├── octane95_price_composition.png │ │ ├── phelps4.png │ │ ├── plot1-super.png │ │ ├── strava-heatmap-north-and-south-korea.png │ │ ├── trpr2_diversification.png │ │ └── waves_full_data.png │ └── youtube.png ├── include │ ├── algorithm_examples.py │ ├── obj_explore.py │ └── optim.py └── pdf │ ├── DaljordHuPouliotXiao2019.pdf │ ├── Marieke_Mudde_2017_EC.pdf │ ├── Rust_ECMA1987.pdf │ └── Rust_nfxp_man_2000.pdf ├── exercise01.ipynb ├── exercise02.ipynb ├── exercise03.ipynb ├── exercise04.ipynb ├── exercise05.ipynb ├── exercise06.ipynb ├── exercise07.ipynb ├── exercise08.ipynb ├── exercise09.ipynb ├── exercise10.ipynb ├── exercise11.ipynb ├── exercise12.ipynb ├── exercise13.ipynb ├── exercise14.ipynb ├── exercise15.ipynb ├── exercise16.ipynb ├── hse2021task6.ipynb ├── hse2021task8.ipynb └── requirements.txt /.gitignore: -------------------------------------------------------------------------------- 1 | # Byte-compiled / optimized / DLL files 2 | __pycache__/ 3 | *.py[cod] 4 | *$py.class 5 | 6 | # C extensions 7 | *.so 8 | 9 | # Distribution / packaging 10 | .Python 11 | build/ 12 | develop-eggs/ 13 | dist/ 14 | downloads/ 15 | eggs/ 16 | .eggs/ 17 | lib/ 18 | lib64/ 19 | parts/ 20 | sdist/ 21 | var/ 22 | wheels/ 23 | pip-wheel-metadata/ 24 | share/python-wheels/ 25 | *.egg-info/ 26 | .installed.cfg 27 | *.egg 28 | MANIFEST 29 | 30 | # PyInstaller 31 | # Usually these files are written by a python script from a template 32 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 33 | *.manifest 34 | *.spec 35 | 36 | # Installer logs 37 | pip-log.txt 38 | pip-delete-this-directory.txt 39 | 40 | # Unit test / coverage reports 41 | htmlcov/ 42 | .tox/ 43 | .nox/ 44 | .coverage 45 | .coverage.* 46 | .cache 47 | nosetests.xml 48 | coverage.xml 49 | *.cover 50 | *.py,cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | db.sqlite3-journal 63 | 64 | # Flask stuff: 65 | instance/ 66 | .webassets-cache 67 | 68 | # Scrapy stuff: 69 | .scrapy 70 | 71 | # Sphinx documentation 72 | docs/_build/ 73 | 74 | # PyBuilder 75 | target/ 76 | 77 | # Jupyter Notebook 78 | .ipynb_checkpoints 79 | 80 | # IPython 81 | profile_default/ 82 | ipython_config.py 83 | 84 | # pyenv 85 | .python-version 86 | 87 | # pipenv 88 | # According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. 89 | # However, in case of collaboration, if having platform-specific dependencies or dependencies 90 | # having no cross-platform support, pipenv may install dependencies that don't work, or not 91 | # install all needed dependencies. 92 | #Pipfile.lock 93 | 94 | # PEP 582; used by e.g. github.com/David-OConnor/pyflow 95 | __pypackages__/ 96 | 97 | # Celery stuff 98 | celerybeat-schedule 99 | celerybeat.pid 100 | 101 | # SageMath parsed files 102 | *.sage.py 103 | 104 | # Environments 105 | .env 106 | .venv 107 | env/ 108 | venv/ 109 | ENV/ 110 | env.bak/ 111 | venv.bak/ 112 | 113 | # Spyder project settings 114 | .spyderproject 115 | .spyproject 116 | 117 | # Rope project settings 118 | .ropeproject 119 | 120 | # mkdocs documentation 121 | /site 122 | 123 | # mypy 124 | .mypy_cache/ 125 | .dmypy.json 126 | dmypy.json 127 | 128 | # Pyre type checker 129 | .pyre/ 130 | -------------------------------------------------------------------------------- /02_workspace.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "slideshow": { 7 | "slide_type": "slide" 8 | } 9 | }, 10 | "source": [ 11 | "# Foundations of Computational Economics\n", 12 | "\n", 13 | "by Fedor Iskhakov, ANU\n", 14 | "\n", 15 | "" 16 | ] 17 | }, 18 | { 19 | "cell_type": "markdown", 20 | "metadata": { 21 | "slideshow": { 22 | "slide_type": "fragment" 23 | } 24 | }, 25 | "source": [ 26 | "## Local workspace. Jupyter notebooks. Git and GitHub\n", 27 | "\n", 28 | "" 29 | ] 30 | }, 31 | { 32 | "cell_type": "markdown", 33 | "metadata": { 34 | "slideshow": { 35 | "slide_type": "subslide" 36 | } 37 | }, 38 | "source": [ 39 | "\n", 40 | "\n", 41 | "[https://youtu.be/UrZnRv3_IUc](https://youtu.be/UrZnRv3_IUc)\n", 42 | "\n", 43 | "Description: Introduction of Git version control system. Local installation of Python, Anaconda, Jupyter Notebooks, Git and Git GUI. GitHub and GitHub Classroom." 44 | ] 45 | }, 46 | { 47 | "cell_type": "markdown", 48 | "metadata": { 49 | "slideshow": { 50 | "slide_type": "slide" 51 | } 52 | }, 53 | "source": [ 54 | "### Prerequisites\n", 55 | "\n", 56 | "- You have a fairly modern computer: desktop or laptop, Windows or Mac or Linux \n", 57 | "- You have administrative access to this computer (can install programs) \n", 58 | "\n", 59 | "\n", 60 | "1. Find the **Terminal** program in your system \n", 61 | "\n", 62 | "\n", 63 | "> - Mac: Applications >> Utilities >> Terminal \n", 64 | "- Win: Run command.. >> cmd or powershell \n", 65 | "- Unix: should be obvious " 66 | ] 67 | }, 68 | { 69 | "cell_type": "markdown", 70 | "metadata": { 71 | "slideshow": { 72 | "slide_type": "slide" 73 | } 74 | }, 75 | "source": [ 76 | "### Main steps to set up your local workspace\n", 77 | "\n", 78 | "1. Install Python environment manager Anaconda \n", 79 | "1. Install Git and Git GUI \n", 80 | "1. Register at GitHub \n", 81 | "1. Install good text editor \n", 82 | "\n", 83 | "\n", 84 | "[QuantEcon page on setting up local environment](https://python-programming.quantecon.org/getting_started.html)" 85 | ] 86 | }, 87 | { 88 | "cell_type": "markdown", 89 | "metadata": { 90 | "slideshow": { 91 | "slide_type": "slide" 92 | } 93 | }, 94 | "source": [ 95 | "#### 1. Anaconda\n", 96 | "\n", 97 | "- Python \n", 98 | "- Jupyter Notebook \n", 99 | "- Scientific programming libraries \n", 100 | "\n", 101 | "\n", 102 | "Install: [Anaconda Individual Edition](https://www.anaconda.com/products/individual) (free)" 103 | ] 104 | }, 105 | { 106 | "cell_type": "markdown", 107 | "metadata": { 108 | "slideshow": { 109 | "slide_type": "slide" 110 | } 111 | }, 112 | "source": [ 113 | "#### 2. Git and Git GUI\n", 114 | "\n", 115 | "- Git is the *command line* version control software \n", 116 | "- GUI makes Git a lot more practical \n", 117 | "\n", 118 | "\n", 119 | "Install: [Git](https://git-scm.com/)\n", 120 | "\n", 121 | "Choose and install: [Git GUI application](https://git-scm.com/downloads/guis)\n", 122 | "\n", 123 | "Recommended options:\n", 124 | "- [SourceTree](https://www.sourcetreeapp.com/)\n", 125 | "- [GitHub Desktop](https://desktop.github.com/)" 126 | ] 127 | }, 128 | { 129 | "cell_type": "markdown", 130 | "metadata": { 131 | "slideshow": { 132 | "slide_type": "slide" 133 | } 134 | }, 135 | "source": [ 136 | "#### 3. GitHub\n", 137 | "\n", 138 | "- Social coding network website\n", 139 | " - Hosting code\n", 140 | " - Version control + integrations\n", 141 | " - Community of coders\n", 142 | " - Open source community projects \n", 143 | "- Register on [GitHub](https://github.com/join) (if not yet)\n", 144 | " - *Be mindful about using your personal data when registering!*\n", 145 | " - [Apply for Student Pack](https://help.github.com/articles/applying-for-a-student-developer-pack) \n", 146 | "- Course materials will be distributed through GitHub Classroom \n", 147 | "- Unless you opt out, you will submit assignments through GitHub \n", 148 | "\n", 149 | "\n", 150 | "https://github.com/fediskhakov" 151 | ] 152 | }, 153 | { 154 | "cell_type": "markdown", 155 | "metadata": { 156 | "slideshow": { 157 | "slide_type": "slide" 158 | } 159 | }, 160 | "source": [ 161 | "#### 4. Text editor [optional]\n", 162 | "\n", 163 | "- Good text editor is very useful for editing source files \n", 164 | "- Could be done in Jupyter or other default editors, but less convenient \n", 165 | "- Essential for bigger coding projects \n", 166 | "- Good options are:\n", 167 | " - [Atom](https://atom.io/)\n", 168 | " - [VS Code](https://code.visualstudio.com/)\n", 169 | " - [Sublime Text](https://www.sublimetext.com/) (for pay)\n", 170 | " - [PyCharm](https://www.jetbrains.com/pycharm/) (complete IDE) " 171 | ] 172 | }, 173 | { 174 | "cell_type": "markdown", 175 | "metadata": { 176 | "slideshow": { 177 | "slide_type": "slide" 178 | } 179 | }, 180 | "source": [ 181 | "#### Typical single user Git workflow\n", 182 | "\n", 183 | "1. Create/Clone repository \n", 184 | "1. Write/edit (text) files (**CODING HERE**) \n", 185 | "1. Observe diffs \n", 186 | "1. Stage and commit \n", 187 | "1. Upload to server/GitHub by pushing \n", 188 | "1. Back to step 2 \n", 189 | "\n", 190 | "\n", 191 | "- Occasionally dig back in history of diffs to figure smth out \n", 192 | "- Checkout previous version of files \n", 193 | "- Branching for experimental features " 194 | ] 195 | }, 196 | { 197 | "cell_type": "markdown", 198 | "metadata": { 199 | "slideshow": { 200 | "slide_type": "slide" 201 | } 202 | }, 203 | "source": [ 204 | "#### Typical multiple coauthor Git workflow (without GitHub)\n", 205 | "\n", 206 | "1. Create/Clone repository *for each co-author* \n", 207 | "1. Link repos by specifying remotes \n", 208 | "1. Fetch latest changes by others, observe diffs \n", 209 | "1. Merge their work into master \n", 210 | "1. Checkout a particular branch to work in \n", 211 | "1. Write/edit (text) files (**CODING HERE**) \n", 212 | "1. Stage and commit \n", 213 | "1. Merge work completed in other branches into *master* \n", 214 | "1. Back to step 3 " 215 | ] 216 | }, 217 | { 218 | "cell_type": "markdown", 219 | "metadata": { 220 | "slideshow": { 221 | "slide_type": "slide" 222 | } 223 | }, 224 | "source": [ 225 | "#### Typical multiple coauthor Git workflow (with GitHub)\n", 226 | "\n", 227 | "1. Create repository on GitHub \n", 228 | "1. Each author clones from GitHub to create local repository \n", 229 | "1. Fetch and merge (pull) latest changes from GitHub **before doing any work** \n", 230 | "1. Merge their work into master \n", 231 | "1. Checkout a new branch to work in \n", 232 | "1. Write/edit (text) files (**CODING HERE**) \n", 233 | "1. Stage and commit \n", 234 | "1. Push new branch to GitHub, create pull request \n", 235 | "1. Back to step 2 " 236 | ] 237 | }, 238 | { 239 | "cell_type": "markdown", 240 | "metadata": { 241 | "slideshow": { 242 | "slide_type": "slide" 243 | } 244 | }, 245 | "source": [ 246 | "#### Exercise 1\n", 247 | "\n", 248 | "1. Create a test repository on GitHub \n", 249 | "1. Edit README.md file online \n", 250 | "1. Clone repository to the local machine \n", 251 | "1. Observe the history of changes in the local GUI \n", 252 | "1. Make several changes in the working directory \n", 253 | "1. Commit changes \n", 254 | "1. Push updated code to GitHub \n", 255 | "1. Observe the changes on the server " 256 | ] 257 | }, 258 | { 259 | "cell_type": "markdown", 260 | "metadata": { 261 | "slideshow": { 262 | "slide_type": "slide" 263 | } 264 | }, 265 | "source": [ 266 | "#### GitHub Social Coding\n", 267 | "\n", 268 | "- A number of instruments for social coding, beyond Git version control\n", 269 | " - communications with users (*issue tracker*, *wiki pages*)\n", 270 | " - sharing (*code releases*)\n", 271 | " - interactions with other developers (*forking*,*pull requests*,*code reviews*)\n", 272 | " - project web pages (*github pages*) \n", 273 | "- [Interactive minicourse about GitHub](https://lab.github.com/githubtraining/introduction-to-github) [optional] \n", 274 | "- Largely ignored this course " 275 | ] 276 | }, 277 | { 278 | "cell_type": "markdown", 279 | "metadata": { 280 | "slideshow": { 281 | "slide_type": "slide" 282 | } 283 | }, 284 | "source": [ 285 | "#### GitHub Classroom\n", 286 | "\n", 287 | "- The course will use a GitHub add-on software GitHub Classroom \n", 288 | "- Interface for automatic creation of repositories for assignments\n", 289 | " - used for distributing assignment tasks (including midterm and final exam)\n", 290 | " - each student (or group) works in own repository \n", 291 | "- Turn your work in by committing and pushing to this repo\n", 292 | " - Contact me if you want to opt out from using GitHub to submit assignments\n", 293 | " - Alternative way to turn in your work will be made available \n", 294 | "- To accept assignment, follow the distributed *assignment link* " 295 | ] 296 | }, 297 | { 298 | "cell_type": "markdown", 299 | "metadata": { 300 | "slideshow": { 301 | "slide_type": "slide" 302 | } 303 | }, 304 | "source": [ 305 | "#### Jupyter notebooks are great\n", 306 | "\n", 307 | "- Excellent way to present and discuss code\n", 308 | " - this entire course is tough using notebooks \n", 309 | "- Good instrument to develop new ideas\n", 310 | " - especially together with coauthors \n", 311 | "- Saved to disk as JSON files with multiple sections\n", 312 | " - text\n", 313 | " - math and formulas in latex\n", 314 | " - code (different languages are possible)\n", 315 | " - output from the code " 316 | ] 317 | }, 318 | { 319 | "cell_type": "markdown", 320 | "metadata": { 321 | "slideshow": { 322 | "slide_type": "slide" 323 | } 324 | }, 325 | "source": [ 326 | "#### Jupyter notebooks have limitations\n", 327 | "\n", 328 | "- NOT GOOD way to store developed code, use libraries (modules) \n", 329 | "- NOT GOOD for version control\n", 330 | " - changes in metadata are tracked\n", 331 | " - changes in output are tracked\n", 332 | " - merging changed files may break JSON format \n", 333 | "- Require additional tools to work well with Git (see [https://pascalbugnion.net/blog/ipython-notebooks-and-git.html](https://pascalbugnion.net/blog/ipython-notebooks-and-git.html)) \n", 334 | "- We don’t worry about it for the most of the course " 335 | ] 336 | }, 337 | { 338 | "cell_type": "markdown", 339 | "metadata": { 340 | "slideshow": { 341 | "slide_type": "slide" 342 | } 343 | }, 344 | "source": [ 345 | "#### Exercise 2\n", 346 | "\n", 347 | "1. Clone course repository \n", 348 | "1. Run lecture notebook locally \n", 349 | "1. Observe and commit changes \n", 350 | "1. Pull to check if new lecture materials have become available " 351 | ] 352 | }, 353 | { 354 | "cell_type": "markdown", 355 | "metadata": { 356 | "slideshow": { 357 | "slide_type": "slide" 358 | } 359 | }, 360 | "source": [ 361 | "### Further learning resources\n", 362 | "\n", 363 | "- Simple guide to Git [http://rogerdudler.github.io/git-guide/](http://rogerdudler.github.io/git-guide/) \n", 364 | "- Further on version control and Git [https://git-scm.com/doc](https://git-scm.com/doc) \n", 365 | "- More on GitHub [https://guides.github.com/](https://guides.github.com/) \n", 366 | "- Tutorial in Jupyter Notebook\n", 367 | " [https://medium.com/codingthesmartway-com-blog/getting-started-with-jupyter-notebook-for-python-4e7082bd5d46](https://medium.com/codingthesmartway-com-blog/getting-started-with-jupyter-notebook-for-python-4e7082bd5d46) \n", 368 | "- Markdown syntax cheatsheet\n", 369 | " [https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet](https://github.com/adam-p/markdown-here/wiki/Markdown-Cheatsheet) " 370 | ] 371 | } 372 | ], 373 | "metadata": { 374 | "celltoolbar": "Slideshow", 375 | "date": 1612589584.299636, 376 | "download_nb": false, 377 | "filename": "02_workspace.rst", 378 | "filename_with_path": "02_workspace", 379 | "kernelspec": { 380 | "display_name": "Python 3", 381 | "language": "python", 382 | "name": "python3" 383 | }, 384 | "language_info": { 385 | "codemirror_mode": { 386 | "name": "ipython", 387 | "version": 3 388 | }, 389 | "file_extension": ".py", 390 | "mimetype": "text/x-python", 391 | "name": "python", 392 | "nbconvert_exporter": "python", 393 | "pygments_lexer": "ipython3", 394 | "version": "3.7.6" 395 | }, 396 | "title": "Foundations of Computational Economics" 397 | }, 398 | "nbformat": 4, 399 | "nbformat_minor": 4 400 | } 401 | -------------------------------------------------------------------------------- /06_python_ex1.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "slideshow": { 7 | "slide_type": "slide" 8 | } 9 | }, 10 | "source": [ 11 | "# Foundations of Computational Economics #6\n", 12 | "\n", 13 | "by Fedor Iskhakov, ANU\n", 14 | "\n", 15 | "" 16 | ] 17 | }, 18 | { 19 | "cell_type": "markdown", 20 | "metadata": { 21 | "slideshow": { 22 | "slide_type": "fragment" 23 | } 24 | }, 25 | "source": [ 26 | "## Two simple examples\n", 27 | "\n", 28 | "" 29 | ] 30 | }, 31 | { 32 | "cell_type": "markdown", 33 | "metadata": { 34 | "slideshow": { 35 | "slide_type": "subslide" 36 | } 37 | }, 38 | "source": [ 39 | "\n", 40 | "\n", 41 | "[https://youtu.be/UGExPIDwDMs](https://youtu.be/UGExPIDwDMs)\n", 42 | "\n", 43 | "Description: Indexing problem and its inverse, base-N number conversion" 44 | ] 45 | }, 46 | { 47 | "cell_type": "markdown", 48 | "metadata": { 49 | "slideshow": { 50 | "slide_type": "slide" 51 | } 52 | }, 53 | "source": [ 54 | "### Example 1\n", 55 | "\n", 56 | "Code up a function to convert $ (i,j) $ index in a two-dimensional array\n", 57 | "into a single index $ k $ which swipes the matrix by column.\n", 58 | "Also code up the inverse of this function." 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": null, 64 | "metadata": { 65 | "hide-output": false, 66 | "slideshow": { 67 | "slide_type": "slide" 68 | } 69 | }, 70 | "outputs": [], 71 | "source": [ 72 | "# code here" 73 | ] 74 | }, 75 | { 76 | "cell_type": "code", 77 | "execution_count": 27, 78 | "metadata": { 79 | "hide-output": false, 80 | "slideshow": { 81 | "slide_type": "slide" 82 | } 83 | }, 84 | "outputs": [ 85 | { 86 | "name": "stdout", 87 | "output_type": "stream", 88 | "text": [ 89 | "(0,0) --> 0 --> (0,0)\n", 90 | "(0,1) --> 5 --> (0,1)\n", 91 | "(0,2) --> 10 --> (0,2)\n", 92 | "(0,3) --> 15 --> (0,3)\n", 93 | "(0,4) --> 20 --> (0,4)\n", 94 | "(0,5) --> 25 --> (0,5)\n", 95 | "(0,6) --> 30 --> (0,6)\n", 96 | "(0,7) --> 35 --> (0,7)\n", 97 | "(0,8) --> 40 --> (0,8)\n", 98 | "(0,9) --> 45 --> (0,9)\n", 99 | "(1,0) --> 1 --> (1,0)\n", 100 | "(1,1) --> 6 --> (1,1)\n", 101 | "(1,2) --> 11 --> (1,2)\n", 102 | "(1,3) --> 16 --> (1,3)\n", 103 | "(1,4) --> 21 --> (1,4)\n", 104 | "(1,5) --> 26 --> (1,5)\n", 105 | "(1,6) --> 31 --> (1,6)\n", 106 | "(1,7) --> 36 --> (1,7)\n", 107 | "(1,8) --> 41 --> (1,8)\n", 108 | "(1,9) --> 46 --> (1,9)\n", 109 | "(2,0) --> 2 --> (2,0)\n", 110 | "(2,1) --> 7 --> (2,1)\n", 111 | "(2,2) --> 12 --> (2,2)\n", 112 | "(2,3) --> 17 --> (2,3)\n", 113 | "(2,4) --> 22 --> (2,4)\n", 114 | "(2,5) --> 27 --> (2,5)\n", 115 | "(2,6) --> 32 --> (2,6)\n", 116 | "(2,7) --> 37 --> (2,7)\n", 117 | "(2,8) --> 42 --> (2,8)\n", 118 | "(2,9) --> 47 --> (2,9)\n", 119 | "(3,0) --> 3 --> (3,0)\n", 120 | "(3,1) --> 8 --> (3,1)\n", 121 | "(3,2) --> 13 --> (3,2)\n", 122 | "(3,3) --> 18 --> (3,3)\n", 123 | "(3,4) --> 23 --> (3,4)\n", 124 | "(3,5) --> 28 --> (3,5)\n", 125 | "(3,6) --> 33 --> (3,6)\n", 126 | "(3,7) --> 38 --> (3,7)\n", 127 | "(3,8) --> 43 --> (3,8)\n", 128 | "(3,9) --> 48 --> (3,9)\n", 129 | "(4,0) --> 4 --> (4,0)\n", 130 | "(4,1) --> 9 --> (4,1)\n", 131 | "(4,2) --> 14 --> (4,2)\n", 132 | "(4,3) --> 19 --> (4,3)\n", 133 | "(4,4) --> 24 --> (4,4)\n", 134 | "(4,5) --> 29 --> (4,5)\n", 135 | "(4,6) --> 34 --> (4,6)\n", 136 | "(4,7) --> 39 --> (4,7)\n", 137 | "(4,8) --> 44 --> (4,8)\n", 138 | "(4,9) --> 49 --> (4,9)\n" 139 | ] 140 | } 141 | ], 142 | "source": [ 143 | "def k(i,j,m,base0=True):\n", 144 | " '''Convert (i,j) indexes in a two-dimensional array\n", 145 | " with m rows into a single index computed column-wise\n", 146 | " '''\n", 147 | " if base0:\n", 148 | " return j*m + i\n", 149 | " else:\n", 150 | " return (j-1)*m + i\n", 151 | "\n", 152 | "def ik(k,m,base0=True):\n", 153 | " '''Convert k index in a two-dimensional array\n", 154 | " with m rows into a pair of (i,j) indexes\n", 155 | " '''\n", 156 | " if base0:\n", 157 | " j = k//m\n", 158 | " i = k%m\n", 159 | " else:\n", 160 | " j = k//m + 1\n", 161 | " i = k%m\n", 162 | " return i,j\n", 163 | "\n", 164 | "m=5\n", 165 | "for i in range(5):\n", 166 | " for j in range(10):\n", 167 | " k0 = k(i,j,m)\n", 168 | " i1,j1 = ik(k0,m)\n", 169 | " print('(%d,%d) --> %d --> (%d,%d)'%(i,j,k0,i1,j1))" 170 | ] 171 | }, 172 | { 173 | "cell_type": "code", 174 | "execution_count": 28, 175 | "metadata": { 176 | "hide-output": false, 177 | "slideshow": { 178 | "slide_type": "slide" 179 | } 180 | }, 181 | "outputs": [ 182 | { 183 | "name": "stdout", 184 | "output_type": "stream", 185 | "text": [ 186 | "(1,1) --> 1 --> (1,1)\n", 187 | "(1,2) --> 6 --> (1,2)\n", 188 | "(1,3) --> 11 --> (1,3)\n", 189 | "(1,4) --> 16 --> (1,4)\n", 190 | "(1,5) --> 21 --> (1,5)\n", 191 | "(1,6) --> 26 --> (1,6)\n", 192 | "(1,7) --> 31 --> (1,7)\n", 193 | "(1,8) --> 36 --> (1,8)\n", 194 | "(1,9) --> 41 --> (1,9)\n", 195 | "(1,10) --> 46 --> (1,10)\n", 196 | "(2,1) --> 2 --> (2,1)\n", 197 | "(2,2) --> 7 --> (2,2)\n", 198 | "(2,3) --> 12 --> (2,3)\n", 199 | "(2,4) --> 17 --> (2,4)\n", 200 | "(2,5) --> 22 --> (2,5)\n", 201 | "(2,6) --> 27 --> (2,6)\n", 202 | "(2,7) --> 32 --> (2,7)\n", 203 | "(2,8) --> 37 --> (2,8)\n", 204 | "(2,9) --> 42 --> (2,9)\n", 205 | "(2,10) --> 47 --> (2,10)\n", 206 | "(3,1) --> 3 --> (3,1)\n", 207 | "(3,2) --> 8 --> (3,2)\n", 208 | "(3,3) --> 13 --> (3,3)\n", 209 | "(3,4) --> 18 --> (3,4)\n", 210 | "(3,5) --> 23 --> (3,5)\n", 211 | "(3,6) --> 28 --> (3,6)\n", 212 | "(3,7) --> 33 --> (3,7)\n", 213 | "(3,8) --> 38 --> (3,8)\n", 214 | "(3,9) --> 43 --> (3,9)\n", 215 | "(3,10) --> 48 --> (3,10)\n", 216 | "(4,1) --> 4 --> (4,1)\n", 217 | "(4,2) --> 9 --> (4,2)\n", 218 | "(4,3) --> 14 --> (4,3)\n", 219 | "(4,4) --> 19 --> (4,4)\n", 220 | "(4,5) --> 24 --> (4,5)\n", 221 | "(4,6) --> 29 --> (4,6)\n", 222 | "(4,7) --> 34 --> (4,7)\n", 223 | "(4,8) --> 39 --> (4,8)\n", 224 | "(4,9) --> 44 --> (4,9)\n", 225 | "(4,10) --> 49 --> (4,10)\n", 226 | "(5,1) --> 5 --> (0,2)\n", 227 | "(5,2) --> 10 --> (0,3)\n", 228 | "(5,3) --> 15 --> (0,4)\n", 229 | "(5,4) --> 20 --> (0,5)\n", 230 | "(5,5) --> 25 --> (0,6)\n", 231 | "(5,6) --> 30 --> (0,7)\n", 232 | "(5,7) --> 35 --> (0,8)\n", 233 | "(5,8) --> 40 --> (0,9)\n", 234 | "(5,9) --> 45 --> (0,10)\n", 235 | "(5,10) --> 50 --> (0,11)\n" 236 | ] 237 | } 238 | ], 239 | "source": [ 240 | "# Running the check for base1 reveals the bug when i=5!\n", 241 | "\n", 242 | "m=5\n", 243 | "for i in range(1,m+1):\n", 244 | " for j in range(1,11):\n", 245 | " k0 = k(i,j,m,base0=False)\n", 246 | " i1,j1 = ik(k0,m,base0=False)\n", 247 | " print('(%d,%d) --> %d --> (%d,%d)'%(i,j,k0,i1,j1))\n", 248 | "\n", 249 | "# So, the correct inverse conversion in base1 should be:\n", 250 | "\n", 251 | "def ik(k,m,base0=True):\n", 252 | " '''Convert k index in a two-dimensional array\n", 253 | " with m rows into a pair of (i,j) indexes\n", 254 | " '''\n", 255 | " if base0:\n", 256 | " j = k//m\n", 257 | " i = k%m\n", 258 | " else:\n", 259 | " j = (k-1)//m + 1\n", 260 | " i = (k-1)%m + 1\n", 261 | " return i,j" 262 | ] 263 | }, 264 | { 265 | "cell_type": "code", 266 | "execution_count": 29, 267 | "metadata": {}, 268 | "outputs": [ 269 | { 270 | "name": "stdout", 271 | "output_type": "stream", 272 | "text": [ 273 | "(1,1) --> 1 --> (1,1)\n", 274 | "(1,2) --> 6 --> (1,2)\n", 275 | "(1,3) --> 11 --> (1,3)\n", 276 | "(1,4) --> 16 --> (1,4)\n", 277 | "(2,1) --> 2 --> (2,1)\n", 278 | "(2,2) --> 7 --> (2,2)\n", 279 | "(2,3) --> 12 --> (2,3)\n", 280 | "(2,4) --> 17 --> (2,4)\n", 281 | "(3,1) --> 3 --> (3,1)\n", 282 | "(3,2) --> 8 --> (3,2)\n", 283 | "(3,3) --> 13 --> (3,3)\n", 284 | "(3,4) --> 18 --> (3,4)\n", 285 | "(4,1) --> 4 --> (4,1)\n", 286 | "(4,2) --> 9 --> (4,2)\n", 287 | "(4,3) --> 14 --> (4,3)\n", 288 | "(4,4) --> 19 --> (4,4)\n", 289 | "(5,1) --> 5 --> (5,1)\n", 290 | "(5,2) --> 10 --> (5,2)\n", 291 | "(5,3) --> 15 --> (5,3)\n", 292 | "(5,4) --> 20 --> (5,4)\n" 293 | ] 294 | } 295 | ], 296 | "source": [ 297 | "m=5\n", 298 | "for i in range(1,m+1):\n", 299 | " for j in range(1,5):\n", 300 | " k0 = k(i,j,m,base0=False)\n", 301 | " i1,j1 = ik(k0,m,base0=False)\n", 302 | " print('(%d,%d) --> %d --> (%d,%d)'%(i,j,k0,i1,j1)) " 303 | ] 304 | }, 305 | { 306 | "cell_type": "markdown", 307 | "metadata": { 308 | "slideshow": { 309 | "slide_type": "slide" 310 | } 311 | }, 312 | "source": [ 313 | "### Example 2\n", 314 | "\n", 315 | "Write a function to converter a decimal number into a given base. Return the result as string." 316 | ] 317 | }, 318 | { 319 | "cell_type": "code", 320 | "execution_count": null, 321 | "metadata": { 322 | "hide-output": false, 323 | "slideshow": { 324 | "slide_type": "slide" 325 | } 326 | }, 327 | "outputs": [], 328 | "source": [ 329 | "# code here" 330 | ] 331 | }, 332 | { 333 | "cell_type": "code", 334 | "execution_count": null, 335 | "metadata": { 336 | "hide-output": false, 337 | "slideshow": { 338 | "slide_type": "slide" 339 | } 340 | }, 341 | "outputs": [], 342 | "source": [ 343 | "def baseN(x,base=2):\n", 344 | " '''Converts given number to given base'''\n", 345 | " digits = [str(i) for i in range(10)] + [chr(i) for i in range(97,123)]\n", 346 | " assert 2 <= base <= len(digits),'Number base must be between 2 and %d'%(len(digits))\n", 347 | " if x == 0:\n", 348 | " return '0'\n", 349 | " out = []\n", 350 | " while x>0:\n", 351 | " i = x%base\n", 352 | " out.append(digits[i])\n", 353 | " x = x//base\n", 354 | " return ''.join(out[::-1])\n", 355 | "\n", 356 | "for n in [3,8,35,574,1023523,9999]:\n", 357 | " for b in range(36,1,-4):\n", 358 | " print('%d in base %d is %s' % (n,b,baseN(n,b)))\n", 359 | " print()" 360 | ] 361 | } 362 | ], 363 | "metadata": { 364 | "celltoolbar": "Slideshow", 365 | "date": 1628246895.2099788, 366 | "filename": "06_python_ex1.rst", 367 | "kernelspec": { 368 | "display_name": "Python 3", 369 | "language": "python", 370 | "name": "python3" 371 | }, 372 | "language_info": { 373 | "codemirror_mode": { 374 | "name": "ipython", 375 | "version": 3 376 | }, 377 | "file_extension": ".py", 378 | "mimetype": "text/x-python", 379 | "name": "python", 380 | "nbconvert_exporter": "python", 381 | "pygments_lexer": "ipython3", 382 | "version": "3.7.6" 383 | }, 384 | "title": "Foundations of Computational Economics #6" 385 | }, 386 | "nbformat": 4, 387 | "nbformat_minor": 4 388 | } 389 | -------------------------------------------------------------------------------- /10_alg_parity_max.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "slideshow": { 7 | "slide_type": "slide" 8 | } 9 | }, 10 | "source": [ 11 | "# Foundations of Computational Economics #10\n", 12 | "\n", 13 | "by Fedor Iskhakov, ANU\n", 14 | "\n", 15 | "" 16 | ] 17 | }, 18 | { 19 | "cell_type": "markdown", 20 | "metadata": { 21 | "slideshow": { 22 | "slide_type": "fragment" 23 | } 24 | }, 25 | "source": [ 26 | "## Two simple algorithms: parity and max\n", 27 | "\n", 28 | "" 29 | ] 30 | }, 31 | { 32 | "cell_type": "markdown", 33 | "metadata": { 34 | "slideshow": { 35 | "slide_type": "subslide" 36 | } 37 | }, 38 | "source": [ 39 | "\n", 40 | "\n", 41 | "[https://youtu.be/fKFZZc77if0](https://youtu.be/fKFZZc77if0)\n", 42 | "\n", 43 | "Description: Parity of a number, bitwise operations in Python. Finding maximum in an array." 44 | ] 45 | }, 46 | { 47 | "cell_type": "markdown", 48 | "metadata": { 49 | "slideshow": { 50 | "slide_type": "slide" 51 | } 52 | }, 53 | "source": [ 54 | "### Divisibility by number base\n", 55 | "\n", 56 | "Whether a decimal number is divisible by 10 can be easily seen from its last digit.\n", 57 | "\n", 58 | "Similarly, whether a binary number is divisible by 2 can be easily seen from its last digit.\n", 59 | "\n", 60 | "**If last digit of a number is 0, it is divisible by its base!**" 61 | ] 62 | }, 63 | { 64 | "cell_type": "markdown", 65 | "metadata": { 66 | "slideshow": { 67 | "slide_type": "slide" 68 | } 69 | }, 70 | "source": [ 71 | "#### Parity of a number algorithm\n", 72 | "\n", 73 | "1. Convert the number to binary \n", 74 | "1. Check if last digit is zero \n", 75 | "\n", 76 | "\n", 77 | "- All integers already have a clear binary representation \n", 78 | "\n", 79 | "\n", 80 | "*This algorithm only applies to integers*" 81 | ] 82 | }, 83 | { 84 | "cell_type": "markdown", 85 | "metadata": { 86 | "slideshow": { 87 | "slide_type": "slide" 88 | } 89 | }, 90 | "source": [ 91 | "### Bitwise operations in Python\n", 92 | "\n", 93 | "- bitwise AND **&** \n", 94 | "- bitwise OR **|** \n", 95 | "- bitwise XOR **^** \n", 96 | "- bitwise NOT **~** (including sign bit!) \n", 97 | "- right shift **>>** \n", 98 | "- left shift **<<** (without overflow!) " 99 | ] 100 | }, 101 | { 102 | "cell_type": "markdown", 103 | "metadata": { 104 | "slideshow": { 105 | "slide_type": "slide" 106 | } 107 | }, 108 | "source": [ 109 | "#### Bitwise AND, OR and XOR\n", 110 | "\n", 111 | "" 112 | ] 113 | }, 114 | { 115 | "cell_type": "code", 116 | "execution_count": 1, 117 | "metadata": { 118 | "hide-output": false, 119 | "slideshow": { 120 | "slide_type": "slide" 121 | } 122 | }, 123 | "outputs": [ 124 | { 125 | "name": "stdout", 126 | "output_type": "stream", 127 | "text": [ 128 | " a = 3 (0011)\n", 129 | " b = 5 (0101)\n", 130 | "a&b = 1 (0001)\n" 131 | ] 132 | } 133 | ], 134 | "source": [ 135 | "# bitwise logic\n", 136 | "a,b = 3,5 # 3=0011, 5=0101\n", 137 | "print(' a = {0:d} ({0:04b})\\n b = {1:d} ({1:04b})'.format(a,b))\n", 138 | "print('a&b = {0:d} ({0:04b})'.format(a&b))\n", 139 | "# print('a|b = {0:d} ({0:04b})'.format(a|b))\n", 140 | "# print('a^b = {0:d} ({0:04b})'.format(a^b))" 141 | ] 142 | }, 143 | { 144 | "cell_type": "markdown", 145 | "metadata": { 146 | "slideshow": { 147 | "slide_type": "slide" 148 | } 149 | }, 150 | "source": [ 151 | "#### Bit shifts in Python\n", 152 | "\n", 153 | "" 154 | ] 155 | }, 156 | { 157 | "cell_type": "markdown", 158 | "metadata": { 159 | "slideshow": { 160 | "slide_type": "slide" 161 | } 162 | }, 163 | "source": [ 164 | "#### Replacing arithmetic operations with bit operations\n", 165 | "\n", 166 | "Is it possible?\n", 167 | "Which operations can be done in this *geeky* way?" 168 | ] 169 | }, 170 | { 171 | "cell_type": "code", 172 | "execution_count": 2, 173 | "metadata": { 174 | "hide-output": false, 175 | "slideshow": { 176 | "slide_type": "slide" 177 | } 178 | }, 179 | "outputs": [ 180 | { 181 | "name": "stdout", 182 | "output_type": "stream", 183 | "text": [ 184 | " a = 227 (0000000011100011)\n", 185 | " b = 113 (0000000001110001)\n", 186 | "\n", 187 | " a = 227 (0000000011100011)\n", 188 | " b = 908 (0000001110001100)\n", 189 | "\n" 190 | ] 191 | } 192 | ], 193 | "source": [ 194 | "# bit shifts\n", 195 | "a = 0b11100011\n", 196 | "b = a >> 1\n", 197 | "print(' a = {0:4d} ({0:016b})\\n b = {1:4d} ({1:016b})\\n'.format(a,b))\n", 198 | "b = a << 2\n", 199 | "print(' a = {0:4d} ({0:016b})\\n b = {1:4d} ({1:016b})\\n'.format(a,b))" 200 | ] 201 | }, 202 | { 203 | "cell_type": "code", 204 | "execution_count": 3, 205 | "metadata": { 206 | "hide-output": false, 207 | "slideshow": { 208 | "slide_type": "slide" 209 | } 210 | }, 211 | "outputs": [ 212 | { 213 | "name": "stdout", 214 | "output_type": "stream", 215 | "text": [ 216 | " a = 227 (0000000011100011)\n", 217 | "a//2 = 113, a>>1 = 113\n", 218 | "a//4 = 56, a>>2 = 56\n", 219 | "a//8 = 28, a>>3 = 28\n", 220 | "a//16 = 14, a>>4 = 14\n", 221 | "a//32 = 7, a>>5 = 7\n", 222 | "a//64 = 3, a>>6 = 3\n", 223 | "a//128 = 1, a>>7 = 1\n", 224 | "a//256 = 0, a>>8 = 0\n", 225 | "a//512 = 0, a>>9 = 0\n" 226 | ] 227 | } 228 | ], 229 | "source": [ 230 | "# arythmetic operations with bit shifts\n", 231 | "a = 0b11100011\n", 232 | "print(' a = {0:4d} ({0:016b})'.format(a))\n", 233 | "\n", 234 | "for i in range(1,10):\n", 235 | " x = 2**i\n", 236 | " d = a//x\n", 237 | " s = a>>i\n", 238 | " print('a//%d = %d, a>>%d = %d' % (x,d,i,s))" 239 | ] 240 | }, 241 | { 242 | "cell_type": "markdown", 243 | "metadata": { 244 | "slideshow": { 245 | "slide_type": "slide" 246 | } 247 | }, 248 | "source": [ 249 | "### Parity algorithm\n", 250 | "\n", 251 | "Run a single bitwise AND operation to\n", 252 | "compare against **0b0000001** which is simply 1 in decimal\n", 253 | "\n", 254 | "Complexity is constant because only one bit must be checked!\n", 255 | "\n", 256 | "*However, when running AND are all bits checked?*" 257 | ] 258 | }, 259 | { 260 | "cell_type": "code", 261 | "execution_count": 4, 262 | "metadata": { 263 | "hide-output": false, 264 | "slideshow": { 265 | "slide_type": "slide" 266 | } 267 | }, 268 | "outputs": [], 269 | "source": [ 270 | "# parity check\n", 271 | "def parity (n,verbose=False):\n", 272 | " '''Returns 1 if passed integer number is odd\n", 273 | " '''\n", 274 | " pass" 275 | ] 276 | }, 277 | { 278 | "cell_type": "code", 279 | "execution_count": 7, 280 | "metadata": { 281 | "hide-output": false, 282 | "slideshow": { 283 | "slide_type": "slide" 284 | } 285 | }, 286 | "outputs": [ 287 | { 288 | "name": "stdout", 289 | "output_type": "stream", 290 | "text": [ 291 | "n = 2 (00000010), parity=0\n", 292 | "n = 4 (00000100), parity=0\n", 293 | "n = 7 (00000111), parity=1\n", 294 | "n = 32 (00100000), parity=0\n", 295 | "n = 543 (1000011111), parity=1\n", 296 | "n = 671 (1010011111), parity=1\n", 297 | "n = 780 (1100001100), parity=0\n" 298 | ] 299 | } 300 | ], 301 | "source": [ 302 | "# check parity of various numbers\n", 303 | "for n in [2,4,7,32,543,671,780]:\n", 304 | " print('n = {0:5d} ({0:08b}), parity={1:d}'.format(n,parity(n)))" 305 | ] 306 | }, 307 | { 308 | "cell_type": "code", 309 | "execution_count": 8, 310 | "metadata": { 311 | "hide-output": false, 312 | "slideshow": { 313 | "slide_type": "slide" 314 | } 315 | }, 316 | "outputs": [], 317 | "source": [ 318 | "def parity (n,verbose=False):\n", 319 | " '''Returns 1 if passed integer number is odd\n", 320 | " '''\n", 321 | " if not isinstance(n, int): raise TypeError('Only integers in parity()')\n", 322 | " if verbose: print('n = {:08b}'.format(n)) # print binary form of the number\n", 323 | " return n & 1 # bitwise and operation returns the value of last bit" 324 | ] 325 | }, 326 | { 327 | "cell_type": "markdown", 328 | "metadata": { 329 | "slideshow": { 330 | "slide_type": "slide" 331 | } 332 | }, 333 | "source": [ 334 | "### Finding max/min in a list\n", 335 | "\n", 336 | "- In the worst case, there is no way to avoid checking *all elements* \n", 337 | "- Complexity is linear in the number of elements on the list " 338 | ] 339 | }, 340 | { 341 | "cell_type": "code", 342 | "execution_count": 7, 343 | "metadata": { 344 | "hide-output": false, 345 | "slideshow": { 346 | "slide_type": "slide" 347 | } 348 | }, 349 | "outputs": [], 350 | "source": [ 351 | "def maximum_from_list (vars):\n", 352 | " '''Returns the maximum from a list of values\n", 353 | " '''\n", 354 | " pass" 355 | ] 356 | }, 357 | { 358 | "cell_type": "code", 359 | "execution_count": 10, 360 | "metadata": { 361 | "hide-output": false, 362 | "slideshow": { 363 | "slide_type": "slide" 364 | } 365 | }, 366 | "outputs": [ 367 | { 368 | "name": "stdout", 369 | "output_type": "stream", 370 | "text": [ 371 | "Maximum in [40.36631825 33.1923305 4.85928511 31.26526949 38.56821075 92.47304391\n", 372 | " 61.57887596 12.81310827 92.20711143 45.12116267] is 92.47\n", 373 | "Maximum in [36.19221981 68.39217716 71.45549904 59.94828759 17.04806836 42.36644573\n", 374 | " 65.48883833 91.13163144 57.13898149 67.50339454] is 91.13\n", 375 | "Maximum in [75.48095297 70.96067478 15.19709572 94.50537863 79.74015518 99.65516414\n", 376 | " 88.51336519 38.89378926 22.89769873 4.56590212] is 99.66\n", 377 | "Maximum in [46.96531804 30.02051975 20.0643693 11.77139318 77.8880612 1.88485342\n", 378 | " 82.53652171 56.93653459 79.10377169 33.83294574] is 82.54\n", 379 | "Maximum in [ 3.46403787 25.77379166 79.32433345 96.9859477 41.5598842 17.76082696\n", 380 | " 34.37472047 2.59704741 71.6989639 43.67998844] is 96.99\n" 381 | ] 382 | } 383 | ], 384 | "source": [ 385 | "# find maximum in some random lists\n", 386 | "import numpy as np\n", 387 | "for i in range(5):\n", 388 | " list = np.random.uniform(low=0.0, high=100.0, size=10)\n", 389 | " m = maximum_from_list(list)\n", 390 | " print('Maximum in {} is {:.2f}'.format(list,m))" 391 | ] 392 | }, 393 | { 394 | "cell_type": "code", 395 | "execution_count": 9, 396 | "metadata": { 397 | "hide-output": false, 398 | "slideshow": { 399 | "slide_type": "slide" 400 | } 401 | }, 402 | "outputs": [], 403 | "source": [ 404 | "def maximum_from_list (vars):\n", 405 | " '''Returns the maximum from a list of values\n", 406 | " '''\n", 407 | " m=float('-inf') # init with the worst value\n", 408 | " for v in vars:\n", 409 | " if v > m: m = v\n", 410 | " return m" 411 | ] 412 | }, 413 | { 414 | "cell_type": "markdown", 415 | "metadata": { 416 | "slideshow": { 417 | "slide_type": "slide" 418 | } 419 | }, 420 | "source": [ 421 | "### Further learning resources\n", 422 | "\n", 423 | "- Formatting strings\n", 424 | " [https://www.digitalocean.com/community/tutorials/how-to-use-string-formatters-in-python-3](https://www.digitalocean.com/community/tutorials/how-to-use-string-formatters-in-python-3) \n", 425 | "- Bitwise operations post on Geeksforgeeks\n", 426 | " [https://www.geeksforgeeks.org/python-bitwise-operators/](https://www.geeksforgeeks.org/python-bitwise-operators/) " 427 | ] 428 | } 429 | ], 430 | "metadata": { 431 | "celltoolbar": "Slideshow", 432 | "date": 1612589584.636859, 433 | "download_nb": false, 434 | "filename": "10_alg_parity_max.rst", 435 | "filename_with_path": "10_alg_parity_max", 436 | "kernelspec": { 437 | "display_name": "Python 3", 438 | "language": "python", 439 | "name": "python3" 440 | }, 441 | "language_info": { 442 | "codemirror_mode": { 443 | "name": "ipython", 444 | "version": 3 445 | }, 446 | "file_extension": ".py", 447 | "mimetype": "text/x-python", 448 | "name": "python", 449 | "nbconvert_exporter": "python", 450 | "pygments_lexer": "ipython3", 451 | "version": "3.7.6" 452 | }, 453 | "title": "Foundations of Computational Economics #10" 454 | }, 455 | "nbformat": 4, 456 | "nbformat_minor": 4 457 | } 458 | -------------------------------------------------------------------------------- /11_alg_binary_search.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "slideshow": { 7 | "slide_type": "slide" 8 | } 9 | }, 10 | "source": [ 11 | "# Foundations of Computational Economics #11\n", 12 | "\n", 13 | "by Fedor Iskhakov, ANU\n", 14 | "\n", 15 | "" 16 | ] 17 | }, 18 | { 19 | "cell_type": "markdown", 20 | "metadata": { 21 | "slideshow": { 22 | "slide_type": "fragment" 23 | } 24 | }, 25 | "source": [ 26 | "## Binary search algorithm\n", 27 | "\n", 28 | "" 29 | ] 30 | }, 31 | { 32 | "cell_type": "markdown", 33 | "metadata": { 34 | "slideshow": { 35 | "slide_type": "subslide" 36 | } 37 | }, 38 | "source": [ 39 | "\n", 40 | "\n", 41 | "[https://youtu.be/eTmQBpN-eyk](https://youtu.be/eTmQBpN-eyk)\n", 42 | "\n", 43 | "Description: Binary search. Other divide and conquer algorithms. Recursion." 44 | ] 45 | }, 46 | { 47 | "cell_type": "markdown", 48 | "metadata": { 49 | "slideshow": { 50 | "slide_type": "slide" 51 | } 52 | }, 53 | "source": [ 54 | "### Divide and conquer algorithms (DAC)\n", 55 | "\n", 56 | "1. **Divide** the problem into subproblems \n", 57 | "1. **Solve/conquer** each subproblem recursively \n", 58 | "1. **Combine** solutions of subproblems together " 59 | ] 60 | }, 61 | { 62 | "cell_type": "code", 63 | "execution_count": 1, 64 | "metadata": { 65 | "hide-output": false, 66 | "slideshow": { 67 | "slide_type": "slide" 68 | } 69 | }, 70 | "outputs": [], 71 | "source": [ 72 | "# simple example of DAC algorithm\n", 73 | "def sum_list(l):\n", 74 | " '''Summing the elements of the list using DAC algorithm\n", 75 | " '''\n", 76 | " pass\n", 77 | "\n", 78 | "sum_list(list(range(16)))" 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "execution_count": 2, 84 | "metadata": { 85 | "hide-output": false, 86 | "slideshow": { 87 | "slide_type": "slide" 88 | } 89 | }, 90 | "outputs": [ 91 | { 92 | "name": "stdout", 93 | "output_type": "stream", 94 | "text": [ 95 | "dividing [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] into [0, 1, 2, 3, 4, 5, 6, 7] and [8, 9, 10, 11, 12, 13, 14, 15]\n", 96 | "dividing [0, 1, 2, 3, 4, 5, 6, 7] into [0, 1, 2, 3] and [4, 5, 6, 7]\n", 97 | "dividing [0, 1, 2, 3] into [0, 1] and [2, 3]\n", 98 | "dividing [0, 1] into [0] and [1]\n", 99 | "sum of [0, 1] is 1.00\n", 100 | "dividing [2, 3] into [2] and [3]\n", 101 | "sum of [2, 3] is 5.00\n", 102 | "sum of [0, 1, 2, 3] is 6.00\n", 103 | "dividing [4, 5, 6, 7] into [4, 5] and [6, 7]\n", 104 | "dividing [4, 5] into [4] and [5]\n", 105 | "sum of [4, 5] is 9.00\n", 106 | "dividing [6, 7] into [6] and [7]\n", 107 | "sum of [6, 7] is 13.00\n", 108 | "sum of [4, 5, 6, 7] is 22.00\n", 109 | "sum of [0, 1, 2, 3, 4, 5, 6, 7] is 28.00\n", 110 | "dividing [8, 9, 10, 11, 12, 13, 14, 15] into [8, 9, 10, 11] and [12, 13, 14, 15]\n", 111 | "dividing [8, 9, 10, 11] into [8, 9] and [10, 11]\n", 112 | "dividing [8, 9] into [8] and [9]\n", 113 | "sum of [8, 9] is 17.00\n", 114 | "dividing [10, 11] into [10] and [11]\n", 115 | "sum of [10, 11] is 21.00\n", 116 | "sum of [8, 9, 10, 11] is 38.00\n", 117 | "dividing [12, 13, 14, 15] into [12, 13] and [14, 15]\n", 118 | "dividing [12, 13] into [12] and [13]\n", 119 | "sum of [12, 13] is 25.00\n", 120 | "dividing [14, 15] into [14] and [15]\n", 121 | "sum of [14, 15] is 29.00\n", 122 | "sum of [12, 13, 14, 15] is 54.00\n", 123 | "sum of [8, 9, 10, 11, 12, 13, 14, 15] is 92.00\n", 124 | "sum of [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15] is 120.00\n" 125 | ] 126 | }, 127 | { 128 | "data": { 129 | "text/plain": [ 130 | "120" 131 | ] 132 | }, 133 | "execution_count": 2, 134 | "metadata": {}, 135 | "output_type": "execute_result" 136 | } 137 | ], 138 | "source": [ 139 | "# simple example of DAC algorithm\n", 140 | "def sum_list(l):\n", 141 | " '''Summing the elements of the list using DAC algorithm\n", 142 | " '''\n", 143 | " if len(l)==1:\n", 144 | " return l[0] # sum of list of one element\n", 145 | " j = len(l)//2 # devide list in two\n", 146 | " print('dividing %r into %r and %r' % (l,l[:j],l[j:]), flush=True)\n", 147 | " s = sum_list(l[:j]) + sum_list(l[j:])\n", 148 | " print('sum of %r is %1.2f' % (l,s), flush=True)\n", 149 | " return s\n", 150 | "\n", 151 | "sum_list(list(range(16)))" 152 | ] 153 | }, 154 | { 155 | "cell_type": "markdown", 156 | "metadata": { 157 | "slideshow": { 158 | "slide_type": "slide" 159 | } 160 | }, 161 | "source": [ 162 | "### Complexity of DAC\n", 163 | "\n", 164 | "" 165 | ] 166 | }, 167 | { 168 | "cell_type": "markdown", 169 | "metadata": { 170 | "slideshow": { 171 | "slide_type": "slide" 172 | } 173 | }, 174 | "source": [ 175 | "### Typical DAC algorithms\n", 176 | "\n", 177 | "- Binary search \n", 178 | "- Quicksort and merge sort \n", 179 | "- Fast Fourier transform (FTT) algorithm \n", 180 | "- Karatsuba fast multiplication algorithm " 181 | ] 182 | }, 183 | { 184 | "cell_type": "markdown", 185 | "metadata": { 186 | "slideshow": { 187 | "slide_type": "slide" 188 | } 189 | }, 190 | "source": [ 191 | "### Binary search\n", 192 | "\n", 193 | "Inputs: sorted list of numbers, and a value to find\n", 194 | "\n", 195 | "1. Find middle point \n", 196 | "1. If the sought value is below, reduce the list to the lower half \n", 197 | "1. If the sought value is above, reduce the list to the upper half " 198 | ] 199 | }, 200 | { 201 | "cell_type": "code", 202 | "execution_count": 3, 203 | "metadata": { 204 | "hide-output": false, 205 | "slideshow": { 206 | "slide_type": "slide" 207 | } 208 | }, 209 | "outputs": [], 210 | "source": [ 211 | "def binary_search(list=[0,1],val=0):\n", 212 | " pass" 213 | ] 214 | }, 215 | { 216 | "cell_type": "code", 217 | "execution_count": 2, 218 | "metadata": { 219 | "hide-output": false, 220 | "slideshow": { 221 | "slide_type": "slide" 222 | } 223 | }, 224 | "outputs": [ 225 | { 226 | "name": "stdout", 227 | "output_type": "stream", 228 | "text": [ 229 | "list = [ 1 18 27 28 33 35 39 41 50 52 56 61 75 89 94 99]\n", 230 | "searching for [52]\n", 231 | "step 0: gr[i1=0]=1, gr[i2=15]=99, gr[j=7]=41\n", 232 | "step 1: gr[i1=7]=41, gr[i2=15]=99, gr[j=11]=61\n", 233 | "step 2: gr[i1=7]=41, gr[i2=11]=61, gr[j=9]=52\n", 234 | "Searched for 52, found x[9]=52\n" 235 | ] 236 | } 237 | ], 238 | "source": [ 239 | "import numpy as np\n", 240 | "N = 16\n", 241 | "# random sorted sequence of integers up to 100\n", 242 | "x = np.random.choice(100,size=N,replace=False)\n", 243 | "x = np.sort(x)\n", 244 | "# random choice of one number/index\n", 245 | "k0 = np.random.choice(N,size=1)\n", 246 | "\n", 247 | "k1 = binary_search(list=x,val=x[k0])\n", 248 | "print(\"Searched for %d, found x[%d]=%d\"%(x[k0],k1,x[k1]))" 249 | ] 250 | }, 251 | { 252 | "cell_type": "code", 253 | "execution_count": 1, 254 | "metadata": { 255 | "hide-output": false, 256 | "slideshow": { 257 | "slide_type": "slide" 258 | } 259 | }, 260 | "outputs": [], 261 | "source": [ 262 | "def binary_search(list=[0,1],val=0,verbose=True):\n", 263 | " '''Returns the index of val on the sorted list\n", 264 | " Optional delay introduces a delay (in microsecond)\n", 265 | " '''\n", 266 | " i1,i2 = 0,len(list)-1\n", 267 | " if val==list[i1]: return i1\n", 268 | " if val==list[i2]: return i2\n", 269 | " j=(i1+i2)//2\n", 270 | " if verbose:\n", 271 | " print('list =',list)\n", 272 | " print('searching for',val)\n", 273 | " k=0\n", 274 | " print('step %d: gr[i1=%d]=%d, gr[i2=%d]=%d, gr[j=%d]=%d' % (k,i1,list[i1],i2,list[i2],j,list[j]))\n", 275 | " while list[j]!=val:\n", 276 | " if val>list[j]:\n", 277 | " i1 = j\n", 278 | " else:\n", 279 | " i2 = j\n", 280 | " j = (i1+i2)//2 # divide in half\n", 281 | " if verbose:\n", 282 | " k +=1\n", 283 | " print('step %d: gr[i1=%d]=%d, gr[i2=%d]=%d, gr[j=%d]=%d' % (k,i1,list[i1],i2,list[i2],j,list[j]))\n", 284 | " return j" 285 | ] 286 | }, 287 | { 288 | "cell_type": "markdown", 289 | "metadata": { 290 | "slideshow": { 291 | "slide_type": "slide" 292 | } 293 | }, 294 | "source": [ 295 | "#### Further learning resources\n", 296 | "\n", 297 | "- Divide and conquer algorithms by Brandon Skerritt\n", 298 | " [https://skerritt.blog/divide-and-conquer-algorithms/](https://skerritt.blog/divide-and-conquer-algorithms/) " 299 | ] 300 | } 301 | ], 302 | "metadata": { 303 | "celltoolbar": "Slideshow", 304 | "date": 1612589584.667138, 305 | "download_nb": false, 306 | "filename": "11_alg_binary_search.rst", 307 | "filename_with_path": "11_alg_binary_search", 308 | "kernelspec": { 309 | "display_name": "Python 3", 310 | "language": "python", 311 | "name": "python3" 312 | }, 313 | "language_info": { 314 | "codemirror_mode": { 315 | "name": "ipython", 316 | "version": 3 317 | }, 318 | "file_extension": ".py", 319 | "mimetype": "text/x-python", 320 | "name": "python", 321 | "nbconvert_exporter": "python", 322 | "pygments_lexer": "ipython3", 323 | "version": "3.7.6" 324 | }, 325 | "title": "Foundations of Computational Economics #11" 326 | }, 327 | "nbformat": 4, 328 | "nbformat_minor": 4 329 | } 330 | -------------------------------------------------------------------------------- /16_vizualization.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "slideshow": { 7 | "slide_type": "slide" 8 | } 9 | }, 10 | "source": [ 11 | "# Foundations of Computational Economics #16\n", 12 | "\n", 13 | "by Fedor Iskhakov, ANU\n", 14 | "\n", 15 | "" 16 | ] 17 | }, 18 | { 19 | "cell_type": "markdown", 20 | "metadata": { 21 | "slideshow": { 22 | "slide_type": "fragment" 23 | } 24 | }, 25 | "source": [ 26 | "## Visualization of data and solutions\n", 27 | "\n", 28 | "" 29 | ] 30 | }, 31 | { 32 | "cell_type": "markdown", 33 | "metadata": { 34 | "slideshow": { 35 | "slide_type": "subslide" 36 | } 37 | }, 38 | "source": [ 39 | "\n", 40 | "\n", 41 | "[https://youtu.be/dJdWVkSNNpc](https://youtu.be/dJdWVkSNNpc)\n", 42 | "\n", 43 | "Description: Principles and functions of graphics. Examples of visualization of economic models." 44 | ] 45 | }, 46 | { 47 | "cell_type": "markdown", 48 | "metadata": { 49 | "slideshow": { 50 | "slide_type": "slide" 51 | } 52 | }, 53 | "source": [ 54 | "### Why visualize?\n", 55 | "\n", 56 | "1. **Convey ideas to others**\n", 57 | " Ability to efficiently explain your idea/work to other busy people is crucial element of success in many fields \n", 58 | "1. **Check your own work**\n", 59 | " Creating of new knowledge using computational tools requires absolute certainty in the code \n", 60 | "1. **Aggregate large amounts of information**\n", 61 | " Makes it possible to get the big picture and the message behind it " 62 | ] 63 | }, 64 | { 65 | "cell_type": "markdown", 66 | "metadata": { 67 | "slideshow": { 68 | "slide_type": "slide" 69 | } 70 | }, 71 | "source": [ 72 | "\n", 73 | "\n", 74 | "[https://www.strava.com/heatmap#5.13/120.47297/37.61174/hot/all](https://www.strava.com/heatmap#5.13/120.47297/37.61174/hot/all)" 75 | ] 76 | }, 77 | { 78 | "cell_type": "markdown", 79 | "metadata": { 80 | "slideshow": { 81 | "slide_type": "slide" 82 | } 83 | }, 84 | "source": [ 85 | "### Matplotlib and other libraries\n", 86 | "\n", 87 | "- `matplotlib` - Python library that abstracts from the graphical backbone\n", 88 | " of each system and ensures *code mobility* \n", 89 | "\n", 90 | "\n", 91 | "**Matplotlib thumbnail gallery** [https://matplotlib.org/gallery.html](https://matplotlib.org/gallery.html)\n", 92 | "\n", 93 | "- `seaborn` - pretty plots geared towards statistical applications\n", 94 | " [https://seaborn.pydata.org/examples/index.html](https://seaborn.pydata.org/examples/index.html) \n", 95 | "- `bokeh` is a library for creating interactive plots\n", 96 | " [http://bokeh.pydata.org/en/latest/docs/gallery.html](http://bokeh.pydata.org/en/latest/docs/gallery.html) " 97 | ] 98 | }, 99 | { 100 | "cell_type": "markdown", 101 | "metadata": { 102 | "slideshow": { 103 | "slide_type": "slide" 104 | } 105 | }, 106 | "source": [ 107 | "#### Plan\n", 108 | "\n", 109 | "1. Visualization examples from my own research projects \n", 110 | "1. Links to compulsory online learning resources " 111 | ] 112 | }, 113 | { 114 | "cell_type": "markdown", 115 | "metadata": { 116 | "slideshow": { 117 | "slide_type": "slide" 118 | } 119 | }, 120 | "source": [ 121 | "#### Graphical objects\n", 122 | "\n", 123 | "Extensive collection of objects to modify all aspects of the graphics\n", 124 | "\n", 125 | "- figure - axes - subplots \n", 126 | "- lines - polygons (patches) \n", 127 | "- fill color and edge color \n", 128 | "- annotations and other text " 129 | ] 130 | }, 131 | { 132 | "cell_type": "markdown", 133 | "metadata": { 134 | "slideshow": { 135 | "slide_type": "slide" 136 | } 137 | }, 138 | "source": [ 139 | "#### Types of plots\n", 140 | "\n", 141 | "- **bar** - categorical data, histograms \n", 142 | "- **scatter** - individual data points \n", 143 | "- **line** - continuous measure \n", 144 | "- **area** - dynamics of composition \n", 145 | "- **pie** - static composition \n", 146 | "- **Sankey** - flow diagram " 147 | ] 148 | }, 149 | { 150 | "cell_type": "markdown", 151 | "metadata": { 152 | "slideshow": { 153 | "slide_type": "slide" 154 | } 155 | }, 156 | "source": [ 157 | "#### How to choose the plot type\n", 158 | "\n", 159 | "1. Number of variables to be represented \n", 160 | "1. Type of variables \n", 161 | " - continuous \n", 162 | " - categorical \n", 163 | " - ordered \n", 164 | "1. What is the message of the graphics? " 165 | ] 166 | }, 167 | { 168 | "cell_type": "markdown", 169 | "metadata": { 170 | "slideshow": { 171 | "slide_type": "slide" 172 | } 173 | }, 174 | "source": [ 175 | "### General tips\n", 176 | "\n", 177 | "1. **Less visual clutter!** \n", 178 | " Every dot, line, shape and label has to convey useful information \n", 179 | "1. **Read the the manual and change the options** \n", 180 | " Defaults are good for quick and dirty preliminary runs only \n", 181 | "1. **Careful with 3D** \n", 182 | " Much harder to make clear \n", 183 | "1. **“Animations”** \n", 184 | " May be useful in cases when there are one too many dimensions in the data to visualize " 185 | ] 186 | }, 187 | { 188 | "cell_type": "markdown", 189 | "metadata": { 190 | "slideshow": { 191 | "slide_type": "slide" 192 | } 193 | }, 194 | "source": [ 195 | "#### Less visual clutter\n", 196 | "\n", 197 | "" 198 | ] 199 | }, 200 | { 201 | "cell_type": "markdown", 202 | "metadata": { 203 | "slideshow": { 204 | "slide_type": "slide" 205 | } 206 | }, 207 | "source": [ 208 | "#### Choice of appropriate plot type" 209 | ] 210 | }, 211 | { 212 | "cell_type": "markdown", 213 | "metadata": { 214 | "slideshow": { 215 | "slide_type": "slide" 216 | } 217 | }, 218 | "source": [ 219 | "" 220 | ] 221 | }, 222 | { 223 | "cell_type": "markdown", 224 | "metadata": { 225 | "slideshow": { 226 | "slide_type": "slide" 227 | } 228 | }, 229 | "source": [ 230 | "" 231 | ] 232 | }, 233 | { 234 | "cell_type": "markdown", 235 | "metadata": { 236 | "slideshow": { 237 | "slide_type": "slide" 238 | } 239 | }, 240 | "source": [ 241 | "" 242 | ] 243 | }, 244 | { 245 | "cell_type": "markdown", 246 | "metadata": { 247 | "slideshow": { 248 | "slide_type": "slide" 249 | } 250 | }, 251 | "source": [ 252 | "" 253 | ] 254 | }, 255 | { 256 | "cell_type": "markdown", 257 | "metadata": { 258 | "slideshow": { 259 | "slide_type": "slide" 260 | } 261 | }, 262 | "source": [ 263 | "" 264 | ] 265 | }, 266 | { 267 | "cell_type": "markdown", 268 | "metadata": { 269 | "slideshow": { 270 | "slide_type": "slide" 271 | } 272 | }, 273 | "source": [ 274 | "" 275 | ] 276 | }, 277 | { 278 | "cell_type": "markdown", 279 | "metadata": { 280 | "slideshow": { 281 | "slide_type": "slide" 282 | } 283 | }, 284 | "source": [ 285 | "" 286 | ] 287 | }, 288 | { 289 | "cell_type": "markdown", 290 | "metadata": { 291 | "slideshow": { 292 | "slide_type": "slide" 293 | } 294 | }, 295 | "source": [ 296 | "" 297 | ] 298 | }, 299 | { 300 | "cell_type": "markdown", 301 | "metadata": { 302 | "slideshow": { 303 | "slide_type": "slide" 304 | } 305 | }, 306 | "source": [ 307 | "#### Using many dimensions in one plot\n", 308 | "\n", 309 | "- location (x,y,z) \n", 310 | "- color \n", 311 | "- line or marker style \n", 312 | "- size \n", 313 | "- animation \n", 314 | "- multiple plots in a figure " 315 | ] 316 | }, 317 | { 318 | "cell_type": "markdown", 319 | "metadata": { 320 | "slideshow": { 321 | "slide_type": "slide" 322 | } 323 | }, 324 | "source": [ 325 | "" 326 | ] 327 | }, 328 | { 329 | "cell_type": "markdown", 330 | "metadata": { 331 | "slideshow": { 332 | "slide_type": "slide" 333 | } 334 | }, 335 | "source": [ 336 | "#### Visual debugging and dashboards\n", 337 | "\n", 338 | "Using visual representation to verify the code\n", 339 | "- *Seeing* a bug in a plot is easier than in the code!\n", 340 | "\n", 341 | "Dashboards are ideal for aggregation of large amounts of information\n", 342 | "\n", 343 | "1. Calibration/estimation an moment matching \n", 344 | "1. Monitoring computing resources " 345 | ] 346 | }, 347 | { 348 | "cell_type": "markdown", 349 | "metadata": { 350 | "slideshow": { 351 | "slide_type": "slide" 352 | } 353 | }, 354 | "source": [ 355 | "" 356 | ] 357 | }, 358 | { 359 | "cell_type": "markdown", 360 | "metadata": { 361 | "slideshow": { 362 | "slide_type": "slide" 363 | } 364 | }, 365 | "source": [ 366 | "" 367 | ] 368 | }, 369 | { 370 | "cell_type": "markdown", 371 | "metadata": { 372 | "slideshow": { 373 | "slide_type": "slide" 374 | } 375 | }, 376 | "source": [ 377 | "" 378 | ] 379 | }, 380 | { 381 | "cell_type": "markdown", 382 | "metadata": { 383 | "slideshow": { 384 | "slide_type": "slide" 385 | } 386 | }, 387 | "source": [ 388 | "" 389 | ] 390 | }, 391 | { 392 | "cell_type": "markdown", 393 | "metadata": { 394 | "slideshow": { 395 | "slide_type": "slide" 396 | } 397 | }, 398 | "source": [ 399 | "#### Visualizing economic model for new insights" 400 | ] 401 | }, 402 | { 403 | "cell_type": "markdown", 404 | "metadata": { 405 | "slideshow": { 406 | "slide_type": "slide" 407 | } 408 | }, 409 | "source": [ 410 | "" 411 | ] 412 | }, 413 | { 414 | "cell_type": "markdown", 415 | "metadata": { 416 | "slideshow": { 417 | "slide_type": "slide" 418 | } 419 | }, 420 | "source": [ 421 | "" 422 | ] 423 | }, 424 | { 425 | "cell_type": "markdown", 426 | "metadata": { 427 | "slideshow": { 428 | "slide_type": "slide" 429 | } 430 | }, 431 | "source": [ 432 | "" 433 | ] 434 | }, 435 | { 436 | "cell_type": "markdown", 437 | "metadata": { 438 | "slideshow": { 439 | "slide_type": "slide" 440 | } 441 | }, 442 | "source": [ 443 | "" 444 | ] 445 | }, 446 | { 447 | "cell_type": "markdown", 448 | "metadata": { 449 | "slideshow": { 450 | "slide_type": "slide" 451 | } 452 | }, 453 | "source": [ 454 | "### Tutorials for compulsory self-study\n", 455 | "\n", 456 | "- Excellent tutorial on Matplotlib on QuantEcon DataScience\n", 457 | " [https://datascience.quantecon.org/applications/visualization_rules.html](https://datascience.quantecon.org/applications/visualization_rules.html) \n", 458 | "- Presentation by Hans Rosling (1948-2017, Swedish physician, academic, statistician, and public speaker)\n", 459 | " [https://youtu.be/hVimVzgtD6w?t=159](https://youtu.be/hVimVzgtD6w?t=159) " 460 | ] 461 | }, 462 | { 463 | "cell_type": "markdown", 464 | "metadata": { 465 | "slideshow": { 466 | "slide_type": "slide" 467 | } 468 | }, 469 | "source": [ 470 | "### Further learning resources\n", 471 | "\n", 472 | "- Excellent beginner tutorial for Matplotlib by the authors (3h)\n", 473 | " [https://www.youtube.com/watch?v=6gdNUDs6QPc&t=2843s](https://www.youtube.com/watch?v=6gdNUDs6QPc&t=2843s) \n", 474 | "- Playlist of lectures and tutorials\n", 475 | " [https://www.youtube.com/user/EnthoughtMedia/search?query=matplotlib](https://www.youtube.com/user/EnthoughtMedia/search?query=matplotlib) \n", 476 | "- Visualization of sorting algorithms\n", 477 | " [https://www.youtube.com/watch?v=kPRA0W1kECg](https://www.youtube.com/watch?v=kPRA0W1kECg) " 478 | ] 479 | } 480 | ], 481 | "metadata": { 482 | "celltoolbar": "Slideshow", 483 | "date": 1612589584.968545, 484 | "download_nb": false, 485 | "filename": "16_vizualization.rst", 486 | "filename_with_path": "16_vizualization", 487 | "kernelspec": { 488 | "display_name": "Python", 489 | "language": "python3", 490 | "name": "python3" 491 | }, 492 | "language_info": { 493 | "codemirror_mode": { 494 | "name": "ipython", 495 | "version": 3 496 | }, 497 | "file_extension": ".py", 498 | "mimetype": "text/x-python", 499 | "name": "python", 500 | "nbconvert_exporter": "python", 501 | "pygments_lexer": "ipython3", 502 | "version": "3.7.6" 503 | }, 504 | "title": "Foundations of Computational Economics #16" 505 | }, 506 | "nbformat": 4, 507 | "nbformat_minor": 4 508 | } 509 | -------------------------------------------------------------------------------- /18_linear_prog.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "slideshow": { 7 | "slide_type": "slide" 8 | } 9 | }, 10 | "source": [ 11 | "# Foundations of Computational Economics #18\n", 12 | "\n", 13 | "by Fedor Iskhakov, ANU\n", 14 | "\n", 15 | "" 16 | ] 17 | }, 18 | { 19 | "cell_type": "markdown", 20 | "metadata": { 21 | "slideshow": { 22 | "slide_type": "fragment" 23 | } 24 | }, 25 | "source": [ 26 | "## Linear programming and optimal transport models\n", 27 | "\n", 28 | "" 29 | ] 30 | }, 31 | { 32 | "cell_type": "markdown", 33 | "metadata": { 34 | "slideshow": { 35 | "slide_type": "subslide" 36 | } 37 | }, 38 | "source": [ 39 | "\n", 40 | "\n", 41 | "[https://youtu.be/E1T1AWcMDqE](https://youtu.be/E1T1AWcMDqE)\n", 42 | "\n", 43 | "Description: Linear programming and optimal transport problems." 44 | ] 45 | }, 46 | { 47 | "cell_type": "markdown", 48 | "metadata": { 49 | "slideshow": { 50 | "slide_type": "slide" 51 | } 52 | }, 53 | "source": [ 54 | "### Linear programming\n", 55 | "\n", 56 | "- Finding maximum/minimum of linear function subject to a set of linear inequality constraints \n", 57 | "- Classical problem in operations research and economics \n", 58 | "\n", 59 | "\n", 60 | "**Optimal transport problem**\n", 61 | "\n", 62 | "Minimum cost of transporting a set of goods from $ m $ origins to $ n $ destinations,\n", 63 | "where cost of transporting from origin $ i $ to destination $ j $ is given by $ c_{ij} $" 64 | ] 65 | }, 66 | { 67 | "cell_type": "markdown", 68 | "metadata": { 69 | "slideshow": { 70 | "slide_type": "slide" 71 | } 72 | }, 73 | "source": [ 74 | "### Optimal transport in economics\n", 75 | "\n", 76 | "- Matching and trade\n", 77 | " - matching distribution of workers to distribution of firms\n", 78 | " - relation to gravity equation in trade \n", 79 | "- Demand estimation and pricing\n", 80 | " - relation to discrete choice and nested discrete choice\n", 81 | " - quasi-linear hedonic models \n", 82 | "- Quantile methods in econometrics " 83 | ] 84 | }, 85 | { 86 | "cell_type": "markdown", 87 | "metadata": { 88 | "slideshow": { 89 | "slide_type": "slide" 90 | } 91 | }, 92 | "source": [ 93 | "#### Graphic representation\n", 94 | "\n", 95 | "" 96 | ] 97 | }, 98 | { 99 | "cell_type": "markdown", 100 | "metadata": { 101 | "slideshow": { 102 | "slide_type": "slide" 103 | } 104 | }, 105 | "source": [ 106 | "#### Formal problem statement\n", 107 | "\n", 108 | "$$\n", 109 | "\\min \\sum_{i=1}^{m}\\sum_{j=1}^{n} c_{ij} x_{ij}, \\text{ subject to}\n", 110 | "$$\n", 111 | "\n", 112 | "$$\n", 113 | "\\sum_{i=1}^{m} x_{ij} = b_j, j \\in \\{1,\\dots,n\\},\n", 114 | "$$\n", 115 | "\n", 116 | "$$\n", 117 | "\\sum_{j=1}^{n} x_{ij} = a_i, i \\in \\{1,\\dots,m\\},\n", 118 | "$$\n", 119 | "\n", 120 | "$$\n", 121 | "x_{ij} \\ge 0 \\text{ for all } i,j\n", 122 | "$$" 123 | ] 124 | }, 125 | { 126 | "cell_type": "markdown", 127 | "metadata": { 128 | "slideshow": { 129 | "slide_type": "slide" 130 | } 131 | }, 132 | "source": [ 133 | "#### General linear programming problem\n", 134 | "\n", 135 | "Linear programming = optimizing linear function on convex polyhedron\n", 136 | "\n", 137 | "$$\n", 138 | "\\max(c \\cdot x) \\text{ subject to } Ax \\le b\n", 139 | "$$\n", 140 | "\n", 141 | "Note that $ Ax \\le b $ includes as special cases\n", 142 | "\n", 143 | "- $ x_j\\ge 0 $ for some $ j \\in J $, trivially \n", 144 | "- $ x_j = D_j $ for some $ j \\in J $ using two inequalities " 145 | ] 146 | }, 147 | { 148 | "cell_type": "markdown", 149 | "metadata": { 150 | "slideshow": { 151 | "slide_type": "slide" 152 | } 153 | }, 154 | "source": [ 155 | "#### Convex polyhedron in 2d (convex polygon)\n", 156 | "\n", 157 | "" 158 | ] 159 | }, 160 | { 161 | "cell_type": "markdown", 162 | "metadata": { 163 | "slideshow": { 164 | "slide_type": "slide" 165 | } 166 | }, 167 | "source": [ 168 | "#### Convex polyhedron and objective function\n", 169 | "\n", 170 | "" 171 | ] 172 | }, 173 | { 174 | "cell_type": "markdown", 175 | "metadata": { 176 | "slideshow": { 177 | "slide_type": "slide" 178 | } 179 | }, 180 | "source": [ 181 | "#### Convex polyhedron in 3d\n", 182 | "\n", 183 | "" 184 | ] 185 | }, 186 | { 187 | "cell_type": "markdown", 188 | "metadata": { 189 | "slideshow": { 190 | "slide_type": "slide" 191 | } 192 | }, 193 | "source": [ 194 | "#### Example: Optimal production portfolio\n", 195 | "\n", 196 | "Let $ x $ and $ y $ denote production of goods A and B by some firm. The production technology is restricted to have\n", 197 | "\n", 198 | "$$\n", 199 | "\\begin{cases}\n", 200 | "y - x &\\le& 4, \\\\\n", 201 | "2x - y &\\le&8,\n", 202 | "\\end{cases}\n", 203 | "$$\n", 204 | "\n", 205 | "And the resource constraint is given by $ x + 2y \\le 14 $\n", 206 | "\n", 207 | "Let profits be given by $ \\pi(x,y) = y + 2x $" 208 | ] 209 | }, 210 | { 211 | "cell_type": "markdown", 212 | "metadata": { 213 | "slideshow": { 214 | "slide_type": "slide" 215 | } 216 | }, 217 | "source": [ 218 | "Adding the natural non-negativity constraints, in matrix notation we have\n", 219 | "\n", 220 | "$$\n", 221 | "\\max(c^{T}x) \\text{ subject to } Ax \\le b\n", 222 | "$$\n", 223 | "\n", 224 | "$$\n", 225 | "c=\n", 226 | "\\begin{pmatrix}\n", 227 | "2 & 1\n", 228 | "\\end{pmatrix},\\;\\;\n", 229 | "A=\n", 230 | "\\begin{pmatrix}\n", 231 | "-1 & 1 \\\\\n", 232 | "2 & -1 \\\\\n", 233 | "1 & 2 \\\\\n", 234 | "-1 & 0 \\\\\n", 235 | "0 & -1 \\\\\n", 236 | "\\end{pmatrix},\\;\\;\n", 237 | "b=\n", 238 | "\\begin{pmatrix}\n", 239 | "4\\\\\n", 240 | "8\\\\\n", 241 | "14\\\\\n", 242 | "0\\\\\n", 243 | "0\n", 244 | "\\end{pmatrix}\n", 245 | "$$" 246 | ] 247 | }, 248 | { 249 | "cell_type": "markdown", 250 | "metadata": { 251 | "slideshow": { 252 | "slide_type": "slide" 253 | } 254 | }, 255 | "source": [ 256 | "#### Convex polyhedron and objective function\n", 257 | "\n", 258 | "" 259 | ] 260 | }, 261 | { 262 | "cell_type": "code", 263 | "execution_count": 1, 264 | "metadata": { 265 | "hide-output": false, 266 | "slideshow": { 267 | "slide_type": "slide" 268 | } 269 | }, 270 | "outputs": [ 271 | { 272 | "name": "stdout", 273 | "output_type": "stream", 274 | "text": [ 275 | "iteration 0, current solution [0. 0.]\n", 276 | "iteration 1, current solution [4. 0.]\n", 277 | "iteration 2, current solution [6. 4.]\n", 278 | "iteration 3, current solution [6. 4.]\n", 279 | "iteration 3, current solution [6. 4.]\n" 280 | ] 281 | }, 282 | { 283 | "data": { 284 | "text/plain": [ 285 | " con: array([], dtype=float64)\n", 286 | " fun: -16.0\n", 287 | " message: 'Optimization terminated successfully.'\n", 288 | " nit: 3\n", 289 | " slack: array([6., 0., 0., 6., 4.])\n", 290 | " status: 0\n", 291 | " success: True\n", 292 | " x: array([6., 4.])" 293 | ] 294 | }, 295 | "execution_count": 1, 296 | "metadata": {}, 297 | "output_type": "execute_result" 298 | } 299 | ], 300 | "source": [ 301 | "import numpy as np\n", 302 | "from scipy.optimize import linprog\n", 303 | "\n", 304 | "c = np.array([-2,-1])\n", 305 | "A = np.array([[-1,1],[2,-1],[1,2],[-1,0],[0,-1]])\n", 306 | "b = np.array([4,8,14,0,0])\n", 307 | "\n", 308 | "def outf(arg):\n", 309 | " print('iteration %d, current solution %s'%(arg.nit,arg.x))\n", 310 | "\n", 311 | "linprog(c=c,A_ub=A,b_ub=b,method='simplex',callback=outf)" 312 | ] 313 | }, 314 | { 315 | "cell_type": "markdown", 316 | "metadata": { 317 | "slideshow": { 318 | "slide_type": "slide" 319 | } 320 | }, 321 | "source": [ 322 | "### Further learning resources\n", 323 | "\n", 324 | "- “Optimal Transport Methods in Economics” by Alfred Galichon, 2016\n", 325 | " [https://www.jstor.org/stable/j.ctt1q1xs9h](https://www.jstor.org/stable/j.ctt1q1xs9h) \n", 326 | "- Alfred Galichon’s plenary talk at the 2020 Econometric Society World Congress\n", 327 | " [https://youtu.be/XYIRkSIExik?t=2256](https://youtu.be/XYIRkSIExik?t=2256) " 328 | ] 329 | } 330 | ], 331 | "metadata": { 332 | "celltoolbar": "Slideshow", 333 | "date": 1612589585.0195599, 334 | "download_nb": false, 335 | "filename": "18_linear_prog.rst", 336 | "filename_with_path": "18_linear_prog", 337 | "kernelspec": { 338 | "display_name": "Python", 339 | "language": "python3", 340 | "name": "python3" 341 | }, 342 | "language_info": { 343 | "codemirror_mode": { 344 | "name": "ipython", 345 | "version": 3 346 | }, 347 | "file_extension": ".py", 348 | "mimetype": "text/x-python", 349 | "name": "python", 350 | "nbconvert_exporter": "python", 351 | "pygments_lexer": "ipython3", 352 | "version": "3.7.6" 353 | }, 354 | "title": "Foundations of Computational Economics #18" 355 | }, 356 | "nbformat": 4, 357 | "nbformat_minor": 4 358 | } 359 | -------------------------------------------------------------------------------- /21_stationary.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "slideshow": { 7 | "slide_type": "slide" 8 | } 9 | }, 10 | "source": [ 11 | "# Foundations of Computational Economics #21\n", 12 | "\n", 13 | "by Fedor Iskhakov, ANU\n", 14 | "\n", 15 | "" 16 | ] 17 | }, 18 | { 19 | "cell_type": "markdown", 20 | "metadata": { 21 | "slideshow": { 22 | "slide_type": "fragment" 23 | } 24 | }, 25 | "source": [ 26 | "## Computing a stationary distribution of a Markov chain\n", 27 | "\n", 28 | "" 29 | ] 30 | }, 31 | { 32 | "cell_type": "markdown", 33 | "metadata": { 34 | "slideshow": { 35 | "slide_type": "subslide" 36 | } 37 | }, 38 | "source": [ 39 | "\n", 40 | "\n", 41 | "[https://youtu.be/eEbDbM17soU](https://youtu.be/eEbDbM17soU)\n", 42 | "\n", 43 | "Description: Successive approximations and direct linear solver." 44 | ] 45 | }, 46 | { 47 | "cell_type": "markdown", 48 | "metadata": { 49 | "slideshow": { 50 | "slide_type": "slide" 51 | } 52 | }, 53 | "source": [ 54 | "Let stochastic matrix $ P $ denote the transition probability matrix of a Markov chain which takes values from $ S=\\{0,\\dots,n-1\\} $\n", 55 | "\n", 56 | "Assume that $ P $ is aperiodic and irreducible, so there exists a unique stationary distribution $ \\psi^\\star $ such that\n", 57 | "\n", 58 | "$$\n", 59 | "\\psi^\\star = \\psi^\\star \\cdot P\n", 60 | "$$\n", 61 | "\n", 62 | "Our task is to compute $ \\psi^\\star $" 63 | ] 64 | }, 65 | { 66 | "cell_type": "markdown", 67 | "metadata": { 68 | "slideshow": { 69 | "slide_type": "slide" 70 | } 71 | }, 72 | "source": [ 73 | "### Method 1: successive approximations\n", 74 | "\n", 75 | "Due to convergence results, we can use the following algorithm (see previous video on Markov chains)\n", 76 | "\n", 77 | "1. Start from arbitrary distribution $ \\psi_0 $ \n", 78 | "1. Compute the updated distribution $ \\psi_t = \\psi_{t-1} P $ until $ \\psi_t $ and $ \\psi_{t-1} $ are indistinguishable " 79 | ] 80 | }, 81 | { 82 | "cell_type": "code", 83 | "execution_count": 1, 84 | "metadata": { 85 | "hide-output": false, 86 | "slideshow": { 87 | "slide_type": "slide" 88 | } 89 | }, 90 | "outputs": [], 91 | "source": [ 92 | "import numpy as np\n", 93 | "P = np.array([[.5,.3,.2],[.5,.4,.1],[.1,.1,.8]])\n", 94 | "ψ = np.array([1,0,0])" 95 | ] 96 | }, 97 | { 98 | "cell_type": "code", 99 | "execution_count": 2, 100 | "metadata": { 101 | "hide-output": false, 102 | "slideshow": { 103 | "slide_type": "slide" 104 | } 105 | }, 106 | "outputs": [], 107 | "source": [ 108 | "def stationary_sa(P,psi0,tol=1e-6,maxiter=100,callback=None):\n", 109 | " '''Computes stationary distribution for the Markov chain given by transition probability\n", 110 | " matrix P, with given maximum number of iterations, and convergence tolerance.\n", 111 | " callback function is called at each iteration if given.\n", 112 | " Method: successive approximations\n", 113 | " '''\n", 114 | " pass\n", 115 | "\n", 116 | "stationary_sa(P,ψ)" 117 | ] 118 | }, 119 | { 120 | "cell_type": "code", 121 | "execution_count": 3, 122 | "metadata": { 123 | "hide-output": false, 124 | "slideshow": { 125 | "slide_type": "slide" 126 | } 127 | }, 128 | "outputs": [ 129 | { 130 | "name": "stdout", 131 | "output_type": "stream", 132 | "text": [ 133 | "iter 0, psi = array([0.5, 0.3, 0.2])\n", 134 | "iter 1, psi = array([0.42, 0.29, 0.29])\n", 135 | "iter 2, psi = array([0.384, 0.271, 0.345])\n", 136 | "iter 3, psi = array([0.362 , 0.2581, 0.3799])\n", 137 | "iter 4, psi = array([0.34804, 0.24983, 0.40213])\n", 138 | "iter 5, psi = array([0.339148, 0.244557, 0.416295])\n", 139 | "iter 6, psi = array([0.333482 , 0.2411967, 0.4253213])\n", 140 | "iter 7, psi = array([0.32987148, 0.23905541, 0.43107311])\n", 141 | "iter 8, psi = array([0.32757076, 0.23769092, 0.43473833])\n", 142 | "iter 9, psi = array([0.32610467, 0.23682143, 0.4370739 ])\n", 143 | "iter 10, psi = array([0.32517044, 0.23626736, 0.4385622 ])\n", 144 | "iter 11, psi = array([0.32457512, 0.2359143 , 0.43951058])\n", 145 | "iter 12, psi = array([0.32419577, 0.23568931, 0.44011492])\n", 146 | "iter 13, psi = array([0.32395403, 0.23554595, 0.44050002])\n", 147 | "iter 14, psi = array([0.32379999, 0.23545459, 0.44074542])\n", 148 | "iter 15, psi = array([0.32370183, 0.23539638, 0.44090179])\n", 149 | "iter 16, psi = array([0.32363928, 0.23535928, 0.44100144])\n", 150 | "iter 17, psi = array([0.32359943, 0.23533564, 0.44106493])\n", 151 | "iter 18, psi = array([0.32357403, 0.23532058, 0.4411054 ])\n", 152 | "iter 19, psi = array([0.32355784, 0.23531098, 0.44113118])\n", 153 | "iter 20, psi = array([0.32354753, 0.23530486, 0.44114761])\n", 154 | "iter 21, psi = array([0.32354096, 0.23530096, 0.44115808])\n", 155 | "iter 22, psi = array([0.32353677, 0.23529848, 0.44116475])\n", 156 | "iter 23, psi = array([0.3235341, 0.2352969, 0.441169 ])\n", 157 | "iter 24, psi = array([0.3235324 , 0.23529589, 0.44117171])\n", 158 | "iter 25, psi = array([0.32353132, 0.23529525, 0.44117344])\n", 159 | "iter 26, psi = array([0.32353062, 0.23529484, 0.44117454])\n", 160 | "iter 27, psi = array([0.32353018, 0.23529458, 0.44117524])\n" 161 | ] 162 | }, 163 | { 164 | "data": { 165 | "text/plain": [ 166 | "array([0.32353018, 0.23529458, 0.44117524])" 167 | ] 168 | }, 169 | "execution_count": 3, 170 | "metadata": {}, 171 | "output_type": "execute_result" 172 | } 173 | ], 174 | "source": [ 175 | "def stationary_sa(P,psi0=[None,],tol=1e-6,maxiter=100,callback=None):\n", 176 | " '''Computes stationary distribution for the Markov chain given by transition probability\n", 177 | " matrix P, with given maximum number of iterations, and convergence tolerance.\n", 178 | " callback function is called at each iteration if given.\n", 179 | " Method: successive approximations\n", 180 | " '''\n", 181 | " if psi0[0]==None:\n", 182 | " # degenrate initial distribution\n", 183 | " psi0 = [0,]*P.shape[0]\n", 184 | " psi0[0]=1.0\n", 185 | " P,psi0 = np.asarray(P),np.asarray(psi0) # convert to np arrays (in case lists were passed)\n", 186 | " assert np.all(np.abs(P.sum(axis=1)-1)<1e-10), 'Passed P is not stochastic matrix'\n", 187 | " assert np.abs(psi0.sum()-1)<1e-10, 'Passed probabilities do not sum up to one'\n", 188 | " for i in range(maxiter): # main loop\n", 189 | " psi1 = psi0 @ P # update approximation of psi^star\n", 190 | " err = np.amax(abs(psi0-psi1)) # error is the max absolute deviation element-wise\n", 191 | " if callback != None: callback(err=err,iter=i,psi=psi1)\n", 192 | " if err" 16 | ] 17 | }, 18 | { 19 | "cell_type": "markdown", 20 | "metadata": { 21 | "slideshow": { 22 | "slide_type": "fragment" 23 | } 24 | }, 25 | "source": [ 26 | "## Euler equation and time iterations\n", 27 | "\n", 28 | "" 29 | ] 30 | }, 31 | { 32 | "cell_type": "markdown", 33 | "metadata": { 34 | "slideshow": { 35 | "slide_type": "subslide" 36 | } 37 | }, 38 | "source": [ 39 | "\n", 40 | "\n", 41 | "[https://youtu.be/AAv3aO8UJg4](https://youtu.be/AAv3aO8UJg4)\n", 42 | "\n", 43 | "Description: First order conditions and Euler equation. Time iterations solution method. Euler residuals for measuring the accuracy of solution for consumption-savings model." 44 | ] 45 | }, 46 | { 47 | "cell_type": "markdown", 48 | "metadata": { 49 | "slideshow": { 50 | "slide_type": "slide" 51 | } 52 | }, 53 | "source": [ 54 | "### First order conditions in dynamic models with continuous choice\n", 55 | "\n", 56 | "We can write FOCs for the maximization problem in Bellman equation! Is there any use?\n", 57 | "\n", 58 | "- must be satisfied with optimal policy $ \\Rightarrow $ solution method ideas\n", 59 | " - backwards induction with equation solving instead of optimization\n", 60 | " - time iterations in the infinite horizon problems \n", 61 | "- must be satisfied even when the problem is solved by some other method $ \\Rightarrow $ ideas of checking accuracy of numerical solutions\n", 62 | " - Euler residuals accuracy check\n", 63 | " - flat consumption path must be simulated with certain restrictions on parameters (Keane test)\n", 64 | " - other known theoretical property of the solution must hold " 65 | ] 66 | }, 67 | { 68 | "cell_type": "markdown", 69 | "metadata": { 70 | "slideshow": { 71 | "slide_type": "slide" 72 | } 73 | }, 74 | "source": [ 75 | "#### FOCs in the consumption-savings problem (Deaton model)\n", 76 | "\n", 77 | "$$\n", 78 | "V(M)=\\max_{0 \\le c \\le M}\\big\\{u(c)+\\beta \\mathbb{E}_{y} V\\big(\\underset{=M'}{\\underbrace{R(M-c)+\\tilde{y}}}\\big)\\big\\}\n", 79 | "$$\n", 80 | "\n", 81 | "- discrete time, infinite horizon \n", 82 | "- one continuous choice of consumption $ 0 \\le c \\le M $ \n", 83 | "- state space: consumable resources in the beginning of the period $ M $, discretized \n", 84 | "- income $ \\tilde{y} $, follows log-normal distribution with $ \\mu = 0 $ and $ \\sigma $ " 85 | ] 86 | }, 87 | { 88 | "cell_type": "markdown", 89 | "metadata": { 90 | "slideshow": { 91 | "slide_type": "slide" 92 | } 93 | }, 94 | "source": [ 95 | "#### First order conditions for Deaton model\n", 96 | "\n", 97 | "$$\n", 98 | "V(M)=\\max_{0 \\le c \\le M}\\big\\{u(c)+\\beta \\mathbb{E}_{y} V\\big(\\underset{=M'}{\\underbrace{R(M-c)+\\tilde{y}}}\\big)\\big\\}\n", 99 | "$$\n", 100 | "\n", 101 | "FOC:\n", 102 | "\n", 103 | "$$\n", 104 | "u'(c^\\star) - \\beta R \\mathbb{E}_{y} V'\\big(R(M-c^\\star)+\\tilde{y}\\big) = 0\n", 105 | "$$\n", 106 | "\n", 107 | "- define implicit function $ c^\\star(M) $ — *policy function* \n", 108 | "- but $ V'(\\cdot) $ requires special provisions in the numerical implementation.. " 109 | ] 110 | }, 111 | { 112 | "cell_type": "markdown", 113 | "metadata": { 114 | "slideshow": { 115 | "slide_type": "slide" 116 | } 117 | }, 118 | "source": [ 119 | "#### Envelope theorem\n", 120 | "\n", 121 | "$$\n", 122 | "\\text{Let } G(M,c)=u(c)+\\beta \\mathbb{E}_{y} V\\big(\\underset{=M'}{\\underbrace{R(M-c)+\\tilde{y}}}\\big)\n", 123 | "$$\n", 124 | "\n", 125 | "so that the policy function $ c^\\star(M) $ satisfies $ V(M)=G(M,c^\\star(M)) $. Then\n", 126 | "\n", 127 | "$$\n", 128 | "V'(M) = \\tfrac{\\partial G(M,c^\\star)}{\\partial M} + \\underset{=0\\text{ by FOC}}{\\underbrace{\\tfrac{\\partial G(M,c^\\star)}{\\partial c^\\star}}} \\tfrac{\\partial c^\\star(M)}{\\partial M}\n", 129 | "= \\tfrac{\\partial G(M,c^\\star)}{\\partial M} = \\beta R \\mathbb{E}_{y} V'\\big(R(M-c^\\star)+\\tilde{y}\\big)\n", 130 | "$$" 131 | ] 132 | }, 133 | { 134 | "cell_type": "markdown", 135 | "metadata": { 136 | "slideshow": { 137 | "slide_type": "slide" 138 | } 139 | }, 140 | "source": [ 141 | "#### Euler equation for Deaton model\n", 142 | "\n", 143 | "$$\n", 144 | "\\text{(FOC) } u'(c^\\star) = \\beta R \\mathbb{E}_{y} V'\\big(R(M-c^\\star)+\\tilde{y}\\big)\n", 145 | "$$\n", 146 | "\n", 147 | "$$\n", 148 | "\\text{(envelope theorem) } V'(M) = \\beta R \\mathbb{E}_{y} V'\\big(R(M-c^\\star)+\\tilde{y}\\big)\n", 149 | "$$\n", 150 | "\n", 151 | "Thus, we have $ u'(c^\\star) = V'(M) $ in every period, and thus\n", 152 | "\n", 153 | "$$\n", 154 | "u'\\big(c^\\star(M)\\big) = \\beta R \\mathbb{E}_{y} u'\\big(c^\\star\\big(\\underset{=M'}{\\underbrace{R[M-c^\\star(M)]+\\tilde{y}}}\\big)\\big)\n", 155 | "$$" 156 | ] 157 | }, 158 | { 159 | "cell_type": "markdown", 160 | "metadata": { 161 | "slideshow": { 162 | "slide_type": "slide" 163 | } 164 | }, 165 | "source": [ 166 | "#### Consumption smoothing\n", 167 | "\n", 168 | "In deterministic model where $ \\tilde{y} $ is fixed, if $ \\beta R = 1 $ we have in every two consecutive periods\n", 169 | "\n", 170 | "$$\n", 171 | "u'\\big(c^\\star(M)\\big) = u'\\big(c^\\star(M')\\big) \\Rightarrow\n", 172 | "c^\\star(M) = c^\\star(M')\n", 173 | "$$\n", 174 | "\n", 175 | "*Perfect consumption smoothing!*\n", 176 | "\n", 177 | "This is one of the tests for the correct solution of the consumption-savings model!" 178 | ] 179 | }, 180 | { 181 | "cell_type": "markdown", 182 | "metadata": { 183 | "slideshow": { 184 | "slide_type": "slide" 185 | } 186 | }, 187 | "source": [ 188 | "#### Accuracy measure using Euler equation\n", 189 | "\n", 190 | "Common in the literature is to use the average squared **Euler residuals** on a dense\n", 191 | "grid with $ K $ points as a measure of accuracy of the solution for Deaton model\n", 192 | "\n", 193 | "$$\n", 194 | "ER\\big( c(M) \\big) = u'\\big(c(M)\\big) - \\beta R \\mathbb{E}_{y} u'\\big(c\\big(R[M-c(M)]+\\tilde{y}\\big)\\big)\n", 195 | "$$\n", 196 | "\n", 197 | "$$\n", 198 | "Q \\big( c(M) \\big) = \\frac{1}{K} \\sum_{k=1}^{K} {ER}^2\\big( c(M_k) \\big)\n", 199 | "$$\n", 200 | "\n", 201 | "The closer $ Q\\big( c(M) \\big) $ is to zero, the better the solution" 202 | ] 203 | }, 204 | { 205 | "cell_type": "markdown", 206 | "metadata": { 207 | "slideshow": { 208 | "slide_type": "slide" 209 | } 210 | }, 211 | "source": [ 212 | "### Time iterations\n", 213 | "\n", 214 | "The idea of this solution method is to solve the Euler equation in the space of\n", 215 | "policy functions $ c(M) \\in \\mathcal{P} $ as a *functional equation*\n", 216 | "\n", 217 | "$$\n", 218 | "u'\\big(c(M)\\big) = \\beta R \\mathbb{E}_{y} u'\\big(c[R(M-c(M))+\\tilde{y}]\\big)\n", 219 | "$$\n", 220 | "\n", 221 | "The solution is given by the **fixed point** of the *Coleman-Reffett operator* $ K(c)(M) $\n", 222 | "\n", 223 | "- takes as input policy function $ c(M) \\in \\mathcal{P} $ \n", 224 | "- returns the updated policy function $ c'(M) \\in \\mathcal{P} $ that for every $ M $ satisfies \n", 225 | "\n", 226 | "\n", 227 | "$$\n", 228 | "u'\\big(c'(M)\\big) = \\beta R \\mathbb{E}_{y} u'\\big(c[R(M-c'(M))+\\tilde{y}]\\big)\n", 229 | "$$" 230 | ] 231 | }, 232 | { 233 | "cell_type": "markdown", 234 | "metadata": { 235 | "slideshow": { 236 | "slide_type": "slide" 237 | } 238 | }, 239 | "source": [ 240 | "#### Contraction mapping?\n", 241 | "\n", 242 | "Is Coleman-Reffett operator a contraction mapping? **Yes** (in the reasonable metric space with a specially defined norm)\n", 243 | "\n", 244 | "📖 Huiyu Li, John Stachurski (2014, *Journal of Economic Dynamics and Control*) “Solving the income fluctuation problem with unbounded rewards”\n", 245 | "\n", 246 | "- Existence and uniqueness of the solution! \n", 247 | "- Successive approximations solver will deliver the solution \n", 248 | "- Globally convergent " 249 | ] 250 | }, 251 | { 252 | "cell_type": "markdown", 253 | "metadata": { 254 | "slideshow": { 255 | "slide_type": "slide" 256 | } 257 | }, 258 | "source": [ 259 | "#### Time iteration algorithm\n", 260 | "\n", 261 | "1. Discretize the state space \n", 262 | "1. Set the initial policy $ c_0(M) $ at state grid \n", 263 | "1. Increment iteration counter $ i $ (initialize to 0) \n", 264 | "1. Solve Euler equation in every point of the the grid, i.e. plug $ c_{i-1}(M) $ to the\n", 265 | " RHS of the Euler equation, and solve for the $ c $ in the LHS, it becomes new $ c_i(M) $ \n", 266 | "1. Check for convergence in policy function space: \n", 267 | " - If converged, output $ c_i(M) $ \n", 268 | " - Otherwise, return to step 3. " 269 | ] 270 | }, 271 | { 272 | "cell_type": "markdown", 273 | "metadata": { 274 | "slideshow": { 275 | "slide_type": "slide" 276 | } 277 | }, 278 | "source": [ 279 | "#### Accuracy and speed\n", 280 | "\n", 281 | "How does time iteration solver compares to VFI (with explicit maximization)?\n", 282 | "\n", 283 | "- theoretical complexity and convergence rates are the same \n", 284 | "- policy functions are easier to interpolate (less curvature), so interpolation errors are smaller \n", 285 | "- therefore time iterations usually converge faster \n", 286 | "- for the same reasons time iterations deliver more accurate solution \n", 287 | "\n", 288 | "\n", 289 | "Will do some experiments in the next practical video" 290 | ] 291 | }, 292 | { 293 | "cell_type": "markdown", 294 | "metadata": { 295 | "slideshow": { 296 | "slide_type": "slide" 297 | } 298 | }, 299 | "source": [ 300 | "### Further learning resources\n", 301 | "\n", 302 | "- Derivation of Euler equation in cake eating model [https://python.quantecon.org/cake_eating_problem.html](https://python.quantecon.org/cake_eating_problem.html) \n", 303 | "- Time iterations on QuantEcon [https://python.quantecon.org/coleman_policy_iter.html](https://python.quantecon.org/coleman_policy_iter.html) " 304 | ] 305 | } 306 | ], 307 | "metadata": { 308 | "celltoolbar": "Slideshow", 309 | "date": 1612589586.504768, 310 | "download_nb": false, 311 | "filename": "39_euler_timeiter.rst", 312 | "filename_with_path": "39_euler_timeiter", 313 | "kernelspec": { 314 | "display_name": "Python", 315 | "language": "python3", 316 | "name": "python3" 317 | }, 318 | "language_info": { 319 | "codemirror_mode": { 320 | "name": "ipython", 321 | "version": 3 322 | }, 323 | "file_extension": ".py", 324 | "mimetype": "text/x-python", 325 | "name": "python", 326 | "nbconvert_exporter": "python", 327 | "pygments_lexer": "ipython3", 328 | "version": "3.7.6" 329 | }, 330 | "title": "Foundations of Computational Economics #39" 331 | }, 332 | "nbformat": 4, 333 | "nbformat_minor": 4 334 | } 335 | -------------------------------------------------------------------------------- /47_exam_prep.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": { 6 | "slideshow": { 7 | "slide_type": "slide" 8 | } 9 | }, 10 | "source": [ 11 | "# Foundations of Computational Economics #47\n", 12 | "\n", 13 | "by Fedor Iskhakov, ANU\n", 14 | "\n", 15 | "" 16 | ] 17 | }, 18 | { 19 | "cell_type": "markdown", 20 | "metadata": { 21 | "slideshow": { 22 | "slide_type": "fragment" 23 | } 24 | }, 25 | "source": [ 26 | "## Example exam questions\n", 27 | "\n", 28 | "" 29 | ] 30 | }, 31 | { 32 | "cell_type": "markdown", 33 | "metadata": { 34 | "slideshow": { 35 | "slide_type": "subslide" 36 | } 37 | }, 38 | "source": [ 39 | "\n", 40 | "\n", 41 | "[https://youtu.be/zmxxyNsyTGI](https://youtu.be/zmxxyNsyTGI)\n", 42 | "\n", 43 | "Description: Examples of questions and answers in the exam." 44 | ] 45 | }, 46 | { 47 | "cell_type": "markdown", 48 | "metadata": { 49 | "slideshow": { 50 | "slide_type": "slide" 51 | } 52 | }, 53 | "source": [ 54 | "### Instructions: (from last year’s exam)\n", 55 | "\n", 56 | "- Complete the tasks listed in this Jupyter notebook by answering\n", 57 | " questions and writing the code in the cell provided \n", 58 | "- Each task has a number of points associated with it, the complete\n", 59 | " exam assignment has 100 points \n", 60 | "- The grade is the total number of points earned \n", 61 | "- Started but not completed tasks, as well as task completed with\n", 62 | " errors earn partial points \n", 63 | "- You have 180 minutes to compete the exam \n", 64 | "- **Make sure to commit your work to Git and push the changes to GitHub for grading** (alternative ways to submit your exam may have been set on individual bases) " 65 | ] 66 | }, 67 | { 68 | "cell_type": "markdown", 69 | "metadata": { 70 | "slideshow": { 71 | "slide_type": "slide" 72 | } 73 | }, 74 | "source": [ 75 | "#### Overall structure (last year)\n", 76 | "\n", 77 | "- five 2 point questions (10 points) \n", 78 | "- ten 3 point questions (30 points) \n", 79 | "- four 5 point questions (20 points) \n", 80 | "- four 10 point questions (40 points) " 81 | ] 82 | }, 83 | { 84 | "cell_type": "markdown", 85 | "metadata": { 86 | "slideshow": { 87 | "slide_type": "slide" 88 | } 89 | }, 90 | "source": [ 91 | "#### Types of questions/tasks\n", 92 | "\n", 93 | "- 2 point and 3 points: elementary and simple questions which require short answer and check the knowledge of some simple facts \n", 94 | "- 5 points: more elaborate questions, short coding tasks, find-a-bug questions \n", 95 | "- 10 points: more elaborate coding tasks, very hard on their own, but doable with good knowledge and understanding of the code base developed in the course (so that useful donor code can be copied in quickly) " 96 | ] 97 | }, 98 | { 99 | "cell_type": "markdown", 100 | "metadata": { 101 | "slideshow": { 102 | "slide_type": "slide" 103 | } 104 | }, 105 | "source": [ 106 | "#### Question 1. (2 points)\n", 107 | "\n", 108 | "In Python code when assigning a value to a variable, how many spaces\n", 109 | "should be used around the “=” sign according to PEP8?" 110 | ] 111 | }, 112 | { 113 | "cell_type": "markdown", 114 | "metadata": { 115 | "slideshow": { 116 | "slide_type": "slide" 117 | } 118 | }, 119 | "source": [ 120 | "#### Question 2. (2 points)\n", 121 | "\n", 122 | "How does convergence rate of the value function iterations (successive\n", 123 | "approximation) algorithm depend on the discount coefficient\n", 124 | "$ \\beta $?" 125 | ] 126 | }, 127 | { 128 | "cell_type": "markdown", 129 | "metadata": { 130 | "slideshow": { 131 | "slide_type": "slide" 132 | } 133 | }, 134 | "source": [ 135 | "#### Question 3. (3 points)\n", 136 | "\n", 137 | "In NumPy what arithmetic operations differ between the two-dimensional\n", 138 | "array type and the matrix type variables?" 139 | ] 140 | }, 141 | { 142 | "cell_type": "code", 143 | "execution_count": 1, 144 | "metadata": { 145 | "hide-output": false, 146 | "slideshow": { 147 | "slide_type": "slide" 148 | } 149 | }, 150 | "outputs": [ 151 | { 152 | "name": "stdout", 153 | "output_type": "stream", 154 | "text": [ 155 | "[[ 2 4 6]\n", 156 | " [ 0 6 10]\n", 157 | " [14 8 2]]\n", 158 | "[[ 2 4 6]\n", 159 | " [ 0 6 10]\n", 160 | " [14 8 2]]\n", 161 | "\n", 162 | "[[0 0 0]\n", 163 | " [0 0 0]\n", 164 | " [0 0 0]]\n", 165 | "[[0 0 0]\n", 166 | " [0 0 0]\n", 167 | " [0 0 0]]\n", 168 | "\n", 169 | "[[ 1 4 9]\n", 170 | " [ 0 9 25]\n", 171 | " [49 16 1]]\n", 172 | "[[22 20 16]\n", 173 | " [35 29 20]\n", 174 | " [14 30 42]]\n", 175 | "\n", 176 | "[[ 1. 1. 1.]\n", 177 | " [nan 1. 1.]\n", 178 | " [ 1. 1. 1.]]\n", 179 | "[[ 1. 1. 1.]\n", 180 | " [nan 1. 1.]\n", 181 | " [ 1. 1. 1.]]\n", 182 | "\n", 183 | "[[22 20 16]\n", 184 | " [35 29 20]\n", 185 | " [14 30 42]]\n", 186 | "[[22 20 16]\n", 187 | " [35 29 20]\n", 188 | " [14 30 42]]\n", 189 | "\n" 190 | ] 191 | }, 192 | { 193 | "name": "stderr", 194 | "output_type": "stream", 195 | "text": [ 196 | "/usr/local/anaconda3/lib/python3.7/site-packages/ipykernel_launcher.py:7: RuntimeWarning: invalid value encountered in true_divide\n", 197 | " import sys\n" 198 | ] 199 | } 200 | ], 201 | "source": [ 202 | "import numpy as np\n", 203 | "a = np.array([[1,2,3],[0,3,5],[7,4,1]])\n", 204 | "b = np.matrix([[1,2,3],[0,3,5],[7,4,1]])\n", 205 | "print(a+a,b+b,sep='\\n',end='\\n\\n')\n", 206 | "print(a-a,b-b,sep='\\n',end='\\n\\n')\n", 207 | "print(a*a,b*b,sep='\\n',end='\\n\\n')\n", 208 | "print(a/a,b/b,sep='\\n',end='\\n\\n')\n", 209 | "print(a@a,b@b,sep='\\n',end='\\n\\n')" 210 | ] 211 | }, 212 | { 213 | "cell_type": "markdown", 214 | "metadata": { 215 | "slideshow": { 216 | "slide_type": "slide" 217 | } 218 | }, 219 | "source": [ 220 | "#### Question 4. (3 points)\n", 221 | "\n", 222 | "Write the Bellman equation for the infinite horizon formulations of\n", 223 | "the following problem:\n", 224 | "\n", 225 | "- choice variable $ c $ \n", 226 | "- state variables $ x,y,z $ \n", 227 | "- $ x $ and $ y $ evolve stochastically with transition densities $ f_x(x',x,c) $ and $ f_y(y',x,y) $ \n", 228 | "- instantaneous utility is given by $ u(c,y) $ \n", 229 | "- motion rule for variable $ z $ can be left unspecified in the Bellman equation " 230 | ] 231 | }, 232 | { 233 | "cell_type": "markdown", 234 | "metadata": { 235 | "slideshow": { 236 | "slide_type": "slide" 237 | } 238 | }, 239 | "source": [ 240 | "$$\n", 241 | "V(x,y,z) = \\max_{c} \\big[ U(c,y) + \\beta \\int\\int V(x',y',z') f_y(y',x,y) f_x(x',x,c) dy' dx' \\big]\n", 242 | "$$" 243 | ] 244 | }, 245 | { 246 | "cell_type": "markdown", 247 | "metadata": { 248 | "slideshow": { 249 | "slide_type": "slide" 250 | } 251 | }, 252 | "source": [ 253 | "#### Question 5. (5 points)\n", 254 | "\n", 255 | "Write a list comprehension expression to produce pairs of squares and\n", 256 | "cubes of all integers between 1 to 10 inclusive." 257 | ] 258 | }, 259 | { 260 | "cell_type": "code", 261 | "execution_count": 2, 262 | "metadata": { 263 | "hide-output": false, 264 | "slideshow": { 265 | "slide_type": "slide" 266 | } 267 | }, 268 | "outputs": [ 269 | { 270 | "name": "stdout", 271 | "output_type": "stream", 272 | "text": [ 273 | "[(1, 1), (4, 8), (9, 27), (16, 64), (25, 125), (36, 216), (49, 343), (64, 512), (81, 729), (100, 1000)]\n" 274 | ] 275 | } 276 | ], 277 | "source": [ 278 | "squares_and_cubs = [(x**2,x**3) for x in range(1,11)]\n", 279 | "print(squares_and_cubs)" 280 | ] 281 | }, 282 | { 283 | "cell_type": "markdown", 284 | "metadata": { 285 | "slideshow": { 286 | "slide_type": "slide" 287 | } 288 | }, 289 | "source": [ 290 | "#### Question 6. (5 points)\n", 291 | "\n", 292 | "The code below outputs a negative value. This is strange because it\n", 293 | "calculates an average of the powers of 2, which are all positive\n", 294 | "numbers. Explain what is going on and fix the bug with *minimal change to\n", 295 | "the code*." 296 | ] 297 | }, 298 | { 299 | "cell_type": "code", 300 | "execution_count": 3, 301 | "metadata": { 302 | "hide-output": false, 303 | "slideshow": { 304 | "slide_type": "slide" 305 | } 306 | }, 307 | "outputs": [ 308 | { 309 | "name": "stdout", 310 | "output_type": "stream", 311 | "text": [ 312 | "-2.56\n" 313 | ] 314 | } 315 | ], 316 | "source": [ 317 | "import numpy as np\n", 318 | "a = 2**np.arange(100)\n", 319 | "print(a.mean())" 320 | ] 321 | }, 322 | { 323 | "cell_type": "markdown", 324 | "metadata": { 325 | "slideshow": { 326 | "slide_type": "slide" 327 | } 328 | }, 329 | "source": [ 330 | "#### Question 7. (10 points)\n", 331 | "\n", 332 | "Derive **your own algorithm** and implement it in a function that takes\n", 333 | "an integer decimal number and outputs its binary representation. Write\n", 334 | "your code in the cell below and run the test cases." 335 | ] 336 | }, 337 | { 338 | "cell_type": "code", 339 | "execution_count": 4, 340 | "metadata": { 341 | "hide-output": false, 342 | "slideshow": { 343 | "slide_type": "slide" 344 | } 345 | }, 346 | "outputs": [ 347 | { 348 | "name": "stdout", 349 | "output_type": "stream", 350 | "text": [ 351 | "[]\n", 352 | "[]\n", 353 | "[]\n", 354 | "[]\n", 355 | "[]\n", 356 | "[]\n" 357 | ] 358 | } 359 | ], 360 | "source": [ 361 | "def binary(x):\n", 362 | " '''Input: integer in decimal, output: vector of 0 and 1 to represent the input in binary'''\n", 363 | " # write your code here\n", 364 | " return []\n", 365 | "\n", 366 | "print(binary(1))\n", 367 | "print(binary(2))\n", 368 | "print(binary(3))\n", 369 | "print(binary(4))\n", 370 | "print(binary(1673))\n", 371 | "print(binary(3428))" 372 | ] 373 | }, 374 | { 375 | "cell_type": "code", 376 | "execution_count": 5, 377 | "metadata": { 378 | "hide-output": false, 379 | "slideshow": { 380 | "slide_type": "slide" 381 | } 382 | }, 383 | "outputs": [ 384 | { 385 | "name": "stdout", 386 | "output_type": "stream", 387 | "text": [ 388 | "0 = [0]\n", 389 | "1 = [1]\n", 390 | "2 = [1, 0]\n", 391 | "3 = [1, 1]\n", 392 | "4 = [1, 0, 0]\n", 393 | "5 = [1, 0, 1]\n", 394 | "6 = [1, 1, 0]\n", 395 | "7 = [1, 1, 1]\n", 396 | "8 = [1, 0, 0, 0]\n", 397 | "9 = [1, 0, 0, 1]\n", 398 | "10 = [1, 0, 1, 0]\n", 399 | "11 = [1, 0, 1, 1]\n", 400 | "12 = [1, 1, 0, 0]\n", 401 | "13 = [1, 1, 0, 1]\n", 402 | "14 = [1, 1, 1, 0]\n", 403 | "15 = [1, 1, 1, 1]\n", 404 | "16 = [1, 0, 0, 0, 0]\n", 405 | "17 = [1, 0, 0, 0, 1]\n", 406 | "18 = [1, 0, 0, 1, 0]\n", 407 | "19 = [1, 0, 0, 1, 1]\n", 408 | "20 = [1, 0, 1, 0, 0]\n", 409 | "21 = [1, 0, 1, 0, 1]\n", 410 | "22 = [1, 0, 1, 1, 0]\n", 411 | "23 = [1, 0, 1, 1, 1]\n", 412 | "24 = [1, 1, 0, 0, 0]\n", 413 | "25 = [1, 1, 0, 0, 1]\n", 414 | "26 = [1, 1, 0, 1, 0]\n", 415 | "27 = [1, 1, 0, 1, 1]\n", 416 | "28 = [1, 1, 1, 0, 0]\n", 417 | "29 = [1, 1, 1, 0, 1]\n", 418 | "30 = [1, 1, 1, 1, 0]\n", 419 | "31 = [1, 1, 1, 1, 1]\n", 420 | "[1]\n", 421 | "[1, 0]\n", 422 | "[1, 1]\n", 423 | "[1, 0, 0]\n", 424 | "[1, 1, 0, 1, 0, 0, 0, 1, 0, 0, 1]\n", 425 | "[1, 1, 0, 1, 0, 1, 1, 0, 0, 1, 0, 0]\n" 426 | ] 427 | } 428 | ], 429 | "source": [ 430 | "def binary(x):\n", 431 | " '''Input: integer in decimal, output: vector of 0 and 1 to represent the input in binary'''\n", 432 | " d = []\n", 433 | " while True:\n", 434 | " d.append(x%2)\n", 435 | " x//=2\n", 436 | " if x==0:\n", 437 | " return d[::-1]\n", 438 | "\n", 439 | "for i in range(32):\n", 440 | " print(i,binary(i),sep=' = ')\n", 441 | "\n", 442 | "print(binary(1))\n", 443 | "print(binary(2))\n", 444 | "print(binary(3))\n", 445 | "print(binary(4))\n", 446 | "print(binary(1673))\n", 447 | "print(binary(3428))" 448 | ] 449 | }, 450 | { 451 | "cell_type": "markdown", 452 | "metadata": { 453 | "slideshow": { 454 | "slide_type": "slide" 455 | } 456 | }, 457 | "source": [ 458 | "#### Question 8. (10 points)\n", 459 | "\n", 460 | "Consider the consumption/savings problem in the infinite horizon. Each\n", 461 | "period the agent chooses how much to consume from the cash-in-hand\n", 462 | "$ M_t $ (without borrowing). The amount remaining after consumption\n", 463 | "grows stochastically with the gross return taking one of five values\n", 464 | "presented in the table below (independently distributed across time). In\n", 465 | "addition, each period the agent receives a non-stochastic government\n", 466 | "support payment of \\$10 (in thousands). Return on savings and the latter\n", 467 | "payment are the only sources of income.\n", 468 | "\n", 469 | "The instantaneous utility of consumption is given by\n", 470 | "$ u(C_t)=\\log(C_t) $.\n", 471 | "\n", 472 | "Stochastic gross returns on savings are given by\n", 473 | "\n", 474 | "|R|0.85|0.95|1.05|1.10|1.40|\n", 475 | "|:-:|:----:|:----:|:----:|:----:|:----:|\n", 476 | "|p|0.05|0.20|0.55|0.15|0.05|\n", 477 | ".\n", 478 | "\n", 479 | "1. Write the Bellman equation for the problem. \n", 480 | "1. Write the code to solve the problem and plot the value function and\n", 481 | " the optimal policy function, assuming that the choices are made on a\n", 482 | " discrete grid with step \\$1, and the upper bound of the problem is set\n", 483 | " to \\$200. " 484 | ] 485 | } 486 | ], 487 | "metadata": { 488 | "celltoolbar": "Slideshow", 489 | "date": 1612589586.926353, 490 | "download_nb": false, 491 | "filename": "47_exam_prep.rst", 492 | "filename_with_path": "47_exam_prep", 493 | "kernelspec": { 494 | "display_name": "Python", 495 | "language": "python3", 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.7.6" 509 | }, 510 | "title": "Foundations of Computational Economics #47" 511 | }, 512 | "nbformat": 4, 513 | "nbformat_minor": 4 514 | } 515 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2020 Fedor Iskhakov 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # CompEcon 2 | My "Foundations of Computational Economics" course 3 | 4 | See https://fedor.iskh.me/teaching and https://fedor.iskh.me/compecon 5 | 6 | -------------------------------------------------------------------------------- /_static/data/beijin_data.dta: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/data/beijin_data.dta -------------------------------------------------------------------------------- /_static/img/MCIntegration.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/MCIntegration.png -------------------------------------------------------------------------------- /_static/img/PythonLogo.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/PythonLogo.jpg -------------------------------------------------------------------------------- /_static/img/bigO.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/bigO.png -------------------------------------------------------------------------------- /_static/img/binary.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/binary.png -------------------------------------------------------------------------------- /_static/img/bit_map.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/bit_map.gif -------------------------------------------------------------------------------- /_static/img/bitshift.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/bitshift.png -------------------------------------------------------------------------------- /_static/img/bitwise.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/bitwise.png -------------------------------------------------------------------------------- /_static/img/broadcasting.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/broadcasting.png -------------------------------------------------------------------------------- /_static/img/cake.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/cake.png -------------------------------------------------------------------------------- /_static/img/chicago-booth-oeystein-daljord.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/chicago-booth-oeystein-daljord.jpg -------------------------------------------------------------------------------- /_static/img/complexity_classes.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/complexity_classes.png -------------------------------------------------------------------------------- /_static/img/complexity_classes_board.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/complexity_classes_board.png -------------------------------------------------------------------------------- /_static/img/composite_simpsons.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/composite_simpsons.png -------------------------------------------------------------------------------- /_static/img/dag3logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/dag3logo.png -------------------------------------------------------------------------------- /_static/img/dataframe.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/dataframe.jpg -------------------------------------------------------------------------------- /_static/img/float_map.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/float_map.jpg -------------------------------------------------------------------------------- /_static/img/github.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/github.png -------------------------------------------------------------------------------- /_static/img/graph1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/graph1.png -------------------------------------------------------------------------------- /_static/img/graph2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/graph2.png -------------------------------------------------------------------------------- /_static/img/half-precision-floating-point.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/half-precision-floating-point.jpg -------------------------------------------------------------------------------- /_static/img/invcdf.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/invcdf.png -------------------------------------------------------------------------------- /_static/img/kantorovich.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/kantorovich.jpg -------------------------------------------------------------------------------- /_static/img/lab.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/lab.png -------------------------------------------------------------------------------- /_static/img/language_verbosity.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/language_verbosity.png -------------------------------------------------------------------------------- /_static/img/lecture.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/lecture.png -------------------------------------------------------------------------------- /_static/img/lp1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/lp1.png -------------------------------------------------------------------------------- /_static/img/markov3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/markov3.png -------------------------------------------------------------------------------- /_static/img/nedlermead.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/nedlermead.png -------------------------------------------------------------------------------- /_static/img/newton-cotes.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/newton-cotes.jpg -------------------------------------------------------------------------------- /_static/img/newton_fractal.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/newton_fractal.png -------------------------------------------------------------------------------- /_static/img/nfxp_manual.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/nfxp_manual.png -------------------------------------------------------------------------------- /_static/img/numpy_logo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/numpy_logo.png -------------------------------------------------------------------------------- /_static/img/oop.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/oop.png -------------------------------------------------------------------------------- /_static/img/pimc.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/pimc.jpg -------------------------------------------------------------------------------- /_static/img/polyhedron2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/polyhedron2.png -------------------------------------------------------------------------------- /_static/img/polyhedron3.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/polyhedron3.png -------------------------------------------------------------------------------- /_static/img/python_growth.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/python_growth.png -------------------------------------------------------------------------------- /_static/img/python_projections.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/python_projections.png -------------------------------------------------------------------------------- /_static/img/python_usage.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/python_usage.png -------------------------------------------------------------------------------- /_static/img/randbitmap_computer.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/randbitmap_computer.png -------------------------------------------------------------------------------- /_static/img/randbitmap_true.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/randbitmap_true.png -------------------------------------------------------------------------------- /_static/img/runtime1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/runtime1.png -------------------------------------------------------------------------------- /_static/img/runtime2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/runtime2.png -------------------------------------------------------------------------------- /_static/img/th.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/th.jpg -------------------------------------------------------------------------------- /_static/img/tile1.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/tile1.jpg -------------------------------------------------------------------------------- /_static/img/tile2.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/tile2.jpg -------------------------------------------------------------------------------- /_static/img/tile3.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/tile3.jpg -------------------------------------------------------------------------------- /_static/img/tile4.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/tile4.jpg -------------------------------------------------------------------------------- /_static/img/tile5.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/tile5.jpg -------------------------------------------------------------------------------- /_static/img/tile6.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/tile6.jpg -------------------------------------------------------------------------------- /_static/img/tradeoffs.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/tradeoffs.png -------------------------------------------------------------------------------- /_static/img/transportation.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/transportation.png -------------------------------------------------------------------------------- /_static/img/viz/5stage_eqb.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/viz/5stage_eqb.png -------------------------------------------------------------------------------- /_static/img/viz/CDF_2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/viz/CDF_2.png -------------------------------------------------------------------------------- /_static/img/viz/ConsT3NumQuad_sigma0IncVar0.01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/viz/ConsT3NumQuad_sigma0IncVar0.01.png -------------------------------------------------------------------------------- /_static/img/viz/cpu_vs_N.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/viz/cpu_vs_N.png -------------------------------------------------------------------------------- /_static/img/viz/dcegm_value.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/viz/dcegm_value.png -------------------------------------------------------------------------------- /_static/img/viz/distribution_earnings.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/viz/distribution_earnings.png -------------------------------------------------------------------------------- /_static/img/viz/eqb2bw_pureA.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/viz/eqb2bw_pureA.png -------------------------------------------------------------------------------- /_static/img/viz/eqb2bw_symm.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/viz/eqb2bw_symm.png -------------------------------------------------------------------------------- /_static/img/viz/eqb_map.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/viz/eqb_map.png -------------------------------------------------------------------------------- /_static/img/viz/eqb_n5_randtech-eps-converted-to.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/viz/eqb_n5_randtech-eps-converted-to.png -------------------------------------------------------------------------------- /_static/img/viz/fig_moments2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/viz/fig_moments2.png -------------------------------------------------------------------------------- /_static/img/viz/fig_moments_lastrun.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/viz/fig_moments_lastrun.png -------------------------------------------------------------------------------- /_static/img/viz/map.jpg: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/viz/map.jpg -------------------------------------------------------------------------------- /_static/img/viz/octane95_price_composition.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/viz/octane95_price_composition.png -------------------------------------------------------------------------------- /_static/img/viz/phelps4.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/viz/phelps4.png -------------------------------------------------------------------------------- /_static/img/viz/plot1-super.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/viz/plot1-super.png -------------------------------------------------------------------------------- /_static/img/viz/strava-heatmap-north-and-south-korea.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/viz/strava-heatmap-north-and-south-korea.png -------------------------------------------------------------------------------- /_static/img/viz/trpr2_diversification.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/viz/trpr2_diversification.png -------------------------------------------------------------------------------- /_static/img/viz/waves_full_data.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/viz/waves_full_data.png -------------------------------------------------------------------------------- /_static/img/youtube.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/fediskhakov/CompEcon/b640e058de7a9a3250af233be1776ac667b6c7eb/_static/img/youtube.png -------------------------------------------------------------------------------- /_static/include/algorithm_examples.py: -------------------------------------------------------------------------------- 1 | # Example code to be discussed in the following videos 2 | 3 | import time 4 | 5 | def parity (n,verbose=False): 6 | '''Returns 1 if passed integer number is odd 7 | ''' 8 | if not isinstance(n, int): raise TypeError('Only integers in parity()') 9 | if verbose: print('n = ', format(n, "b")) # print binary form of the number 10 | return n & 1 # bitwise and operation returns the value of last bit 11 | 12 | def maximum_from_list (vars): 13 | '''Returns the maximum from a list of values 14 | ''' 15 | m=float('-inf') # init with the worst value 16 | for v in vars: 17 | if v > m: m = v 18 | return m 19 | 20 | def binary_search(grid=[0,1],val=0,delay=0): 21 | '''Returns the index of val on the sorted grid 22 | Optional delay introduces a delay (in microsecond) 23 | ''' 24 | i1,i2 = 0,len(grid)-1 25 | if val==grid[i1]: return i1 26 | if val==grid[i2]: return i2 27 | j=(i1+i2)//2 28 | while grid[j]!=val: 29 | if val>grid[j]: 30 | i1=j 31 | else: 32 | i2=j 33 | j=(i1+i2)//2 # divide in half 34 | time.sleep(delay*1e-6) # micro-sec to seconds 35 | return j 36 | 37 | def compositions(N,m): 38 | '''Iterable on compositions of N with m parts 39 | Returns the generator (to be used in for loops) 40 | ''' 41 | cmp=[0,]*m 42 | cmp[m-1]=N # initial composition is all to the last 43 | yield cmp 44 | while cmp[0]!=N: 45 | i=m-1 46 | while cmp[i]==0: i-=1 # find lowest non-zero digit 47 | cmp[i-1] = cmp[i-1]+1 # increment next digit 48 | cmp[m-1] = cmp[i]-1 # the rest to the lowest 49 | if i!=m-1: cmp[i] = 0 # maintain cost sum 50 | yield cmp 51 | -------------------------------------------------------------------------------- /_static/include/obj_explore.py: -------------------------------------------------------------------------------- 1 | 2 | def obj_explore(obj,what='all'): 3 | '''Lists attributes and methods of a class 4 | Input arguments: obj = variable to explore, 5 | what = string with any combination of 6 | all, public, private, methods, properties 7 | ''' 8 | import sys # this function will run rarely, so import here 9 | trstr = lambda s: s[:30] if isinstance(s, str) else s # truncates if string 10 | spacer = lambda s: " "*max(15-len(s),2) # returns spacer to pad strings 11 | hr='-'*60 # horizontal line 12 | print(obj) # string representation of the input 13 | print('%s\nObject report on object = %r' % (hr,obj)) 14 | cl=type(obj) 15 | print('Objec class : %s' % cl) 16 | print('Parent classes : %r' % cl.__bases__) 17 | print('Occupied memory : %d bytes' % sys.getsizeof(obj)) 18 | if what in 'all public properties': 19 | print('PUBLIC PROPERTIES') 20 | data = [(name,getattr(obj,name)) for name in dir(obj) if not callable(getattr(obj,name)) and name[0:2]!='__'] 21 | for item in data: 22 | print('%s = %r %s' % (item[0]+spacer(item[0]),trstr(item[1]),type(item[1]))) 23 | if what in 'all private properties': 24 | print('PRIVATE PROPERTIES') 25 | data = [(name,getattr(obj,name)) for name in dir(obj) if not callable(getattr(obj,name)) and name[0:2]=='__'] 26 | for item in data: 27 | print('%s = %r %s' % (item[0]+spacer(item[0]),trstr(item[1]),type(item[1]))) 28 | if what in 'all public methods': 29 | print('PUBLIC METHODS') 30 | data = [(name,getattr(obj,name)) for name in dir(obj) if callable(getattr(obj,name)) and name[0:2]!='__'] 31 | for item in data: 32 | print('%s %s' % (item[0]+spacer(item[0]),type(item[1]))) 33 | if what in 'all private methods': 34 | print('PRIVATE METHODS') 35 | data = [(name,getattr(obj,name)) for name in dir(obj) if callable(getattr(obj,name)) and name[0:2]=='__'] 36 | for item in data: 37 | print('%s %s' % (item[0]+spacer(item[0]),type(item[1]))) 38 | -------------------------------------------------------------------------------- /_static/include/optim.py: -------------------------------------------------------------------------------- 1 | # Collection of simple optimization algorithms from the Computational Economics course 2 | # 3 | # by Fedor Iskhakov, 2020 4 | 5 | import numpy as np 6 | 7 | def bisection(f,a=0,b=1,tol=1e-6,maxiter=100,callback=None): 8 | '''Bisection method for solving equation f(x)=0 9 | on the interval [a,b], with given tolerance and number of iterations. 10 | Callback function is invoked at each iteration if given. 11 | ''' 12 | if f(a)*f(b)>0: 13 | raise ValueError('Function has the same sign at the bounds') 14 | for i in range(maxiter): 15 | err = abs(b-a) 16 | if err0 else (a,x) 19 | if callback != None: callback(err=err,x=x,iter=i) 20 | else: 21 | raise RuntimeError('Failed to converge in %d iterations'%maxiter) 22 | return x 23 | 24 | 25 | def newton(fun,grad,x0,tol=1e-6,maxiter=100,callback=None): 26 | '''Newton method for solving equation f(x)=0 27 | with given tolerance and number of iterations. 28 | Callback function is invoked at each iteration if given. 29 | ''' 30 | for i in range(maxiter): 31 | x1 = x0 - fun(x0)/grad(x0) 32 | err = abs(x1-x0) 33 | if callback != None: callback(err=err,x0=x0,x1=x1,iter=i) 34 | if err \\text{th}_4\n", 30 | "\\end{cases}\n", 31 | "$$\n", 32 | "\n", 33 | "The values for the thresholds and the rates in the 15 year in the period\n", 34 | "between 2000 and 2015 are given in the table below.\n", 35 | "\n", 36 | "|Year|$ th_1 $|$ th_2 $|$ th_3 $|$ th_4 $|$ rate_1 $|$ rate_2 $|$ rate_3 $|$ rate_4 $|\n", 37 | "|:----:|:------------:|:------------:|:------------:|:------------:|:--------------:|:--------------:|:--------------:|:--------------:|\n", 38 | "|2000|6,000|20,000|50,000|60,000|0.17|0.30|0.42|0.47|\n", 39 | "|2001|6,000|20,000|50,000|60,000|0.17|0.30|0.42|0.47|\n", 40 | "|2002|6,000|20,000|50,000|60,000|0.17|0.30|0.42|0.47|\n", 41 | "|2003|6,000|21,600|52,000|62,500|0.17|0.30|0.42|0.47|\n", 42 | "|2004|6,000|21,600|58,000|70,000|0.17|0.30|0.42|0.47|\n", 43 | "|2005|6,000|21,600|63,000|95,000|0.15|0.30|0.42|0.47|\n", 44 | "|2006|6,000|25,000|75,000|150,000|0.15|0.30|0.40|0.45|\n", 45 | "|2007|6,000|30,000|75,000|150,000|0.15|0.30|0.40|0.45|\n", 46 | "|2008|6,000|34,000|80,000|180,000|0.15|0.30|0.40|0.45|\n", 47 | "|2009|6,000|35,000|80,000|180,000|0.15|0.30|0.38|0.45|\n", 48 | "|2010|6,000|37,000|80,000|180,000|0.15|0.30|0.37|0.45|\n", 49 | "|2011|6,000|37,000|80,000|180,000|0.15|0.30|0.37|0.45|\n", 50 | "|2012|18,200|37,000|80,000|180,000|0.19|0.325|0.37|0.45|\n", 51 | "|2013|18,200|37,000|80,000|180,000|0.19|0.325|0.37|0.45|\n", 52 | "|2014|18,200|37,000|80,000|180,000|0.19|0.325|0.37|0.45|\n", 53 | "|2015|18,200|37,000|80,000|180,000|0.19|0.325|0.37|0.45|" 54 | ] 55 | }, 56 | { 57 | "cell_type": "markdown", 58 | "metadata": {}, 59 | "source": [ 60 | "## Task 1:\n", 61 | "\n", 62 | "- Write a function to calculate income tax from 2 input arguments: year and amount of income \n", 63 | "- Use **if/elif/then** statements for branching of the code \n", 64 | "- Run your function on the data provided " 65 | ] 66 | }, 67 | { 68 | "cell_type": "code", 69 | "execution_count": null, 70 | "metadata": { 71 | "hide-output": false 72 | }, 73 | "outputs": [], 74 | "source": [ 75 | "# draft implementation for year 2000 to get you started\n", 76 | "\n", 77 | "income=54780.0\n", 78 | "\n", 79 | "if income <= 6000:\n", 80 | " tax = 0.0\n", 81 | "elif income > 6000 and income <= 20000:\n", 82 | " tax = (income-6000)*0.17\n", 83 | "elif income > 20000 and income <= 50000:\n", 84 | " tax = (income-20000)*0.30\n", 85 | "elif income > 50000 and income <= 60000:\n", 86 | " tax = (income-50000)*0.42\n", 87 | "elif income > 60000:\n", 88 | " tax = (income-60000)*0.47\n", 89 | "\n", 90 | "print('tax(%1.2f) = %1.2f AUD' % (income,tax))" 91 | ] 92 | }, 93 | { 94 | "cell_type": "code", 95 | "execution_count": null, 96 | "metadata": { 97 | "hide-output": false 98 | }, 99 | "outputs": [], 100 | "source": [ 101 | "# run your function on the following data\n", 102 | "\n", 103 | "year = 2000\n", 104 | "income = 42400\n", 105 | "\n", 106 | "year = 2010\n", 107 | "income = 58300\n", 108 | "\n", 109 | "year = 2015\n", 110 | "income = 82710\n", 111 | "\n", 112 | "year = 2012\n", 113 | "income = 120340\n", 114 | "\n", 115 | "year = 2001\n", 116 | "income = 431400\n", 117 | "\n", 118 | "year = 2003\n", 119 | "income = 41870\n", 120 | "\n", 121 | "year = 2090\n", 122 | "income = 1407790" 123 | ] 124 | }, 125 | { 126 | "cell_type": "markdown", 127 | "metadata": {}, 128 | "source": [ 129 | "## Task 2:\n", 130 | "\n", 131 | "- Make the plot of the tax functions using the starter code below \n", 132 | "- Replace the @@@ symbols with appropriate code \n", 133 | "- The plot should show 15 different lines in the income - tax space " 134 | ] 135 | }, 136 | { 137 | "cell_type": "code", 138 | "execution_count": null, 139 | "metadata": { 140 | "hide-output": false 141 | }, 142 | "outputs": [], 143 | "source": [ 144 | "#let's make a plot as well\n", 145 | "import matplotlib.pyplot as plt\n", 146 | "%matplotlib inline\n", 147 | "plt.rcParams['figure.figsize'] = [12, 8]\n", 148 | "K = 250 #number of points in the income grid\n", 149 | "max_inc = 250000 #maximum income\n", 150 | "inc = [k * @@ / (K-1) for k in range(@@)] # grid over income\n", 151 | "tax = [0,]*K\n", 152 | "for year in [@@@ for i in range(@@)]:\n", 153 | " for j in range(@@):\n", 154 | " income = inc[j]\n", 155 | " tax[j] = @@@\n", 156 | " plt.plot(inc,tax,label=\"year %d\" % year)\n", 157 | "plt.xlabel(@@@)\n", 158 | "plt.ylabel(@@@)\n", 159 | "plt.show()" 160 | ] 161 | }, 162 | { 163 | "cell_type": "markdown", 164 | "metadata": {}, 165 | "source": [ 166 | "## Task 3 Alternative implementation [optional]\n", 167 | "\n", 168 | "- Write another implementation of the same function based on the **while** loop \n", 169 | "- Hint: precompute thresholds and rates based on the year, and run a while loop to compute the amount of tax in stages \n", 170 | "- Run the new implementation on the same data as above and verify it returns the same answers \n", 171 | "- Discuss the advantages and disadvantages of the two implementations " 172 | ] 173 | }, 174 | { 175 | "cell_type": "code", 176 | "execution_count": null, 177 | "metadata": { 178 | "hide-output": false 179 | }, 180 | "outputs": [], 181 | "source": [ 182 | "#Your code here" 183 | ] 184 | } 185 | ], 186 | "metadata": { 187 | "date": 1627475014.4823182, 188 | "filename": "exercise02.rst", 189 | "kernelspec": { 190 | "display_name": "Python", 191 | "language": "python3", 192 | "name": "python3" 193 | }, 194 | "title": "Weekly exercise 2: Tax function" 195 | }, 196 | "nbformat": 4, 197 | "nbformat_minor": 4 198 | } -------------------------------------------------------------------------------- /exercise03.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Weekly exercise 3: Two short quests on Python and Git\n", 8 | "\n", 9 | "GitHub offers “short courses” on its lab platform.\n", 10 | "\n", 11 | "To learn deeper about GitHub functionality while coding simple tasks in Python, follow these links:\n", 12 | "\n", 13 | "1. [https://lab.github.com/everydeveloper/introduction-to-python](https://lab.github.com/everydeveloper/introduction-to-python) \n", 14 | "1. [https://lab.github.com/everydeveloper/intermediate-python](https://lab.github.com/everydeveloper/intermediate-python) " 15 | ] 16 | } 17 | ], 18 | "metadata": { 19 | "date": 1627475014.486233, 20 | "filename": "exercise03.rst", 21 | "kernelspec": { 22 | "display_name": "Python", 23 | "language": "python3", 24 | "name": "python3" 25 | }, 26 | "title": "Weekly exercise 3: Two short quests on Python and Git" 27 | }, 28 | "nbformat": 4, 29 | "nbformat_minor": 4 30 | } -------------------------------------------------------------------------------- /exercise04.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Weekly exercise 4: Optimal choice in the bungle good market\n", 8 | "\n", 9 | "In this exercise I ask you to apply the machinery of bungled goods\n", 10 | "we have created in video 08 for answering some economic questions.\n", 11 | "Make sure you use the code written in that video which is stored\n", 12 | "in the notebook *08_bundles_ex2*." 13 | ] 14 | }, 15 | { 16 | "cell_type": "code", 17 | "execution_count": null, 18 | "metadata": { 19 | "hide-output": false 20 | }, 21 | "outputs": [], 22 | "source": [ 23 | "# copy the working code of the bungle_good class into this cell and run it" 24 | ] 25 | }, 26 | { 27 | "cell_type": "markdown", 28 | "metadata": {}, 29 | "source": [ 30 | "## Optimal choice of bundle goods\n", 31 | "\n", 32 | "Consider a consumer with a utility function over the individual goods\n", 33 | "given by\n", 34 | "\n", 35 | "$$\n", 36 | "u(x_1,\\dots,x_7)=\\log(x_1+1)+\\big((x_2)^{0.4}+0.5(x_3)^{0.4}\\big)^{2.5}-0.5\\log(x_4+1)-0.2(x_5*x_6)^{0.2}+2\\log(x_7+1).\n", 37 | "$$\n", 38 | "\n", 39 | "Find the optimal set of bundle goods to be consumed by comparing\n", 40 | "different combinations of the available bundles shown below.\n", 41 | "\n", 42 | "There are only three bundle goods on the market, so we\n", 43 | "can afford a brute force optimization algorithm implemented as a\n", 44 | "triple nested loop, with each level corresponding to one bundle good\n", 45 | "and looping from 0 to some reasonable number (think which number\n", 46 | "would be reasonable).\n", 47 | "\n", 48 | "Compute the optimal choice for budgets of 100, 200 and 300 price units.\n", 49 | "\n", 50 | "Use the starter code below. Each occurrence of **@@@** has to be replaced with appropriate code." 51 | ] 52 | }, 53 | { 54 | "cell_type": "code", 55 | "execution_count": null, 56 | "metadata": { 57 | "hide-output": false 58 | }, 59 | "outputs": [], 60 | "source": [ 61 | "# Available bundle goods\n", 62 | "a = bundle_good([2,0,1,3,1,1,0],10.50)\n", 63 | "b = bundle_good([0,5,0,4,2,2,2],15.36)\n", 64 | "c = bundle_good([1,0,1,2,0,5,4],12.72)\n", 65 | "market = [a,b,c]\n", 66 | "\n", 67 | "import math\n", 68 | "\n", 69 | "# utility function\n", 70 | "def u(x):\n", 71 | " '''Returns the utility of a bundle'''\n", 72 | " return @@@\n", 73 | "\n", 74 | "# optimization routine\n", 75 | "def optim(budget,util,market):\n", 76 | " '''Returns the optimal combination of goods at the market, given the budget'''\n", 77 | " nn = @@@ #heuristic for the maximum quantity to check\n", 78 | " # loop over all combination of three bundles to find max utility\n", 79 | " m = -float('inf') #initialize with negative infinity\n", 80 | " for i in range(nn):\n", 81 | " for j in range(nn):\n", 82 | " for k in range(nn):\n", 83 | " bnd = @@@ # combination of so many of each of the three bundled goods\n", 84 | " u = util(@@@)\n", 85 | " if bnd.price <= budget and m upper: # checked all divisors up to upper\n", 43 | " @@@\n", 44 | " i=0 # check for divisibility starting from the first element of remaining list\n", 45 | " while i < len(primes): # until the end of the list (which changes length inside the loop)\n", 46 | " if primes[i] @@@ divisor and primes[i] @@@ divisor == 0:\n", 47 | " # remove divisible, except the divisor itself\n", 48 | " primes.remove(primes[i]) # remove, next is with the same index\n", 49 | " else:\n", 50 | " i += 1 # skip to go to next element\n", 51 | " if @@@: print(\"divisor %d:\"%divisor,primes)\n", 52 | " if @@@: print(\"Primes up to %d are:\"%upper,primes)\n", 53 | " return @@@" 54 | ] 55 | }, 56 | { 57 | "cell_type": "markdown", 58 | "metadata": {}, 59 | "source": [ 60 | "To make sure the function is running as it is supposed to, run the\n", 61 | "tests below and confirm that the output is as expected." 62 | ] 63 | }, 64 | { 65 | "cell_type": "code", 66 | "execution_count": null, 67 | "metadata": { 68 | "hide-output": false 69 | }, 70 | "outputs": [], 71 | "source": [ 72 | "eratosthenes(25,verbosity=True) #should print the steps of the algorithm" 73 | ] 74 | }, 75 | { 76 | "cell_type": "code", 77 | "execution_count": null, 78 | "metadata": { 79 | "hide-output": false 80 | }, 81 | "outputs": [], 82 | "source": [ 83 | "x = eratosthenes(5)\n", 84 | "print(x) #should print [2,3,5]" 85 | ] 86 | }, 87 | { 88 | "cell_type": "code", 89 | "execution_count": null, 90 | "metadata": { 91 | "hide-output": false 92 | }, 93 | "outputs": [], 94 | "source": [ 95 | "x = eratosthenes(2500)\n", 96 | "print('Number of primes up to 2500 is ',len(x)) #should print \"Number of primes up to 2500 is 368\"" 97 | ] 98 | }, 99 | { 100 | "cell_type": "markdown", 101 | "metadata": {}, 102 | "source": [ 103 | "## Task 2\n", 104 | "\n", 105 | "Use the code snippet from lecture video 9 to collect data on the runtime of the *eratosthenes()* as\n", 106 | "a function of the upper bound.\n", 107 | "Compute 25 runtime data points using the following sequence for the upper bound: 5, 10, 15, etc,\n", 108 | "and using 1000 functional calls to compute the average.\n", 109 | "\n", 110 | "Make a conjecture on the computational complexity of this algorithm." 111 | ] 112 | }, 113 | { 114 | "cell_type": "code", 115 | "execution_count": null, 116 | "metadata": { 117 | "hide-output": false 118 | }, 119 | "outputs": [], 120 | "source": [ 121 | "import matplotlib.pyplot as plt\n", 122 | "%matplotlib inline\n", 123 | "plt.rcParams['figure.figsize'] = [12, 8]\n", 124 | "\n", 125 | "N = @@@\n", 126 | "n,x = [0,] @@@ N, [0,] @@@ N # lists to accumulate the data\n", 127 | "for i,k in [(i,@@@) for i in range(N)]:\n", 128 | " n[i] = k\n", 129 | " t = @@@\n", 130 | " x[i] = @@@\n", 131 | "\n", 132 | "plt.plot(n,x)\n", 133 | "plt.xlabel('upper bound')\n", 134 | "plt.ylabel('average run time, sec')\n", 135 | "plt.show()" 136 | ] 137 | }, 138 | { 139 | "cell_type": "markdown", 140 | "metadata": {}, 141 | "source": [ 142 | "## Task 3\n", 143 | "\n", 144 | "Copy your code from above and make the following improvements to the algorithm:\n", 145 | "\n", 146 | "1. Force divisors only be prime numbers themselves \n", 147 | "1. When checking for divisibility, start from the square of the divisor instead of checking each one (why can we do it this way?) \n", 148 | "1. Complete the algorithm when the starting point in previous step is above the upper bound \n", 149 | "\n", 150 | "\n", 151 | "Run the same tests and make sure it the results are identical to the first implementation of the algorithm." 152 | ] 153 | }, 154 | { 155 | "cell_type": "code", 156 | "execution_count": null, 157 | "metadata": { 158 | "hide-output": false 159 | }, 160 | "outputs": [], 161 | "source": [ 162 | "# Write your code here\n", 163 | "#" 164 | ] 165 | }, 166 | { 167 | "cell_type": "code", 168 | "execution_count": null, 169 | "metadata": { 170 | "hide-output": false 171 | }, 172 | "outputs": [], 173 | "source": [ 174 | "eratosthenes(25,verbosity=True) #should print the steps of the algorithm\n", 175 | "eratosthenes_better(25,verbosity=True)" 176 | ] 177 | }, 178 | { 179 | "cell_type": "code", 180 | "execution_count": null, 181 | "metadata": { 182 | "hide-output": false 183 | }, 184 | "outputs": [], 185 | "source": [ 186 | "x = eratosthenes(5)\n", 187 | "print(x) #should print [2,3,5]\n", 188 | "x = eratosthenes_better(5)\n", 189 | "print(x) #should print [2,3,5]" 190 | ] 191 | }, 192 | { 193 | "cell_type": "code", 194 | "execution_count": null, 195 | "metadata": { 196 | "hide-output": false 197 | }, 198 | "outputs": [], 199 | "source": [ 200 | "x = eratosthenes(2500)\n", 201 | "print('Number of primes up to 2500 is ',len(x)) #should print \"Number of primes up to 2500 is 368\"\n", 202 | "x = eratosthenes_better(2500)\n", 203 | "print('Number of primes up to 2500 is ',len(x)) #should print \"Number of primes up to 2500 is 368\"" 204 | ] 205 | }, 206 | { 207 | "cell_type": "markdown", 208 | "metadata": {}, 209 | "source": [ 210 | "## Task 4\n", 211 | "\n", 212 | "Repeat the run time analysis for the improved version of the algorithm, and plot the graph for the two implementations side by side." 213 | ] 214 | }, 215 | { 216 | "cell_type": "code", 217 | "execution_count": null, 218 | "metadata": { 219 | "hide-output": false 220 | }, 221 | "outputs": [], 222 | "source": [ 223 | "import matplotlib.pyplot as plt\n", 224 | "%matplotlib inline\n", 225 | "plt.rcParams['figure.figsize'] = [12, 8]\n", 226 | "\n", 227 | "N = @@@\n", 228 | "n,x,y = @@@ # lists to accumulate the data\n", 229 | "for i,k in [(i,@@@) for i in range(N)]:\n", 230 | " n[i] = @@@\n", 231 | " t = @@@\n", 232 | " x[i] = @@@ # run time of original algorithm\n", 233 | " t = @@@\n", 234 | " y[i] = @@@ # run time of improved algorithm\n", 235 | "\n", 236 | "plt.plot(n,x,label='Original algorithm')\n", 237 | "plt.plot(n,y,label='Improved algorithm')\n", 238 | "plt.xlabel('upper bound')\n", 239 | "plt.ylabel('average run time, sec')\n", 240 | "plt.legend()\n", 241 | "plt.show()" 242 | ] 243 | }, 244 | { 245 | "cell_type": "markdown", 246 | "metadata": {}, 247 | "source": [ 248 | "Note, however, that 1 is not a prime!\n", 249 | "[https://www.youtube.com/watch?v=IQofiPqhJ_s](https://www.youtube.com/watch?v=IQofiPqhJ_s)" 250 | ] 251 | } 252 | ], 253 | "metadata": { 254 | "date": 1627475014.509599, 255 | "filename": "exercise05.rst", 256 | "kernelspec": { 257 | "display_name": "Python", 258 | "language": "python3", 259 | "name": "python3" 260 | }, 261 | "title": "Weekly exercise 5: Improving Sieves of Eratosthenes algorithm" 262 | }, 263 | "nbformat": 4, 264 | "nbformat_minor": 4 265 | } -------------------------------------------------------------------------------- /exercise06.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Weekly exercise 6: Simple NumPy exercises\n", 8 | "\n", 9 | "In this task you are practicing using NumPy in several applications." 10 | ] 11 | }, 12 | { 13 | "cell_type": "markdown", 14 | "metadata": {}, 15 | "source": [ 16 | "## Task 1. Power of a matrix\n", 17 | "\n", 18 | "Write a function that would take in a matrix and a non-negative integer,\n", 19 | "check for that matrix is square, and return the power of the matrix computed through\n", 20 | "successive multiplication." 21 | ] 22 | }, 23 | { 24 | "cell_type": "code", 25 | "execution_count": null, 26 | "metadata": { 27 | "hide-output": false 28 | }, 29 | "outputs": [], 30 | "source": [ 31 | "import numpy as np\n", 32 | "\n", 33 | "def matrix_power(mtrx,n=1):\n", 34 | " # Write your code here\n", 35 | " pass\n", 36 | "\n", 37 | "A = np.array([[1,2,0],[0,2,3],[1,1,5]])\n", 38 | "print(matrix_power(A))" 39 | ] 40 | }, 41 | { 42 | "cell_type": "markdown", 43 | "metadata": {}, 44 | "source": [ 45 | "Here are the tests to pass for your code (which are referred to as *unit tests*)" 46 | ] 47 | }, 48 | { 49 | "cell_type": "code", 50 | "execution_count": null, 51 | "metadata": { 52 | "hide-output": false 53 | }, 54 | "outputs": [], 55 | "source": [ 56 | "# Test the code above\n", 57 | "\n", 58 | "A = np.array([[1,2,0],[0,2,3],[1,1,5]])\n", 59 | "B = [[355,614,1806],[903,1565,4533],[1210,2113,6098]]\n", 60 | "eq=np.equal(matrix_power(A,5),B)\n", 61 | "if eq.all():\n", 62 | " print('Test 1 passed')\n", 63 | "else:\n", 64 | " print('Test 1 FAIL')\n", 65 | "\n", 66 | "\n", 67 | "A = [[1,2,0],[0,2,3],[1,1,5]]\n", 68 | "B = [[355,614,1806],[903,1565,4533],[1210,2113,6098]]\n", 69 | "eq=np.equal(matrix_power(A,5),B)\n", 70 | "if eq.all():\n", 71 | " print('Test 2 passed')\n", 72 | "else:\n", 73 | " print('Test 2 FAIL')\n", 74 | "\n", 75 | "\n", 76 | "try:\n", 77 | " matrix_power([1],4.5)\n", 78 | "except TypeError:\n", 79 | " print('Test 3 passed')\n", 80 | "except:\n", 81 | " print('Test 3 FAIL')\n", 82 | "else:\n", 83 | " print('Test 3 FAIL')\n", 84 | "\n", 85 | "try:\n", 86 | " matrix_power([1],-5)\n", 87 | "except ValueError:\n", 88 | " print('Test 4 passed')\n", 89 | "except:\n", 90 | " print('Test 4 FAIL')\n", 91 | "else:\n", 92 | " print('Test 4 FAIL')" 93 | ] 94 | }, 95 | { 96 | "cell_type": "markdown", 97 | "metadata": {}, 98 | "source": [ 99 | "## Task 2. Autoregressive model in matrix form\n", 100 | "\n", 101 | "Consider the AR(1) model\n", 102 | "\n", 103 | "$$\n", 104 | "y_t = a y_{t-1} + \\varepsilon, \\; \\varepsilon \\sim N(0, 1).\n", 105 | "$$\n", 106 | "\n", 107 | "We can represent it in the form\n", 108 | "\n", 109 | "$$\n", 110 | "Ay = \\varepsilon \\quad \\quad \\varepsilon \\sim N(0, 1)\n", 111 | "$$\n", 112 | "\n", 113 | "where $ A $ is\n", 114 | "\n", 115 | "$$\n", 116 | "A = \\begin{bmatrix} 1 & 0 & \\cdots & 0 & 0 \\cr\n", 117 | " -a & 1 & \\cdots & 0 & 0 \\cr\n", 118 | " \\vdots & \\vdots & \\cdots & \\vdots & \\vdots \\cr\n", 119 | " \\vdots & \\vdots & \\cdots & 1 & 0 \\cr\n", 120 | " 0 & 0 & \\cdots & -a & 1 \\end{bmatrix}\n", 121 | "$$\n", 122 | "\n", 123 | "and $ y $ and $ \\varepsilon $ are $ (T x 1) $ vectors\n", 124 | "\n", 125 | "Generate an AR(1) series with $ T=500 $ and $ \\alpha = 0.9 $\n", 126 | "using matrix algebra, and make a plot of $ y_t $.\n", 127 | "\n", 128 | "Hint: use NumPy.eye() with additional arguments." 129 | ] 130 | }, 131 | { 132 | "cell_type": "code", 133 | "execution_count": null, 134 | "metadata": { 135 | "hide-output": false 136 | }, 137 | "outputs": [], 138 | "source": [ 139 | "# replace @@@ by your code\n", 140 | "import numpy as np\n", 141 | "\n", 142 | "T = @@@\n", 143 | "α = @@@\n", 144 | "ɛ = np.random.randn(T)\n", 145 | "A = @@@\n", 146 | "y = @@@\n", 147 | "\n", 148 | "import matplotlib.pyplot as plt\n", 149 | "@@@" 150 | ] 151 | } 152 | ], 153 | "metadata": { 154 | "date": 1632755196.273495, 155 | "filename": "exercise06.rst", 156 | "kernelspec": { 157 | "display_name": "Python", 158 | "language": "python3", 159 | "name": "python3" 160 | }, 161 | "title": "Weekly exercise 6: Simple NumPy exercises" 162 | }, 163 | "nbformat": 4, 164 | "nbformat_minor": 4 165 | } -------------------------------------------------------------------------------- /exercise07.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Weekly exercise 7: Simple Pandas exercises\n", 8 | "\n", 9 | "In this exercise you will analyze some data on occupations." 10 | ] 11 | }, 12 | { 13 | "cell_type": "code", 14 | "execution_count": null, 15 | "metadata": { 16 | "hide-output": false 17 | }, 18 | "outputs": [], 19 | "source": [ 20 | "import pandas as pd" 21 | ] 22 | }, 23 | { 24 | "cell_type": "markdown", 25 | "metadata": {}, 26 | "source": [ 27 | "## Task 1\n", 28 | "\n", 29 | "- Import the data from [https://raw.githubusercontent.com/justmarkham/DAT8/master/data/u.user](https://raw.githubusercontent.com/justmarkham/DAT8/master/data/u.user) \n", 30 | "- Assign it to a variable called `users` \n", 31 | "- Output the number of variables and the number of observations \n", 32 | "- List the variables \n", 33 | "- To take a first look at the data output the first 15 observations " 34 | ] 35 | }, 36 | { 37 | "cell_type": "code", 38 | "execution_count": null, 39 | "metadata": { 40 | "hide-output": false 41 | }, 42 | "outputs": [], 43 | "source": [ 44 | "# write your code here" 45 | ] 46 | }, 47 | { 48 | "cell_type": "markdown", 49 | "metadata": {}, 50 | "source": [ 51 | "## Task 2\n", 52 | "\n", 53 | "Compute the mean age per occupation" 54 | ] 55 | }, 56 | { 57 | "cell_type": "code", 58 | "execution_count": null, 59 | "metadata": { 60 | "hide-output": false 61 | }, 62 | "outputs": [], 63 | "source": [ 64 | "# write your code here" 65 | ] 66 | }, 67 | { 68 | "cell_type": "markdown", 69 | "metadata": {}, 70 | "source": [ 71 | "## Task 3\n", 72 | "\n", 73 | "Compute the female ratio per occupation and sort it from the most to the least\n", 74 | "\n", 75 | "Hint: write a function and use *apply* method to convert M/F symbols to integers, if needed." 76 | ] 77 | }, 78 | { 79 | "cell_type": "code", 80 | "execution_count": null, 81 | "metadata": { 82 | "hide-output": false 83 | }, 84 | "outputs": [], 85 | "source": [ 86 | "# write your code here" 87 | ] 88 | }, 89 | { 90 | "cell_type": "markdown", 91 | "metadata": {}, 92 | "source": [ 93 | "## Task 4\n", 94 | "\n", 95 | "For each occupation, calculate the minimum and maximum ages" 96 | ] 97 | }, 98 | { 99 | "cell_type": "code", 100 | "execution_count": null, 101 | "metadata": { 102 | "hide-output": false 103 | }, 104 | "outputs": [], 105 | "source": [ 106 | "# write your code here" 107 | ] 108 | }, 109 | { 110 | "cell_type": "markdown", 111 | "metadata": {}, 112 | "source": [ 113 | "## Task 5\n", 114 | "\n", 115 | "For each combination of occupation and gender, calculate the mean age" 116 | ] 117 | }, 118 | { 119 | "cell_type": "code", 120 | "execution_count": null, 121 | "metadata": { 122 | "hide-output": false 123 | }, 124 | "outputs": [], 125 | "source": [ 126 | "# write your code here" 127 | ] 128 | }, 129 | { 130 | "cell_type": "markdown", 131 | "metadata": {}, 132 | "source": [ 133 | "## Task 6\n", 134 | "\n", 135 | "For each occupation present the percentage of women and men\n", 136 | "\n", 137 | "Hint: you may find useful functions agg() and div()" 138 | ] 139 | }, 140 | { 141 | "cell_type": "code", 142 | "execution_count": null, 143 | "metadata": { 144 | "hide-output": false 145 | }, 146 | "outputs": [], 147 | "source": [ 148 | "# write your code here" 149 | ] 150 | }, 151 | { 152 | "cell_type": "markdown", 153 | "metadata": {}, 154 | "source": [ 155 | "Special thanks to [https://github.com/justmarkham](https://github.com/justmarkham) for sharing the dataset and materials." 156 | ] 157 | } 158 | ], 159 | "metadata": { 160 | "date": 1632755196.289502, 161 | "filename": "exercise07.rst", 162 | "kernelspec": { 163 | "display_name": "Python", 164 | "language": "python3", 165 | "name": "python3" 166 | }, 167 | "title": "Weekly exercise 7: Simple Pandas exercises" 168 | }, 169 | "nbformat": 4, 170 | "nbformat_minor": 4 171 | } -------------------------------------------------------------------------------- /exercise08.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Weekly exercise 8: Simple Matplotlib exercises\n", 8 | "\n", 9 | "Follow the compulsory QuantEcon DataScience tutorial at\n", 10 | "[https://datascience.quantecon.org/applications/visualization_rules.html](https://datascience.quantecon.org/applications/visualization_rules.html)" 11 | ] 12 | }, 13 | { 14 | "cell_type": "markdown", 15 | "metadata": {}, 16 | "source": [ 17 | "## Task 1\n", 18 | "\n", 19 | "Import the necessary libraries" 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": null, 25 | "metadata": { 26 | "hide-output": false 27 | }, 28 | "outputs": [], 29 | "source": [ 30 | "# hint: we need pd and plt\n", 31 | "@@@\n", 32 | "\n", 33 | "# print the graphs in the notebook\n", 34 | "%matplotlib inline" 35 | ] 36 | }, 37 | { 38 | "cell_type": "markdown", 39 | "metadata": {}, 40 | "source": [ 41 | "## Task 2\n", 42 | "\n", 43 | "Import the dataset from [https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/07_Visualization/Tips/tips.csv](https://raw.githubusercontent.com/guipsamora/pandas_exercises/master/07_Visualization/Tips/tips.csv)\n", 44 | "\n", 45 | "Assign it to a variable called tips\n", 46 | "\n", 47 | "Take the first look at the dataset" 48 | ] 49 | }, 50 | { 51 | "cell_type": "code", 52 | "execution_count": null, 53 | "metadata": { 54 | "hide-output": false 55 | }, 56 | "outputs": [], 57 | "source": [ 58 | "# write your code here" 59 | ] 60 | }, 61 | { 62 | "cell_type": "markdown", 63 | "metadata": {}, 64 | "source": [ 65 | "## Task 3\n", 66 | "\n", 67 | "Delete the Unnamed 0 column" 68 | ] 69 | }, 70 | { 71 | "cell_type": "code", 72 | "execution_count": null, 73 | "metadata": { 74 | "hide-output": false 75 | }, 76 | "outputs": [], 77 | "source": [ 78 | "# write your code here" 79 | ] 80 | }, 81 | { 82 | "cell_type": "markdown", 83 | "metadata": {}, 84 | "source": [ 85 | "## Task 4\n", 86 | "\n", 87 | "Plot the total_bill column histogram:\n", 88 | "\n", 89 | "- create the histogram plot object \n", 90 | "- set axes labels and plot title \n", 91 | "\n", 92 | "\n", 93 | "Follow [https://matplotlib.org/gallery/pyplots/pyplot_text.html#sphx-glr-gallery-pyplots-pyplot-text-py](https://matplotlib.org/gallery/pyplots/pyplot_text.html#sphx-glr-gallery-pyplots-pyplot-text-py)" 94 | ] 95 | }, 96 | { 97 | "cell_type": "code", 98 | "execution_count": null, 99 | "metadata": { 100 | "hide-output": false 101 | }, 102 | "outputs": [], 103 | "source": [ 104 | "# write your code here" 105 | ] 106 | }, 107 | { 108 | "cell_type": "markdown", 109 | "metadata": {}, 110 | "source": [ 111 | "## Task 5\n", 112 | "\n", 113 | "Create a scatter plot presenting the relationship between total_bill and tip,\n", 114 | "using one function." 115 | ] 116 | }, 117 | { 118 | "cell_type": "code", 119 | "execution_count": null, 120 | "metadata": { 121 | "hide-output": false 122 | }, 123 | "outputs": [], 124 | "source": [ 125 | "# write your code here" 126 | ] 127 | }, 128 | { 129 | "cell_type": "markdown", 130 | "metadata": {}, 131 | "source": [ 132 | "## Task 6\n", 133 | "\n", 134 | "Create one 3 by 3 image with the relationship of total_bill, tip and size.\n", 135 | "Again, use just one function." 136 | ] 137 | }, 138 | { 139 | "cell_type": "code", 140 | "execution_count": null, 141 | "metadata": { 142 | "hide-output": false 143 | }, 144 | "outputs": [], 145 | "source": [ 146 | "# write your code here" 147 | ] 148 | }, 149 | { 150 | "cell_type": "markdown", 151 | "metadata": {}, 152 | "source": [ 153 | "## Task 7\n", 154 | "\n", 155 | "Present the relationship between days and total_bill value.\n", 156 | "Use `jitter = True` argument for visual appeal." 157 | ] 158 | }, 159 | { 160 | "cell_type": "code", 161 | "execution_count": null, 162 | "metadata": { 163 | "hide-output": false 164 | }, 165 | "outputs": [], 166 | "source": [ 167 | "# write your code here" 168 | ] 169 | }, 170 | { 171 | "cell_type": "markdown", 172 | "metadata": {}, 173 | "source": [ 174 | "## Task 8\n", 175 | "\n", 176 | "Create two scatterplot graphs, one for Male and another for Female, presenting the total_bill value and tip relationship, differing by smoker or non-smoker. Add a legend." 177 | ] 178 | }, 179 | { 180 | "cell_type": "code", 181 | "execution_count": null, 182 | "metadata": { 183 | "hide-output": false 184 | }, 185 | "outputs": [], 186 | "source": [ 187 | "# write your code here" 188 | ] 189 | } 190 | ], 191 | "metadata": { 192 | "date": 1627475014.55644, 193 | "filename": "exercise08.rst", 194 | "kernelspec": { 195 | "display_name": "Python 3", 196 | "language": "python", 197 | "name": "python3" 198 | }, 199 | "language_info": { 200 | "codemirror_mode": { 201 | "name": "ipython", 202 | "version": 3 203 | }, 204 | "file_extension": ".py", 205 | "mimetype": "text/x-python", 206 | "name": "python", 207 | "nbconvert_exporter": "python", 208 | "pygments_lexer": "ipython3", 209 | "version": "3.7.6" 210 | }, 211 | "title": "Weekly exercise 8: Simple Matplotlib exercises" 212 | }, 213 | "nbformat": 4, 214 | "nbformat_minor": 4 215 | } 216 | -------------------------------------------------------------------------------- /exercise09.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Weekly exercise 9: Finding the intersection of line segments\n", 8 | "\n", 9 | "Given two line segments in $ \\mathbb{R}^2 $ with endpoint\n", 10 | "coordinates as\n", 11 | "\n", 12 | "$$\n", 13 | "(x^1_1,y^1_1),(x^1_2,y^1_2) \\text{ and } (x^2_1,y^2_1),(x^2_2,y^2_2),\n", 14 | "$$\n", 15 | "\n", 16 | "where superscripts indicate the segment, subscripts indicate beginning\n", 17 | "and end of the line, find whether the segments intersect, and if so,\n", 18 | "what is the intersection point." 19 | ] 20 | }, 21 | { 22 | "cell_type": "markdown", 23 | "metadata": {}, 24 | "source": [ 25 | "## Method\n", 26 | "\n", 27 | "Let intersection be given by $ (x_0,y_0) $, and introduce two more\n", 28 | "variables $ t_1 $ and $ t_2 $ that equal to the distance from\n", 29 | "the starting points $ (x^1_1,y^1_1) $ and $ (x^2_1,y^2_1) $ to\n", 30 | "the intersection point, relative to the corresponding segment lengths.\n", 31 | "Then we can write the following system of equations\n", 32 | "\n", 33 | "$$\n", 34 | "\\begin{eqnarray*}\n", 35 | "(x^1_2 - x^1_1) \\cdot t_1 &=& x_0 - x^1_1 \\\\\n", 36 | "(x^2_2 - x^2_1) \\cdot t_2 &=& x_0 - x^2_1 \\\\\n", 37 | "(y^1_2 - y^1_1) \\cdot t_1 &=& y_0 - y^1_1 \\\\\n", 38 | "(y^2_2 - y^2_1) \\cdot t_2 &=& y_0 - y^2_1 \\\\\n", 39 | "\\end{eqnarray*}\n", 40 | "$$\n", 41 | "\n", 42 | "In matrix notation $ Az=b $ where\n", 43 | "\n", 44 | "$$\n", 45 | "A=\n", 46 | "\\begin{pmatrix}\n", 47 | "x^1_2 - x^1_1 & 0 & -1 & 0 \\\\\n", 48 | "0 & x^2_2 - x^2_1 & -1 & 0 \\\\\n", 49 | "y^1_2 - y^1_1 & 0 & 0 & -1 \\\\\n", 50 | "0 & y^2_2 - y^2_1 & 0 & -1 \\\\\n", 51 | "\\end{pmatrix},\\;\\;\n", 52 | "b=\\begin{pmatrix}\n", 53 | "-x^1_1\\\\\n", 54 | "-x^2_1\\\\\n", 55 | "-y^1_1\\\\\n", 56 | "-y^2_1\\\\\n", 57 | "\\end{pmatrix},\\;\\;\n", 58 | "z=(t_1,t_2,x_0,y_0)\n", 59 | "$$\n", 60 | "\n", 61 | "After solving the system, we can check $ t_1 $ and $ t_2 $\n", 62 | "\n", 63 | "- If both belong to $ [0,1] $, the intersection point exists and is given by the computed $ (x_0,y_0) $ \n", 64 | "- Otherwise, it the segments do not intersect " 65 | ] 66 | }, 67 | { 68 | "cell_type": "markdown", 69 | "metadata": {}, 70 | "source": [ 71 | "## Task\n", 72 | "\n", 73 | "Write a function that takes the coordinates of the two line segments as input, and outputs the coordinates of the intersection point, if it exists, and None otherwise.\n", 74 | "\n", 75 | "Write several tests to check that your function works correctly in both cases when lines do and do not intersect." 76 | ] 77 | }, 78 | { 79 | "cell_type": "code", 80 | "execution_count": null, 81 | "metadata": { 82 | "hide-output": false 83 | }, 84 | "outputs": [], 85 | "source": [ 86 | "# your code here" 87 | ] 88 | } 89 | ], 90 | "metadata": { 91 | "date": 1627475014.565591, 92 | "filename": "exercise09.rst", 93 | "kernelspec": { 94 | "display_name": "Python 3", 95 | "language": "python", 96 | "name": "python3" 97 | }, 98 | "language_info": { 99 | "codemirror_mode": { 100 | "name": "ipython", 101 | "version": 3 102 | }, 103 | "file_extension": ".py", 104 | "mimetype": "text/x-python", 105 | "name": "python", 106 | "nbconvert_exporter": "python", 107 | "pygments_lexer": "ipython3", 108 | "version": "3.7.6" 109 | }, 110 | "title": "Weekly exercise 9: Finding the intersection of line segments" 111 | }, 112 | "nbformat": 4, 113 | "nbformat_minor": 4 114 | } 115 | -------------------------------------------------------------------------------- /exercise10.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Weekly exercise 10: Markov employment transitions\n", 8 | "\n", 9 | "Consider a worker who, at any given time can be either\n", 10 | "\n", 11 | "- employed full time (x = 2) \n", 12 | "- employed part time (x = 1) \n", 13 | "- unemployed (x = 0) \n", 14 | "\n", 15 | "\n", 16 | "Assume that an unemployed worker finds a part time job with probability $ \\alpha $ and full time job with probability $ \\beta < \\alpha $.\n", 17 | "\n", 18 | "A full time worker may loose their job, or transfer to part time job, with probability $ \\gamma $.\n", 19 | "\n", 20 | "Further, a part time worker may loose their job, or finds a full time job, with probability $ \\delta $." 21 | ] 22 | }, 23 | { 24 | "cell_type": "markdown", 25 | "metadata": {}, 26 | "source": [ 27 | "## Tasks:\n", 28 | "\n", 29 | "1. Write a function that would return the transition probability matrix given the parameters $ (\\alpha,\\beta,\\gamma,\\delta) $ after making the appropriate checks \n", 30 | "1. Assume that initially half of the population has no job, while another half has a full time job. Simulate the distribution of employment states in the following 50 time periods. Use what you think are appropriate values of the parameters. \n", 31 | "1. Visualize the evolution of the employment states using an area plot \n", 32 | "1. Compute the stationary distribution of employment states. Verify that it coincides with the simulated invariant distribution. \n", 33 | "1. Consider an initially unemployed worker. Simulate employment states for this worker for $ N $ periods. Compute the fractions of time the worker is in each state, and make a line plot of the three of these fraction with N on the horizontal axis. Verify that the ergodicity of the invariant distribution. \n", 34 | "\n", 35 | "\n", 36 | "In your work, do not use other than standard scientific libraries (like NumPy and Pandas).\n", 37 | "The exercise is inspired by QuantEcon example on [https://python.quantecon.org/finite_markov.html](https://python.quantecon.org/finite_markov.html) which you may find helpful to go though." 38 | ] 39 | }, 40 | { 41 | "cell_type": "code", 42 | "execution_count": null, 43 | "metadata": { 44 | "hide-output": false 45 | }, 46 | "outputs": [], 47 | "source": [ 48 | "# your code here" 49 | ] 50 | } 51 | ], 52 | "metadata": { 53 | "date": 1627475014.571282, 54 | "filename": "exercise10.rst", 55 | "kernelspec": { 56 | "display_name": "Python", 57 | "language": "python3", 58 | "name": "python3" 59 | }, 60 | "title": "Weekly exercise 10: Markov employment transitions" 61 | }, 62 | "nbformat": 4, 63 | "nbformat_minor": 4 64 | } -------------------------------------------------------------------------------- /exercise11.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Weekly exercise 11: Inventory dynamics problem with stochastic demand\n", 8 | "\n", 9 | "Using bus engine replacement model as an analogy, in this exercise you’ll continue developing the inventory model from the first lecture on dynamic programming (video 27),\n", 10 | "and extend it to the infinite horizon case with stochastic demand." 11 | ] 12 | }, 13 | { 14 | "cell_type": "markdown", 15 | "metadata": {}, 16 | "source": [ 17 | "## Inventory dynamics model\n", 18 | "\n", 19 | "Recall the inventory management problem in discrete time and finite horizon $ t=0,\\dots,T $\n", 20 | "\n", 21 | "The notation is:\n", 22 | "\n", 23 | "- $ x_t\\ge 0 $ is inventory at period $ t $ \n", 24 | "- $ d_t\\ge 0 $ is *stochastic* demand at period $ t $ \n", 25 | "- $ q_t\\ge 0 $ is the order of new inventory \n", 26 | "- $ p $ is the profit per one unit of (supplied) good \n", 27 | "- $ c $ is the fixed cost of ordering any amount of new inventory \n", 28 | "- $ r $ is the cost of storing one unit of good \n", 29 | "\n", 30 | "\n", 31 | "The sales in period $ t $ are given by $ s_t = \\min\\{x_t,d_t\\} $.\n", 32 | "\n", 33 | "Inventory to be stored till next period is given by $ k_t = \\max\\{x_t-d_t,0\\} + q_t = x_{t+1} $.\n", 34 | "\n", 35 | "The profit in period $ t $ is given by\n", 36 | "\n", 37 | "$$\n", 38 | "\\begin{eqnarray}\n", 39 | "\\pi_t & = & p \\cdot \\text{sales}_t - r \\cdot x_{t+1} - c \\cdot (\\text{order made in period }t) \\\\\n", 40 | "& = & s_t p - k_t r - c \\mathbb{1}\\{q_t>0\\}\n", 41 | "\\end{eqnarray}\n", 42 | "$$\n", 43 | "\n", 44 | "Assuming all $ q_t \\ge 0 $, let $ \\sigma = \\{q_t\\}_{t=1,\\dots,T} $ denote a feasible inventory policy.\n", 45 | "\n", 46 | "If $ d_t $ is stochastic the policy becomes a function of the period $ t $ inventory $ x_t $.\n", 47 | "\n", 48 | "The expected profit maximizing problem is given by\n", 49 | "\n", 50 | "$$\n", 51 | "{\\max}_{\\sigma} \\mathbb{E}\\Big[ \\sum_{t=0}^{T} \\beta^t \\pi_t \\Big],\n", 52 | "$$\n", 53 | "\n", 54 | "where $ \\beta $ is discount factor." 55 | ] 56 | }, 57 | { 58 | "cell_type": "markdown", 59 | "metadata": {}, 60 | "source": [ 61 | "### Bellman equation for the problem\n", 62 | "\n", 63 | "$$\n", 64 | "\\begin{eqnarray}\n", 65 | "V(x_t,d_t) &=& \\max_{q_t \\ge 0} \\Big\\{ \\pi_t + \\beta \\mathbb{E}\\Big[ V\\big(x_{t+1} , d_{t+1} \\big) \\Big| x_t,d_t,q_t \\Big] \\Big\\} \\\\\n", 66 | "&=& \\max_{q_t \\ge 0} \\Big\\{ s_t p - k_t r - c \\mathbb{1}\\{q_t>0\\}\n", 67 | "+ \\beta \\mathbb{E}\\Big[ V\\big( k_t, d_{t+1} \\big) \\Big] \\Big\\}\n", 68 | "\\end{eqnarray}\n", 69 | "$$\n", 70 | "\n", 71 | "$$\n", 72 | "\\begin{eqnarray}\n", 73 | "s_t &=& \\min\\{x_t,d_t\\} \\\\\n", 74 | "k_t &=& \\max\\{x_t-d_t,0\\} + q_t\n", 75 | "\\end{eqnarray}\n", 76 | "$$\n", 77 | "\n", 78 | "The expectation in the Bellman equation is taken over the distribution of the next period demand $ d_{t+1} $, which according to the problem is independent of any other variables (idiosyncratic), thus the conditioning on $ (x_t,d_t,q_t) $ can be meaningfully dropped. Expectation can be written as an integral over the distribution of demand $ F(d) $.\n", 79 | "\n", 80 | "$$\n", 81 | "V(x_t,d_t)\n", 82 | "= \\max_{q_t \\ge 0} \\Big\\{ s_t p - k_t r - c \\mathbb{1}\\{q_t>0\\}\n", 83 | "+ \\beta \\int V\\big( k_t, d \\big) \\partial F(d) \\Big\\}\n", 84 | "$$" 85 | ] 86 | }, 87 | { 88 | "cell_type": "markdown", 89 | "metadata": {}, 90 | "source": [ 91 | "### Dropping the time subscripts\n", 92 | "\n", 93 | "Because we’ll be solving the problem in infinite horizon, the time subscripts can be dropped, and we can just have current period variables $ x,d,q,s,k $, and next period variables denoted by prime, i.e. $ x' $\n", 94 | "\n", 95 | "The Bellman equation is then\n", 96 | "\n", 97 | "$$\n", 98 | "\\begin{eqnarray}\n", 99 | "V(x,d) &=& \\max_{q \\ge 0} \\Big\\{ \\pi + \\beta \\mathbb{E}\\Big[ V\\big(x', d' \\big) \\Big| x,d,q \\Big] \\Big\\} \\\\\n", 100 | "&=& \\max_{q \\ge 0} \\Big\\{ s\\cdot p - k\\cdot r - c \\mathbb{1}\\{q>0\\}\n", 101 | "+ \\beta \\mathbb{E}\\Big[ V\\big( k, d' \\big) \\Big] \\Big\\}\n", 102 | "\\end{eqnarray}\n", 103 | "$$\n", 104 | "\n", 105 | "$$\n", 106 | "\\begin{eqnarray}\n", 107 | "s &=& \\min\\{x,d\\} \\\\\n", 108 | "k &=& \\max\\{x-d,0\\} + q\n", 109 | "\\end{eqnarray}\n", 110 | "$$" 111 | ] 112 | }, 113 | { 114 | "cell_type": "markdown", 115 | "metadata": {}, 116 | "source": [ 117 | "### Bellman equation in expected value function space\n", 118 | "\n", 119 | "Note that similar to the bus engine replacement model, the inventory model features random variable which distribution does not depend on the previous period variables (it is *idiosyncratic*).\n", 120 | "\n", 121 | "In this case it is possible to reduce the dimensionality of the fixed point problem by rewriting the Bellman operator in expected value function terms.\n", 122 | "\n", 123 | "$$\n", 124 | "EV(x') = \\mathbb{E}\\Big[ V\\big(x', d' \\big) \\Big| x,d,q \\Big] = \\mathbb{E}\\Big[ V\\big(x', d' \\big) \\Big],\n", 125 | "$$\n", 126 | "\n", 127 | "where the expectation is taken over the distribution of the next period demand $ d' $.\n", 128 | "The conditioning on $ x,d,q $ can be dropped exactly because $ d' $ is idiosyncratic.\n", 129 | "\n", 130 | "We can then write the Bellman equation as\n", 131 | "\n", 132 | "$$\n", 133 | "V(x,d) = \\max_{q \\ge 0} \\Big\\{ s\\cdot p - k\\cdot r - c \\mathbb{1}\\{q>0\\}\n", 134 | "+ \\beta EV(k) \\Big\\}\n", 135 | "$$\n", 136 | "\n", 137 | "$$\n", 138 | "V(x,d) = \\max_{q \\ge 0} \\Big\\{ p \\min\\{x,d\\} - r ( \\max\\{x-d,0\\} + q ) - c \\mathbb{1}\\{q>0\\}\n", 139 | "+ \\beta EV(\\max\\{x-d,0\\} + q) \\Big\\}\n", 140 | "$$\n", 141 | "\n", 142 | "Taking the expectation with respect to $ d $ on both sides, we get\n", 143 | "\n", 144 | "$$\n", 145 | "EV(x) = \\mathbb{E}\\Big[ \\max_{q \\ge 0} \\Big\\{ p \\min\\{x,d\\} - r ( \\max\\{x-d,0\\} + q ) - c \\mathbb{1}\\{q>0\\}\n", 146 | "+ \\beta EV(\\max\\{x-d,0\\} + q) \\Big\\} \\Big]\n", 147 | "$$\n", 148 | "\n", 149 | "By assumption the inventory is discrete, and so it is natural to assume that the demand is also represented as a discrete random variable. Then the expectation can be written as a sum weighted with\n", 150 | "the corresponding probabilities $ pr(d) $, as\n", 151 | "\n", 152 | "$$\n", 153 | "EV(x) = \\sum_{d} \\Big[ \\max_{q \\ge 0} \\Big\\{ p \\min\\{x,d\\} - r ( \\max\\{x-d,0\\} + q ) - c \\mathbb{1}\\{q>0\\}\n", 154 | "+ \\beta EV(\\max\\{x-d,0\\} + q) \\Big\\} \\Big] pr(d)\n", 155 | "$$\n", 156 | "\n", 157 | "This is functional equation in $ EV $ which is also a contraction mapping!" 158 | ] 159 | }, 160 | { 161 | "cell_type": "markdown", 162 | "metadata": {}, 163 | "source": [ 164 | "### Specification of stochastic demand\n", 165 | "\n", 166 | "Assume that $ d(t) $ is stochastic and follows geometric distribution with the support\n", 167 | "$ k \\in \\{0,1,2,\\dots\\} $ and corresponding probabilities $ P(k)=(1-p)^k p $, where $ p $ is a fixed parameter." 168 | ] 169 | }, 170 | { 171 | "cell_type": "markdown", 172 | "metadata": {}, 173 | "source": [ 174 | "### Tasks\n", 175 | "\n", 176 | "1. Copy the implementation of the inventory model from the lecture notebook (27) to serve the starter code \n", 177 | "1. Implement VFI solver for the infinite horizon stochastic inventory problem, similar to the Rust bus engine model \n", 178 | "1. Run several tests of the solver using parameter values you see fit \n", 179 | "1. Make nice plots to illustrate convergence of the value and the policy functions to the solution. " 180 | ] 181 | }, 182 | { 183 | "cell_type": "code", 184 | "execution_count": null, 185 | "metadata": { 186 | "hide-output": false 187 | }, 188 | "outputs": [], 189 | "source": [ 190 | "# your code here" 191 | ] 192 | } 193 | ], 194 | "metadata": { 195 | "date": 1632755196.305168, 196 | "filename": "exercise11.rst", 197 | "kernelspec": { 198 | "display_name": "Python", 199 | "language": "python3", 200 | "name": "python3" 201 | }, 202 | "title": "Weekly exercise 11: Inventory dynamics problem with stochastic demand" 203 | }, 204 | "nbformat": 4, 205 | "nbformat_minor": 4 206 | } -------------------------------------------------------------------------------- /exercise12.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Weekly exercise 12: Choosing interpolation method\n", 8 | "\n", 9 | "In this exercise you will check how different interpolation methods\n", 10 | "work with different functions, after writing some diagnostic functions." 11 | ] 12 | }, 13 | { 14 | "cell_type": "markdown", 15 | "metadata": {}, 16 | "source": [ 17 | "## Choosing the right interpolation method\n", 18 | "\n", 19 | "Review the code in the lecture notebook to refresh your memory about\n", 20 | "\n", 21 | "1. Linear interpolation \n", 22 | "1. Quadratic and cubic splines \n", 23 | "1. Polynomial interpolation \n", 24 | "\n", 25 | "\n", 26 | "Fix the interpolation window $ x \\in [0,25] $, the interpolation nodes\n", 27 | "as in the code below, and only change the interpolated function and\n", 28 | "interpolation scheme." 29 | ] 30 | }, 31 | { 32 | "cell_type": "code", 33 | "execution_count": null, 34 | "metadata": { 35 | "hide-output": false 36 | }, 37 | "outputs": [], 38 | "source": [ 39 | "import numpy as np\n", 40 | "import matplotlib.pyplot as plt\n", 41 | "%matplotlib inline\n", 42 | "from scipy import interpolate # Interpolation routines\n", 43 | "\n", 44 | "# fixed parts of the problem\n", 45 | "a,b = 0,25 # interval\n", 46 | "xd = np.linspace(a,b,1000) # dense grid for plotting\n", 47 | "np.random.seed(21234) # fix random number sequences\n", 48 | "nodes = np.sort(np.random.uniform(a,b,15)) # sorted random points" 49 | ] 50 | }, 51 | { 52 | "cell_type": "markdown", 53 | "metadata": {}, 54 | "source": [ 55 | "## Task 1. Measuring the accuracy\n", 56 | "\n", 57 | "Write a function to plot the true function and the interpolation function,\n", 58 | "and let it also return the measure of accuracy equal to the average square deviation\n", 59 | "between the two.\n", 60 | "\n", 61 | "More precisely, let two measures of accuracy be calculated: one calculated off\n", 62 | "all points within the initial interval, and the second only between the min and max\n", 63 | "nodes (so, the second one excludes the extrapolated points)." 64 | ] 65 | }, 66 | { 67 | "cell_type": "code", 68 | "execution_count": null, 69 | "metadata": { 70 | "hide-output": false 71 | }, 72 | "outputs": [], 73 | "source": [ 74 | "# write your code here\n", 75 | "# come up with a test of your own" 76 | ] 77 | }, 78 | { 79 | "cell_type": "markdown", 80 | "metadata": {}, 81 | "source": [ 82 | "## Task 2. Interpolating smooth function\n", 83 | "\n", 84 | "Compare the accuracy of all three schemes above to interpolate\n", 85 | "\n", 86 | "$$\n", 87 | "f(x) = \\exp(-x/10)\\sin(x/2)\n", 88 | "$$\n", 89 | "\n", 90 | "Hint: use *fill_value=”extrapolate”* option in *interp1d()* to allow for extrapolation\n", 91 | "\n", 92 | "Which interpolation scheme is most accurate?" 93 | ] 94 | }, 95 | { 96 | "cell_type": "code", 97 | "execution_count": null, 98 | "metadata": { 99 | "hide-output": false 100 | }, 101 | "outputs": [], 102 | "source": [ 103 | "# write your code here" 104 | ] 105 | }, 106 | { 107 | "cell_type": "markdown", 108 | "metadata": {}, 109 | "source": [ 110 | "## Task 3. Interpolating complex periodic function\n", 111 | "\n", 112 | "Compare the accuracy of all three schemes above to interpolate\n", 113 | "\n", 114 | "$$\n", 115 | "f(x) = x + \\exp(x/10)\\sin(x)\n", 116 | "$$\n", 117 | "\n", 118 | "Which interpolation scheme is most accurate?" 119 | ] 120 | }, 121 | { 122 | "cell_type": "code", 123 | "execution_count": null, 124 | "metadata": { 125 | "hide-output": false 126 | }, 127 | "outputs": [], 128 | "source": [ 129 | "# write your code here" 130 | ] 131 | }, 132 | { 133 | "cell_type": "markdown", 134 | "metadata": {}, 135 | "source": [ 136 | "## Task 4. Interpolating function with kinks\n", 137 | "\n", 138 | "Compare the accuracy of all three schemes above to interpolate\n", 139 | "\n", 140 | "$$\n", 141 | "f(x) = \\max \\big( x + \\exp(x/10)\\sin(3x/4); x + 5 + \\exp([x+5]/10)\\sin(3[x+5]/4) \\big)\n", 142 | "$$\n", 143 | "\n", 144 | "Which interpolation scheme is most accurate?" 145 | ] 146 | }, 147 | { 148 | "cell_type": "code", 149 | "execution_count": null, 150 | "metadata": { 151 | "hide-output": false 152 | }, 153 | "outputs": [], 154 | "source": [ 155 | "# write your code here" 156 | ] 157 | }, 158 | { 159 | "cell_type": "markdown", 160 | "metadata": {}, 161 | "source": [ 162 | "## Task 5. Interpolating discontinuous function\n", 163 | "\n", 164 | "Compare the accuracy of all three schemes above to interpolate\n", 165 | "\n", 166 | "$$\n", 167 | "f(x) = \\exp(-x/10)\\sin(x/2) + \\mathbb{1}\\{\\cos(x)>1/2\\}\n", 168 | "$$\n", 169 | "\n", 170 | "Which interpolation scheme is most accurate?" 171 | ] 172 | }, 173 | { 174 | "cell_type": "code", 175 | "execution_count": null, 176 | "metadata": { 177 | "hide-output": false 178 | }, 179 | "outputs": [], 180 | "source": [ 181 | "# write your code here" 182 | ] 183 | } 184 | ], 185 | "metadata": { 186 | "date": 1627475014.595328, 187 | "filename": "exercise12.rst", 188 | "kernelspec": { 189 | "display_name": "Python 3", 190 | "language": "python", 191 | "name": "python3" 192 | }, 193 | "language_info": { 194 | "codemirror_mode": { 195 | "name": "ipython", 196 | "version": 3 197 | }, 198 | "file_extension": ".py", 199 | "mimetype": "text/x-python", 200 | "name": "python", 201 | "nbconvert_exporter": "python", 202 | "pygments_lexer": "ipython3", 203 | "version": "3.7.6" 204 | }, 205 | "title": "Weekly exercise 12: Choosing interpolation method" 206 | }, 207 | "nbformat": 4, 208 | "nbformat_minor": 4 209 | } 210 | -------------------------------------------------------------------------------- /exercise13.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Weekly exercise 13: Numerical integration\n", 8 | "\n", 9 | "In this exercise you will compare several integration schemes for\n", 10 | "several different functions.\n", 11 | "\n", 12 | "Compute the following expressions:\n", 13 | "\n", 14 | "1. $ \\int_0^8 \\exp(-x/4) sin(x) dx $ \n", 15 | "1. $ \\int_0^8 \\big| \\exp(-x/4) sin(x) \\big| dx $ (similar to above but with the absolute value) \n", 16 | "1. $ E\\{ \\exp(-x/4) sin(x) \\} $, where $ x $ is normally distributed with parameters $ \\mu=0 $, $ \\sigma=1 $. \n", 17 | "\n", 18 | "\n", 19 | "For each use the following integration schemes:\n", 20 | "\n", 21 | "1. Monte Carlo integration \n", 22 | "1. Gauss-Legendre quadrature (for 1,2), or Gauss-Hermite quadrature (for 3) \n", 23 | "\n", 24 | "\n", 25 | "In each integration scheme start with a low number of grid points (Monte Carlo draws) and sequentially increase the number of point while computing the change in the result of calculation (reduction of the error).\n", 26 | "\n", 27 | "Plot these step-by-step changes in the integrals for each of the integration scheme applied for each of the expressions.\n", 28 | "\n", 29 | "Discuss which scheme is preferable in which case." 30 | ] 31 | }, 32 | { 33 | "cell_type": "code", 34 | "execution_count": null, 35 | "metadata": { 36 | "hide-output": false 37 | }, 38 | "outputs": [], 39 | "source": [ 40 | "# Your code here" 41 | ] 42 | }, 43 | { 44 | "cell_type": "markdown", 45 | "metadata": {}, 46 | "source": [ 47 | "## Gauss-Legendre change of variables\n", 48 | "\n", 49 | "- Change of variable $ y = \\tfrac{1}{4}x-1 $, so that $ dy = \\tfrac{1}{4} dx $ \n", 50 | "\n", 51 | "\n", 52 | "$$\n", 53 | "\\int_0^8 f(x) dx =\n", 54 | "\\int_{-1}^1 4 f(4y+4) dy\n", 55 | "\\approx \\sum_i 4 w_i f(4 q_i +4)\n", 56 | "$$\n", 57 | "\n", 58 | "- For convenience, could convert the the Gauss-Legendre quadrature notes and weights $ \\{q_i,w_i\\} $ to $ q'_i = 4 q_i +4 $ and $ w'_i = 4 w_i $ " 59 | ] 60 | }, 61 | { 62 | "cell_type": "markdown", 63 | "metadata": {}, 64 | "source": [ 65 | "## Gauss-Hermite change of variables\n", 66 | "\n", 67 | "- Expectation over normal distribution with $ \\mu=0 $, $ \\sigma=1 $ \n", 68 | "- Change of variable $ y = \\tfrac{x}{\\sqrt{2}} $, so that $ dy = \\tfrac{dx}{\\sqrt{2}} $ \n", 69 | "\n", 70 | "\n", 71 | "$$\n", 72 | "E\\{ f(x) \\} = \\int_{-\\infty}^\\infty f(x) \\frac{1}{\\sqrt{2\\pi}} e^{-\\tfrac{1}{2}x^2 } dx =\n", 73 | "\\int_{-\\infty}^\\infty \\frac{f\\left(\\sqrt{2} y\\right)}{\\sqrt{\\pi}} e^{-y^2 } dy\n", 74 | "\\approx \\sum_i \\frac{w_i}{\\sqrt{\\pi}} f\\left(\\sqrt{2} q_i \\right)\n", 75 | "$$\n", 76 | "\n", 77 | "- For convenience, convert the the Gauss-Legendre quadrature notes and weights $ \\{q_i,w_i\\} $ to $ q'_i = \\sqrt{2} q_i $ and $ w'_i = \\frac{w_i}{\\sqrt{\\pi}} $ " 78 | ] 79 | } 80 | ], 81 | "metadata": { 82 | "date": 1627475014.604309, 83 | "filename": "exercise13.rst", 84 | "kernelspec": { 85 | "display_name": "Python", 86 | "language": "python3", 87 | "name": "python3" 88 | }, 89 | "title": "Weekly exercise 13: Numerical integration" 90 | }, 91 | "nbformat": 4, 92 | "nbformat_minor": 4 93 | } -------------------------------------------------------------------------------- /exercise14.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Weekly exercise 14: Stochastic consumption-savings model in finite horizon\n", 8 | "\n", 9 | "In this exercise you continue building up the `deaton()` class by adding the finite horizon version of the model.\n", 10 | "\n", 11 | "Start by copying the `deaton()` class code from lecture notebook 36. Make the following modifications:\n", 12 | "\n", 13 | "- add an attribute horizon to the model which is set to ‘infinite’ by default, but can take numerical values fixing the number of periods in the model $ T $ \n", 14 | "- modify the `__repr__()` method to output whether the model is finite or infinite horizon \n", 15 | "- code up the backwards induction solver for the finite horizon version of the model in a separate method `solver_backwards_induction()` with the only argument callback function (but using horizon attribute for the maximum number of periods). See lecture notebook 27 for examples of backward induction solvers \n", 16 | "- modify the simulator method to default to the $ T $ set in the horizon attribute when it is not equal ‘infinite’ \n", 17 | "\n", 18 | "\n", 19 | "Run separate simulations of the model for a few values of parameters, and discuss their similarities and differences." 20 | ] 21 | }, 22 | { 23 | "cell_type": "code", 24 | "execution_count": null, 25 | "metadata": { 26 | "hide-output": false 27 | }, 28 | "outputs": [], 29 | "source": [ 30 | "# Your code here" 31 | ] 32 | }, 33 | { 34 | "cell_type": "code", 35 | "execution_count": null, 36 | "metadata": { 37 | "hide-output": false 38 | }, 39 | "outputs": [], 40 | "source": [ 41 | "m = deaton(ngrid=100,nchgrid=250,sigma=.2,R=1.05,beta=.975,nquad=10)\n", 42 | "m.horizon=12\n", 43 | "print(m)\n", 44 | "v,c = m.solve_plot(solver='vfi')\n", 45 | "sims = m.simulator(init_wealth=[1,2,3],T=5)" 46 | ] 47 | } 48 | ], 49 | "metadata": { 50 | "date": 1627475014.609771, 51 | "filename": "exercise14.rst", 52 | "kernelspec": { 53 | "display_name": "Python", 54 | "language": "python3", 55 | "name": "python3" 56 | }, 57 | "title": "Weekly exercise 14: Stochastic consumption-savings model in finite horizon" 58 | }, 59 | "nbformat": 4, 60 | "nbformat_minor": 4 61 | } -------------------------------------------------------------------------------- /exercise15.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Weekly exercise 16: Accuracy vs runtime trade-off in Deaton model.\n", 8 | "\n", 9 | "In this exercise you will compare the accuracy of several solution methods for the stochastic consumption-savings model.\n", 10 | "\n", 11 | "## Task 1\n", 12 | "\n", 13 | "Start by copying the code of `deaton` class from the video notebook 40." 14 | ] 15 | }, 16 | { 17 | "cell_type": "code", 18 | "execution_count": null, 19 | "metadata": { 20 | "hide-output": false 21 | }, 22 | "outputs": [], 23 | "source": [ 24 | " # paste the deaton class code here\n", 25 | " # alternatively (and this is a better option) create file deaton.py in the same directory, paste the code there, and include it using \"import * from deaton.py\" command" 26 | ] 27 | }, 28 | { 29 | "cell_type": "markdown", 30 | "metadata": {}, 31 | "source": [ 32 | "## Task 2\n", 33 | "\n", 34 | "Make sure the code from the lecture runs and produces the same output" 35 | ] 36 | }, 37 | { 38 | "cell_type": "code", 39 | "execution_count": null, 40 | "metadata": { 41 | "hide-output": false 42 | }, 43 | "outputs": [], 44 | "source": [ 45 | "m = deaton(ngrid=100,nchgrid=250,sigma=.5,nquad=10, bellman_type='continuous')\n", 46 | "print(m)\n", 47 | "v,c = m.solve_plot(solver='timeiter')\n", 48 | "m.accuracy(verbose=True)\n", 49 | "sims = m.simulator(init_wealth=m.Mbar*np.arange(15)/15,T=25,seed=2020)\n", 50 | "\n", 51 | "v,c = m.solve_plot(solver='vfi')\n", 52 | "m.accuracy(verbose=True)\n", 53 | "sims = m.simulator(init_wealth=m.Mbar*np.arange(15)/15,T=25,seed=2020)\n", 54 | "\n", 55 | "m.bellman_type='discretized'\n", 56 | "v,c = m.solve_plot(solver='vfi')\n", 57 | "m.accuracy(verbose=True)\n", 58 | "sims = m.simulator(init_wealth=m.Mbar*np.arange(15)/15,T=25,seed=2020)" 59 | ] 60 | }, 61 | { 62 | "cell_type": "markdown", 63 | "metadata": {}, 64 | "source": [ 65 | "## Task 3\n", 66 | "\n", 67 | "Consider the three solution methods above:\n", 68 | "\n", 69 | "- VFI with discretized choices \n", 70 | "- VFI with continuous choices \n", 71 | "- Time iterations \n", 72 | "\n", 73 | "\n", 74 | "Choose parametrization for the test model, compute the accuracy measure for each method.\n", 75 | "\n", 76 | "Then, by changing various (technical) parameters of the model, for each of the three methods, choose one parameter that influences the accuracy of that method the most.\n", 77 | "\n", 78 | "Finally, make a plot to visualize the trade-off between accuracy and run time. It should have run time on vertical axis and accuracy measure on the horizontal axis. Three curves\n", 79 | "should correspond to the three solution methods, and should be composed on the points obtained for different settings identified as important factors influencing the accuracy for each method.\n", 80 | "\n", 81 | "Make the plot look good and be easy to read." 82 | ] 83 | }, 84 | { 85 | "cell_type": "code", 86 | "execution_count": null, 87 | "metadata": { 88 | "hide-output": false 89 | }, 90 | "outputs": [], 91 | "source": [ 92 | "# Write your code here" 93 | ] 94 | } 95 | ], 96 | "metadata": { 97 | "date": 1627475014.616064, 98 | "filename": "exercise15.rst", 99 | "kernelspec": { 100 | "display_name": "Python", 101 | "language": "python3", 102 | "name": "python3" 103 | }, 104 | "title": "Weekly exercise 16: Accuracy vs runtime trade-off in Deaton model." 105 | }, 106 | "nbformat": 4, 107 | "nbformat_minor": 4 108 | } -------------------------------------------------------------------------------- /exercise16.ipynb: -------------------------------------------------------------------------------- 1 | { 2 | "cells": [ 3 | { 4 | "cell_type": "markdown", 5 | "metadata": {}, 6 | "source": [ 7 | "# Weekly exercise 16: Update on accuracy vs runtime trade-off in Deaton model.\n", 8 | "\n", 9 | "Repeat all of the tasks in Exercise 15, now including the EGM solution method in the `deaton` class." 10 | ] 11 | } 12 | ], 13 | "metadata": { 14 | "date": 1627475014.619636, 15 | "filename": "exercise16.rst", 16 | "kernelspec": { 17 | "display_name": "Python", 18 | "language": "python3", 19 | "name": "python3" 20 | }, 21 | "title": "Weekly exercise 16: Update on accuracy vs runtime trade-off in Deaton model." 22 | }, 23 | "nbformat": 4, 24 | "nbformat_minor": 4 25 | } -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | scipy 2 | matplotlib 3 | numpy 4 | pandas 5 | seaborn 6 | cycler 7 | 8 | 9 | --------------------------------------------------------------------------------