diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..4a50f37 --- /dev/null +++ b/.gitignore @@ -0,0 +1,5 @@ +*~ +*.o + +.sublime-project +.sublime-workspace \ No newline at end of file diff --git a/README.md b/README.md new file mode 100644 index 0000000..e5e4b2d --- /dev/null +++ b/README.md @@ -0,0 +1,11 @@ +### Names of the students in the group: +- Tristan Barjavel +- Théo Lemaire + +*Flavio Raschella* was also part of the group for the 3 first weeks, therefore he is included in the initial commits. + +### How to run the code for homework 1 (week 4): +- Open a terminal to the root of the repository +- Move to the appropriate subfolder: `$ cd work/week4/conjugate_gradient` +- To execute part 1: `$ python optimizer.py` +- To execute part 2: `$ python conjugate_gradient.py` diff --git a/SP4E 2018 - course plan.pdf b/SP4E 2018 - course plan.pdf new file mode 100644 index 0000000..dc4e15d Binary files /dev/null and b/SP4E 2018 - course plan.pdf differ diff --git a/SP4E18.sublime-project b/SP4E18.sublime-project new file mode 100644 index 0000000..543b76f --- /dev/null +++ b/SP4E18.sublime-project @@ -0,0 +1,31 @@ +{ + "build_systems": + [ + { + "file_regex": "^[ ]*File \"(...*?)\", line ([0-9]*)", + "name": "Anaconda Python Builder", + "selector": "source.python", + "shell_cmd": "\"C:\\ProgramData\\Anaconda3\\python.exe\" -u \"$file\"" + } + ], + "folders": + [ + { + "file_exclude_patterns": + [ + "*.sublime-workspace", + "*.pdf", + "*.png", + "*.sh", + "main", + "*.gitignore" + ], + "folder_exclude_patterns": + [ + "build" + ], + "path": "." + } + ], + "translate_tabs_to_spaces": true +} diff --git a/SP4E18.sublime-workspace b/SP4E18.sublime-workspace new file mode 100644 index 0000000..5203ba7 --- /dev/null +++ b/SP4E18.sublime-workspace @@ -0,0 +1,1408 @@ +{ + "auto_complete": + { + "selected_items": + [ + [ + "plot", + "plotSurface" + ], + [ + "inter", + "intersectSets" + ], + [ + "map2", + "map2Set" + ], + [ + "ia", + "I-algorithm\tinc" + ], + [ + "sta", + "stack_values" + ], + [ + "heap", + "heap_allocation" + ], + [ + "vae", + "values" + ], + [ + "es", + "else\t(ex1.cc)" + ], + [ + "tan", + "tanhx2" + ], + [ + "arg", + "argc" + ], + [ + "zoom", + "zoom_xbounds" + ], + [ + "get_xl", + "get_xticklabels\t(effvars.py)" + ], + [ + "F", + "False" + ], + [ + "plotEf", + "plotEffectiveCapacitance\t(effvars.py)" + ], + [ + "main", + "mainfig" + ], + [ + "Cm", + "Cmbounds" + ], + [ + "look", + "lookups2D" + ], + [ + "Fr", + "FRbounds" + ], + [ + "comp", + "comprates" + ], + [ + "1e3", + "1e-3" + ], + [ + "flul", + "full_fpaths\tparam" + ], + [ + "full", + "full_comprates" + ], + [ + "mu", + "mu_full_comptimes" + ], + [ + "read_", + "read_csv\tfunction" + ], + [ + "sonic_", + "sonic_comptimes" + ], + [ + "ind", + "index_col" + ], + [ + "plo", + "plotSpikingMetrics\tfunction" + ], + [ + "lo", + "logscale" + ], + [ + "cool", + "colors_dict" + ], + [ + "Dc", + "DCs" + ], + [ + "spike", + "spikeamp" + ], + [ + "metri", + "metrics_dict" + ], + [ + "color", + "colors" + ], + [ + "sonci", + "sonic_metrics" + ], + [ + "fre", + "frequency\t(comp_spikemetrics_CW_vs_frequency.py)" + ], + [ + "am", + "amplitudes" + ], + [ + "upd", + "updated_queue" + ], + [ + "fp", + "fpaths" + ], + [ + "cre", + "createSimQueue\tfunction" + ], + [ + "empt", + "empty_like\t(fig3.py)" + ], + [ + "fig", + "figset" + ], + [ + "in", + "inputdir" + ], + [ + "CW", + "CW_sonic_fpaths" + ], + [ + "plotC", + "plotComp" + ], + [ + "son", + "sonic" + ], + [ + "sonic", + "sonic_metrics" + ], + [ + "toff", + "toffset" + ], + [ + "AS", + "ASTIM_filecode\tfunction" + ], + [ + "titration", + "titration_file" + ], + [ + "load", + "loads\tfunction" + ], + [ + "jon", + "json" + ], + [ + "neu", + "neurons" + ], + [ + "Ath", + "Athrs_sparse" + ], + [ + "DC", + "DCs_sparse" + ], + [ + "font", + "fontsize=fs" + ], + [ + "get", + "get" + ], + [ + "linewidth", + "linewidth=0.5" + ], + [ + "set_", + "set_yticks" + ], + [ + "Cort", + "CorticalLTS" + ], + [ + "cm2", + "cm2inch" + ], + [ + "rgxp", + "rgxp_mech" + ], + [ + "fra", + "frameon\t(pltutils.py)" + ], + [ + "actmap_fil", + "actmap_filename" + ], + [ + "Neuron", + "NeuronalBilayerSonophore\tclass" + ], + [ + "sele", + "selectDirDialog" + ], + [ + "Arg", + "ArgumentParser\tclass" + ], + [ + "mesh", + "meshedges" + ], + [ + "FR", + "FR_bounds\tstatement" + ], + [ + "FR_", + "FR_scale" + ], + [ + "input", + "inputdir" + ], + [ + "Neur", + "NeuronalBilayerSonophore\t(nbls.py)" + ], + [ + "im", + "import" + ], + [ + "getLo", + "getLookups2D" + ], + [ + "MECH", + "MECH_filecode" + ], + [ + "ES", + "ESTIM_filecode" + ], + [ + "el", + "elec" + ], + [ + "none", + "None\tkeyword" + ], + [ + "output", + "outputs" + ], + [ + "lookups", + "lookups4D" + ], + [ + "lok", + "lookups" + ], + [ + "pl", + "plt" + ], + [ + "Sav", + "SaveFileDialog" + ], + [ + "Save", + "SaveFigDialog" + ], + [ + "MEC", + "MECH_title" + ], + [ + "pkl", + "pkl_filepath" + ], + [ + "ge", + "getNeuronLookupsFile\tfunction" + ], + [ + "Lenn", + "LennardJones\t(bls.py)" + ], + [ + "In", + "Intensity2Pressure" + ], + [ + "out", + "outdir" + ], + [ + "dat", + "date_str" + ], + [ + "Bila", + "BilayerSonophore" + ], + [ + "tco", + "tcomp\t(utils.py)" + ], + [ + "log", + "logentry" + ], + [ + "filen", + "filename" + ], + [ + "sheet", + "sheetname" + ], + [ + "default", + "defaults" + ], + [ + "ne", + "neurons" + ], + [ + "neuron", + "neuron_str" + ], + [ + "nr", + "neurons\tstatement" + ], + [ + "Th", + "ThalamicRE\tclass" + ], + [ + "Py", + "PySONIC" + ], + [ + "pos", + "postpro\tmodule" + ], + [ + "__", + "__main__" + ], + [ + "Neu", + "NeuronalBilayerSonophore\t(ASTIM.py)" + ], + [ + "simul", + "simulate" + ], + [ + "sim", + "simulate\t(sonic.py)" + ], + [ + "neurons", + "neurons_str" + ], + [ + "eff", + "eff_coeffs" + ], + [ + "no", + "nofreq_queue" + ], + [ + "method", + "method_str" + ], + [ + "Sonci", + "SonicNeuron\t(sonic.py)" + ], + [ + "stim", + "stim_params\tparam" + ], + [ + "run", + "runBatch" + ], + [ + "batch", + "batches\tmodule" + ], + [ + "sel", + "selectDirDialog\t(batch_MECH.py)" + ], + [ + "Run", + "runBatch\tfunction" + ], + [ + "emb", + "embedding_depth\t(bls.py)" + ], + [ + "Bilay", + "BilayerSonophore\t(bls.py)" + ], + [ + "Son", + "SonicNeuron\tclass" + ], + [ + "embe", + "embedding_depth\t(sonic.py)" + ], + [ + "check", + "checkBatchLog\tfunction" + ], + [ + "neurons_", + "neurons_dict" + ], + [ + "fin", + "findPeaks\tfunction" + ], + [ + "kA", + "kA_tissue" + ], + [ + "cortial", + "CorticalRS\tclass" + ], + [ + "Soni", + "SonicNeuron" + ], + [ + "A", + "Arange" + ], + [ + "Q", + "Qderivatives\tfunction" + ] + ] + }, + "buffers": + [ + { + "file": "work/week4/conjugate_gradient/optimizer.py", + "settings": + { + "buffer_size": 1710, + "encoding": "UTF-8", + "line_ending": "Windows", + "name": "def S(x, y):" + } + } + ], + "build_system": "", + "build_system_choices": + [ + ], + "build_varint": "", + "command_palette": + { + "height": 357.0, + "last_filter": "", + "selected_items": + [ + [ + "ana", + "Anaconda Prompt" + ], + [ + "comm", + "Git: Quick Commit (repo)" + ], + [ + "pre", + "Markdown Preview: Preview in Browser" + ], + [ + "sid", + "View: Toggle Side Bar" + ], + [ + "pus", + "Git: Push" + ], + [ + "side", + "View: Toggle Side Bar" + ], + [ + "push", + "Git: Push" + ], + [ + "stat", + "Git: Status" + ], + [ + "ub", + "Ubuntu Bash" + ], + [ + "list", + "Package Control: List Packages" + ], + [ + "ins", + "Package Control: Install Package" + ], + [ + "term", + "Terminal" + ], + [ + "ubun", + "Ubuntu Bash" + ], + [ + "sta", + "Git: Status" + ], + [ + "rein", + "Indentation: Reindent Lines" + ], + [ + "inden", + "Indentation: Reindent Lines" + ], + [ + "comman", + "Preferences: Commands - User" + ], + [ + "git list", + "Git: Stash List" + ], + [ + "lint", + "SublimeLinter: Lint This View" + ], + [ + "ter", + "Terminal" + ], + [ + "li", + "Package Control: List Packages" + ], + [ + "lin", + "SublimeLinter: Lint This View" + ], + [ + "insta", + "Package Control: Install Package" + ], + [ + "remo", + "Package Control: Remove Package" + ], + [ + "sublimelinter", + "SublimeLinter: Toggle Highlights" + ], + [ + "ab", + "About" + ], + [ + "commi", + "Git: Quick Commit (repo)" + ], + [ + "te", + "Terminal" + ], + [ + "git stat", + "Git: Status" + ], + [ + "go", + "Anaconda: Goto object assignment" + ], + [ + "go to", + "Anaconda: Goto object assignment" + ], + [ + "got", + "Anaconda: Goto object assignment" + ], + [ + "temr", + "Terminal" + ], + [ + "git", + "Git: Status" + ], + [ + "st", + "Git: Status" + ], + [ + "bar", + "View: Toggle Side Bar" + ], + [ + "", + "About" + ], + [ + "prev", + "Markdown Preview: Preview in Browser" + ], + [ + "commit", + "Git: Quick Commit (repo)" + ], + [ + "com", + "Git: Commit" + ], + [ + "log", + "Git: Log All" + ], + [ + "prett", + "Pretty JSON: Format (Pretty Print) JSON" + ], + [ + "inst", + "Package Control: Install Package" + ], + [ + "statu", + "Git: Status" + ], + [ + "git commi", + "Git: Quick Commit (repo)" + ], + [ + "comit", + "Git: Quick Commit (repo)" + ], + [ + "previ", + "Markdown Preview: Preview in Browser" + ], + [ + "mak", + "Markdown Preview: Preview in Browser" + ], + [ + "git commit ", + "Git: Quick Commit (repo)" + ], + [ + "git add", + "Git: Add All" + ], + [ + "status", + "Git: Status" + ], + [ + "packa", + "Preferences: Browse Packages" + ], + [ + "goto", + "Package Control: Discover Packages" + ], + [ + "repl p", + "SublimeREPL: Python - IPython" + ], + [ + "repl py", + "SublimeREPL: Python" + ], + [ + "theme", + "UI: Select Color Scheme" + ], + [ + "list pa", + "Package Control: List Packages" + ], + [ + "lo", + "Git: Log All" + ], + [ + "commitr", + "Git: Quick Commit (repo)" + ], + [ + "git repo", + "Git: Quick Commit (repo)" + ], + [ + "commit repo", + "Git: Quick Commit (repo)" + ], + [ + "doc", + "Anaconda: Display object docs" + ], + [ + "pu", + "Git: Push" + ], + [ + "auto", + "Anaconda: Autoformat PEP8 Errors" + ], + [ + "git st", + "Git: Status" + ], + [ + "them", + "Colorsublime: Install Theme" + ], + [ + "intall", + "Package Control: Install Package" + ], + [ + "boxy", + "Boxy Theme: Preferences" + ], + [ + "color", + "Colorsublime: Install Theme" + ], + [ + "colo", + "Colorsublime: Install Theme" + ], + [ + "in", + "Package Control: Install Package" + ] + ], + "width": 454.0 + }, + "console": + { + "height": 171.0, + "history": + [ + "cls", + "clear" + ] + }, + "distraction_free": + { + "menu_visible": true, + "show_minimap": false, + "show_open_files": false, + "show_tabs": false, + "side_bar_visible": false, + "status_bar_visible": false + }, + "expanded_folders": + [ + "/C/Users/Theo/Documents/SP4E18" + ], + "file_history": + [ + "/C/Users/Theo/Documents/SP4E18/work/week4/conjugate_gradient/conjugate_gradient.py", + "/C/Users/Theo/Documents/SP4E18/README.md", + "/C/Users/Theo/Downloads/2dcollections3d_demo.py", + "/C/Users/Theo/Documents/SP4E-TNE18/work/week3/stl/starting_point/memory_third.cc", + "/C/Users/Theo/Documents/SP4E-TNE18/work/week3/stl/starting_point/memory_second.cc", + "/C/Users/Theo/Documents/SP4E-TNE18/work/week3/stl/starting_point/memory_first.cc", + "/C/Users/Theo/Documents/SP4E-TNE18/work/week3/stl/starting_point/CMakeLists.txt", + "/C/Users/Theo/Documents/SP4E-TNE18/work/week3/stl/starting_point/ex6.cc", + "/C/Users/Theo/Documents/SP4E-TNE18/work/week3/stl/starting_point/ex5.cc", + "/C/Users/Theo/Documents/SP4E-TNE18/work/.gitignore", + "/C/Users/Theo/Documents/SP4E-TNE18/work/week3/stl/starting_point/ex2.cc", + "/C/Users/Theo/Documents/SP4E-TNE18/work/week3/stl/starting_point/build/cmake_install.cmake", + "/C/Users/Theo/Documents/SP4E-TNE18/work/week3/stl/starting_point/build/CMakeFiles/Makefile2", + "/C/Users/Theo/Documents/SP4E-TNE18/work/week3/stl/starting_point/build/Makefile", + "/C/Users/Theo/AppData/Roaming/Sublime Text 3/Packages/User/Default.sublime-commands", + "/C/Users/Theo/Documents/fit Vmeff/fit_Vmeff.py", + "/C/Users/Theo/Documents/BCdemystifier/init.txt", + "/C/Users/Theo/Documents/BCdemystifier/New Text Document.txt", + "/C/Users/Theo/Documents/BCdemystifier/.gitignore", + "/C/Users/Theo/Documents/SP4E-TNE18/work/week3/stl/starting_point/ex3.cc", + "/C/Users/Theo/Documents/SP4E-TNE18/work/week3/stl/starting_point/ex1.cc", + "/C/Users/Theo/Documents/SP4E-TNE18/SP4E-TNE18.sublime-project", + "/C/Users/Theo/Documents/SP4E-TNE18/work/week3/stl/starting_point/build/toto.txt", + "/C/Users/Theo/Documents/SP4E-TNE18/work/week2/hello/sources/hello.cc", + "/C/Users/Theo/Documents/SP4E-TNE18/work/week2/float/sources/main.cc", + "/C/Users/Theo/Documents/SP4E-TNE18/work/week2/pi/sources/main.cc", + "/C/Users/Theo/Documents/SP4E-TNE18/work/week2/hello/sources/series.cc", + "/C/Users/Theo/Documents/SP4E-TNE18/work/week2/hello/sources/series.hh", + "/C/Users/Theo/AppData/Roaming/Sublime Text 3/Packages/User/ubuntu_bash.py", + "/C/Users/Theo/AppData/Roaming/Sublime Text 3/Packages/User/anaconda_prompt.py", + "/C/Users/Theo/Documents/SP4E-TNE18/work/week2/hello/sources/CMakeLists.txt", + "/C/Users/Theo/Documents/SP4E-TNE18/.gitignore", + "/C/Users/Theo/Documents/SP4E-TNE18/test.cpp", + "/C/Users/Theo/Documents/SP4E-TNE18/work/week2/hello/sources/build/CMakeFiles/Makefile2", + "/C/Users/Theo/Documents/SP4E-TNE18/lectures/list-package-Debian.txt", + "/C/Users/Theo/Documents/SP4E-TNE18/work/week2/hello/sources/build/CMakeCache.txt", + "/C/Users/Theo/Documents/SP4E-TNE18/work/week2/hello/sources/build/hello", + "/C/Users/Theo/Documents/SP4E-TNE18/work/week3/stl/starting_point/empty_main.cc", + "/C/Users/Theo/Desktop/key.txt", + "/C/Users/Theo/Documents/PySONIC/paper figures/fig7.py", + "/C/Users/Theo/Documents/PySONIC/paper figures/fig4.py", + "/C/Users/Theo/Documents/PySONIC/paper figures/fig3.py", + "/C/Users/Theo/Documents/PySONIC/paper figures/fig2.py", + "/C/Users/Theo/Desktop/SONIC paper data/Fig 7 - behavior maps/behavior_maps.py", + "/C/Users/Theo/Documents/PySONIC/PySONIC/plt/effvars.py", + "/C/Users/Theo/Documents/PySONIC/PySONIC/plt/__init__.py", + "/C/Users/Theo/Desktop/SONIC paper data/Fig 3 - QS approximation/test_subthr_mech.py", + "/C/Users/Theo/Documents/PySONIC/paper figures/fig5.py", + "/C/Users/Theo/Documents/PySONIC/paper figures/fig6.py", + "/C/Users/Theo/Documents/PySONIC/PySONIC/plt/actmap.py", + "/C/Users/Theo/Documents/PySONIC/paper figures/utils.py", + "/C/Users/Theo/Desktop/SONIC paper data/Fig 5-6 - model validation/PW DC/comp_comprates_PW_vs_DC.py", + "/C/Users/Theo/Desktop/test.py", + "/C/Users/Theo/Desktop/SONIC paper data/Fig 5-6 - model validation/CW amplitude/comp_comprates_CW_vs_amplitude.py", + "/C/Users/Theo/Desktop/SONIC paper data/Fig 5-6 - model validation/CW regimes/comp_comprates_CW_vs_regimes.py", + "/C/Users/Theo/Documents/PySONIC/PySONIC/utils.py", + "/C/Users/Theo/Desktop/SONIC paper data/Fig 5-6 - model validation/PW PRF/comp_traces_PW_vs_PRF.py", + "/C/Users/Theo/Documents/PySONIC/PySONIC/postpro.py", + "/C/Users/Theo/Documents/PySONIC/paper figures/fig5-6.py", + "/C/Users/Theo/Documents/PySONIC/PySONIC/plt/spikemetrics.py", + "/C/Users/Theo/Desktop/SONIC paper data/Fig 5-6 - model validation/PW DC/comp_spikemetrics_PW_vs_DC.py", + "/C/Users/Theo/Documents/PySONIC/PySONIC/plt/comp.py", + "/C/Users/Theo/Desktop/SONIC paper data/Fig 5-6 - model validation/PW DC/comp_traces_PW_vs_DC.py", + "/C/Users/Theo/Documents/PySONIC/PySONIC/batches.py", + "/C/Users/Theo/Desktop/SONIC paper data/Fig 5-6 - model validation/CW frequency/comp_traces_CW_vs_frequency.py", + "/C/Users/Theo/Desktop/SONIC paper data/Fig 5-6 - model validation/CW frequency/comp_spikemetrics_CW_vs_frequency.py", + "/C/Users/Theo/Documents/PySONIC/scripts/run_estim.py", + "/C/Users/Theo/Documents/PySONIC/scripts/run_astim.py", + "/C/Users/Theo/Desktop/SONIC paper data/Fig 5-6 - model validation/CW amplitude/comp_spikemetrics_CW_vs_amplitude.py", + "/C/Users/Theo/Documents/PySONIC/PySONIC/core/nbls.py", + "/C/Users/Theo/Documents/PySONIC/PySONIC/constants.py", + "/C/Users/Theo/Documents/PySONIC/scripts/plot_effective_variables.py", + "/C/Users/Theo/Desktop/SONIC paper data/Fig 5-6 - model validation/CW regimes/comp_spikes_CW_vs_regimes.py", + "/C/Users/Theo/Desktop/SONIC paper data/Fig 5-6 - model validation/CW regimes/run_CW_vs_regimes.py", + "/C/Users/Theo/Desktop/SONIC paper data/Fig 5-6 - model validation/CW regimes/comp_traces_CW_vs_regimes.py", + "/C/Users/Theo/Desktop/SONIC paper data/Fig 5-6 - model validation/CW amplitude/comp_traces_CW_vs_amplitude.py", + "/C/Users/Theo/Desktop/SONIC paper data/Fig 5-6 - model validation/CW amplitude/run_CW_vs_amplitude.py", + "/C/Users/Theo/Documents/PySONIC/scripts/run_lookups.py", + "/C/Users/Theo/Documents/PySONIC/.gitignore", + "/C/Users/Theo/Desktop/Intramembrane Cavitation Detection/experiments 04.18/calibration_utils.py", + "/C/Users/Theo/Desktop/Intramembrane Cavitation Detection/model predictions/utils.py", + "/C/Users/Theo/Desktop/Intramembrane Cavitation Detection/experiments 04.18/utils.py", + "/C/Users/Theo/Desktop/Paper data/Fig 2 - optimization pipeline/plot_pipeline_figure.py", + "/C/Users/Theo/Desktop/Paper data/Fig 2 - optimization pipeline/HH_equations.tex", + "/C/Users/Theo/Documents/PySONIC/scripts/plot_gating_kinetics.py", + "/C/Users/Theo/Documents/PySONIC/PySONIC/neurons/TC.mod", + "/C/Users/Theo/Documents/PySONIC/scripts/records.csv", + "/C/Users/Theo/Documents/PySONIC/PySONIC/plt/batch.py", + "/C/Users/Theo/Documents/PySONIC/PySONIC/neurons/leech.py", + "/C/Users/Theo/Documents/PySONIC/scripts/plot.py", + "/C/Users/Theo/Documents/PySONIC/PySONIC/neurons/cortical.py", + "/C/Users/Theo/Documents/PySONIC/PySONIC/neurons/thalamic.py", + "/C/Users/Theo/Documents/PySONIC/PySONIC/plt/pltutils.py", + "/C/Users/Theo/Desktop/Paper data/Fig 7 - behavior maps/behavior_maps.py", + "/C/Users/Theo/Documents/PySONIC/scripts/plot_activation_map.py", + "/C/Users/Theo/Desktop/Paper data/Fig 7 - behavior maps/plot_activation_map.py", + "/C/Users/Theo/Documents/PySONIC/PySONIC/core/pneuron.py", + "/C/Users/Theo/Documents/PySONIC/PySONIC/core/bls.py", + "/C/Users/Theo/Documents/PySONIC/scripts/plot_rheobase_amps.py", + "/C/Users/Theo/Documents/PySONIC/PySONIC/plt/plot_comp.py", + "/C/Users/Theo/Documents/PySONIC/PySONIC/plt/plot_batch.py", + "/C/Users/Theo/Documents/PySONIC/scripts/run_mech.py", + "/C/Users/Theo/Documents/test NEURON/comp_Python_NEURON_TC_detailed.py", + "/C/Users/Theo/Documents/PySONIC/scripts/plot_comp.py", + "/C/Users/Theo/Documents/PySONIC/scripts/plot_batch.py", + "/C/Users/Theo/Documents/PySONIC/deprecated/curve fitting/fit_alphameff.py", + "/C/Users/Theo/Documents/PySONIC/deprecated/update_lookups.py", + "/C/Users/Theo/Documents/PySONIC/tests/test_basic.py", + "/C/Users/Theo/Documents/PySONIC/deprecated/miscellaneous/plot_ZeqQS0.py", + "/C/Users/Theo/Documents/PySONIC/deprecated/miscellaneous/test_downsampling.py", + "/C/Users/Theo/Documents/PySONIC/deprecated/miscellaneous/interpolate_lookups.py", + "/C/Users/Theo/Documents/PySONIC/deprecated/miscellaneous/postpro_rmse_charge.py", + "/C/Users/Theo/Documents/PySONIC/deprecated/file management/datasort.py", + "/C/Users/Theo/Documents/PySONIC/deprecated/file management/create_data_folders.py", + "/C/Users/Theo/Documents/PySONIC/PySONIC.sublime-project", + "/C/Users/Theo/Documents/SP4E-TNE18/work/week2/float/sources/CMakeLists.txt", + "/C/Users/Theo/Documents/SP4E-TNE18/work/week2/hello.cpp", + "/C/Users/Theo/Documents/PySONIC/deprecated/miscellaneous/test_interp_speed.py", + "/C/Users/Theo/Documents/PySONIC/deprecated/GUI/test_gui.py", + "/C/Users/Theo/Documents/PySONIC/PySONIC/neurons/__init__.py", + "/C/Users/Theo/Documents/PySONIC/PySONIC/core/__init__.py", + "/C/Users/Theo/Documents/PySONIC/MANIFEST.in", + "/C/Users/Theo/Desktop/test xlslog/test.py", + "/C/Users/Theo/Documents/SP4E-TNE18/exercises/week1/python-hello/sources-solution/hello-exo2.py", + "/C/ProgramData/Anaconda3/Lib/site-packages/xlsxwriter/worksheet.py", + "/C/Users/Theo/Documents/PySONIC/tests/test_intermolecular_pressure.py", + "/C/Users/Theo/Documents/PySONIC/PySONIC/__init__.py", + "/C/Users/Theo/Documents/PySONIC/notebooks/BLS model - intermolecular pressure.ipynb" + ], + "find": + { + "height": 49.0 + }, + "find_in_files": + { + "height": 340.0, + "where_history": + [ + "", + "C:\\Users\\Theo\\Desktop\\Paper data,*.py", + "" + ] + }, + "find_state": + { + "case_sensitive": true, + "find_history": + [ + "gcc", + "g++", + "underflow", + "vec", + "locator", + "interp1d", + "Cmavg", + "'fig7a'", + "CW_Athrs", + "index_col", + "extractCompTimes", + "getSims", + "getSpikingMetrics", + "sipkeamp", + "plotSpikingMetrics", + "full_paths", + "sonic_paths", + "CW_sonic_fpaths", + "CW_full_fpaths", + "plotSpikingMetrics", + "getSpikingMetrics", + "computeSpikeMetrics", + "createSimQueue", + "xlslog", + "effective", + "classic", + "amps", + "effective", + "classic", + "computeSpikeMetrics", + "add_patch", + "bbox_to_", + "subplots_ad", + "Qm", + "np.int", + "xlslog", + "computeAStimLookups", + "from PySONIC.plt", + "('PySONIC')", + "from PySONIC.plt", + "timeunits", + "cm2inch", + "neuron", + "plotRawTrace", + "logging", + "defaults", + "onClick", + "defaults", + "FRlims", + "tmax", + "neuron", + "cm2", + "colorscale", + "yscale", + "FR_bounds", + "A_scale", + "FR_scale", + "ybounds", + "si_format", + "toffset", + "getActivationMap", + "Vm", + "plotRawTrace", + "getLookups2D", + "getNeuronLookupsFile", + "ctivation", + "getActivationMap", + "on_click", + "plotActivationMap", + "matplotlib", + "cm", + "computeMeshEdges", + "getStimTiming", + "getPatchesLoc", + "patch", + "computeMeshEdges", + "SaveFigDialog", + "fig_ext", + "SaveFigDialog", + "directory", + "name ", + "logger", + "npatches", + "Rec", + "title", + "ESTIM_CW_title", + "getP", + "inset", + "Rectangle", + "getNeuronsDict", + "BilayerSonophore", + "Rectangle", + "InteractiveLegend", + "bbox_to_anchor", + "ngas", + "nQ", + "200", + "bls.simulate", + "npc", + "filecode", + "pkl_filename", + "pkl_root", + "nbls", + "pickle.load", + "NeuronalBilayerSonophore", + "DownSample", + "nblscore", + "getLookups2D", + "getNeuronLookupsFile", + "downsample", + "extractCompTimes", + "computeMeshEdges", + "LennardJones", + "rescale", + "find_nearest", + "DownSample", + "xlslog", + "filterwarnings", + "self", + "checkBatchLog", + "CheckBatchLog", + "filename", + "None", + "1", + "None", + "getDefaultIndexes", + "checkNumBounds", + "getCycleAverage" + ], + "highlight": true, + "in_selection": false, + "preserve_case": false, + "regex": false, + "replace_history": + [ + "arr", + "prefix", + "spikeamp", + "full_fpaths", + "sonic_fpaths", + "sonic_paths", + "full_paths", + "sonic", + "full", + "xvar", + "sonic", + "full", + "Qthr", + "FRscale", + "Ascale", + "FRbounds", + "Ascale", + "FRscale", + "Vbounds", + "getStimPulses", + "pulse", + "gas.size", + "charges.size", + "downsample", + "bls", + "filepath", + "1.", + "None", + "2", + "1", + "Qref", + "nbls", + "NeuronalBilayerSonophore", + "queue_out", + "queue_in", + "queue", + "Adrive", + "self", + "self.neuron", + "fullDerivatives", + "ode", + "Arange", + "Astim", + "outpath", + "derivatives", + "PointNeuron", + "Aref", + "Qref", + "Aref", + "aref", + "fref", + "dref", + "='sonic'", + "PySONIC", + "getLogger('PySONIC')", + "from PySONIC import", + "from PySONIC." + ], + "reverse": false, + "show_context": true, + "use_buffer2": true, + "whole_word": false, + "wrap": true + }, + "groups": + [ + { + "selected": 0, + "sheets": + [ + { + "buffer": 0, + "file": "work/week4/conjugate_gradient/optimizer.py", + "semi_transient": false, + "settings": + { + "buffer_size": 1710, + "regions": + { + }, + "selection": + [ + [ + 178, + 178 + ] + ], + "settings": + { + "SL.37.region_keys": + [ + ], + "auto_complete_triggers": + [ + { + "characters": ".", + "selector": "source.python - string - comment - constant.numeric" + }, + { + "characters": ".", + "selector": "source.python - string - constant.numeric" + } + ], + "auto_name": "def S(x, y):", + "c_time": + [ + 128, + 3, + 99, + 100, + 97, + 116, + 101, + 116, + 105, + 109, + 101, + 10, + 100, + 97, + 116, + 101, + 116, + 105, + 109, + 101, + 10, + 113, + 0, + 67, + 10, + 7, + 226, + 10, + 9, + 13, + 25, + 52, + 12, + 20, + 120, + 113, + 1, + 133, + 113, + 2, + 82, + 113, + 3, + 46 + ], + "syntax": "Packages/Python/Python.sublime-syntax", + "translate_tabs_to_spaces": true + }, + "translation.x": 0.0, + "translation.y": 0.0, + "zoom_level": 1.0 + }, + "stack_index": 0, + "type": "text" + } + ] + } + ], + "incremental_find": + { + "height": 27.0 + }, + "input": + { + "height": 106.0 + }, + "layout": + { + "cells": + [ + [ + 0, + 0, + 1, + 1 + ] + ], + "cols": + [ + 0.0, + 1.0 + ], + "rows": + [ + 0.0, + 1.0 + ] + }, + "menu_visible": true, + "output.SublimeLinter": + { + "height": 160.0 + }, + "output.exec": + { + "height": 144.0 + }, + "output.find_results": + { + "height": 0.0 + }, + "output.git": + { + "height": 171.0 + }, + "output.mdpopups": + { + "height": 0.0 + }, + "pinned_build_system": "Packages/User/py36.sublime-build", + "project": "SP4E18.sublime-project", + "replace": + { + "height": 50.0 + }, + "save_all_on_build": true, + "select_file": + { + "height": 0.0, + "last_filter": "", + "selected_items": + [ + [ + "", + "paper figures\\fig6.py" + ], + [ + "git stats", + "scripts\\plot_gating_kinetics.py" + ] + ], + "width": 0.0 + }, + "select_project": + { + "height": 0.0, + "last_filter": "", + "selected_items": + [ + ], + "width": 0.0 + }, + "select_symbol": + { + "height": 357.0, + "last_filter": "", + "selected_items": + [ + ], + "width": 374.0 + }, + "selected_group": 0, + "settings": + { + }, + "show_minimap": false, + "show_open_files": false, + "show_tabs": true, + "side_bar_visible": true, + "side_bar_width": 234.0, + "status_bar_visible": true, + "template_settings": + { + } +} diff --git a/exercises/.gitignore b/exercises/.gitignore new file mode 100644 index 0000000..b5c28b7 --- /dev/null +++ b/exercises/.gitignore @@ -0,0 +1,11 @@ +CMakeCache.txt +CMakeFiles +Makefile +*~ +cmake_install.cmake +*.cbp +.idea +*.pyc +*.out +cmake-build-* +*.o \ No newline at end of file diff --git a/exercises/week1/git/auto/sujet.el b/exercises/week1/git/auto/sujet.el new file mode 100644 index 0000000..4b83741 --- /dev/null +++ b/exercises/week1/git/auto/sujet.el @@ -0,0 +1,16 @@ +(TeX-add-style-hook + "sujet" + (lambda () + (TeX-add-to-alist 'LaTeX-provided-class-options + '(("article" "a4paper" "11pt"))) + (TeX-run-style-hooks + "latex2e" + "../td" + "article" + "art11") + (TeX-add-symbols + '("mycomment" 1)) + (LaTeX-add-environments + '("exercice" LaTeX-env-args ["argument"] 0))) + :latex) + diff --git a/exercises/week1/git/sujet.pdf b/exercises/week1/git/sujet.pdf new file mode 100644 index 0000000..62173fd Binary files /dev/null and b/exercises/week1/git/sujet.pdf differ diff --git a/exercises/week1/python-hello/sources-solution/hello-exo1.py b/exercises/week1/python-hello/sources-solution/hello-exo1.py new file mode 100644 index 0000000..595709f --- /dev/null +++ b/exercises/week1/python-hello/sources-solution/hello-exo1.py @@ -0,0 +1,11 @@ +import sys + +if (not len(sys.argv) == 2): + print("Not enough parameters for the program {0}".format(sys.argv[0])) + sys.exit() + +print("sys.argv is of type {0}".format(type(sys.argv))) +prog_name = sys.argv[0] +N = sys.argv[1] + +print("{0} says: Hello {1}".format(prog_name, N)) diff --git a/exercises/week1/python-hello/sources-solution/hello-exo2.py b/exercises/week1/python-hello/sources-solution/hello-exo2.py new file mode 100644 index 0000000..5766005 --- /dev/null +++ b/exercises/week1/python-hello/sources-solution/hello-exo2.py @@ -0,0 +1,20 @@ +import sys +import series + + +def main(): + + if (not len(sys.argv) == 2): + print("Not enough parameters for the program {0}".format(sys.argv[0])) + return + + print("sys.argv is of type {0}".format(type(sys.argv))) + prog_name = sys.argv[0] + N = int(sys.argv[1]) + + print("{0} says: Hello {1} {2}".format( + prog_name, series.computeSeries(N), N*(N+1)/2)) + + +if __name__ == '__main__': + main() diff --git a/exercises/week1/python-hello/sources-solution/series.py b/exercises/week1/python-hello/sources-solution/series.py new file mode 100644 index 0000000..a792cca --- /dev/null +++ b/exercises/week1/python-hello/sources-solution/series.py @@ -0,0 +1,6 @@ +def computeSeries(n): + res = 0 + for i in range(1, n+1): + res += i + + return res diff --git a/exercises/week1/python-hello/sources/hello.py b/exercises/week1/python-hello/sources/hello.py new file mode 100644 index 0000000..b31f50f --- /dev/null +++ b/exercises/week1/python-hello/sources/hello.py @@ -0,0 +1,26 @@ +import sys + + +# 1 +print("Hello World") +print(len(sys.argv)) +print(type(sys.argv)) # sys.argv is a list + +# 2 +n = int(sys.argv[1]) +print("Hello {}".format(n)) + +# 3 +n = int(sys.argv[1]) +s = 0 +for k in range(1, n + 1): # n additions are necessary + s += k +print("Hello {}".format(s)) +# overhead? + +# 4 +n = int(sys.argv[1]) +s = 0 +for k in range(1, n + 1): + s += k +print("Hello {}".format(s)) diff --git a/exercises/week1/python-hello/sources/main.py b/exercises/week1/python-hello/sources/main.py new file mode 100644 index 0000000..c4a3f08 --- /dev/null +++ b/exercises/week1/python-hello/sources/main.py @@ -0,0 +1,5 @@ +import sys +from series import computeSeries + +n = int(sys.argv[1]) +print("Hello {}".format(computeSeries(n))) diff --git a/exercises/week1/python-hello/sources/series.py b/exercises/week1/python-hello/sources/series.py new file mode 100644 index 0000000..32942d5 --- /dev/null +++ b/exercises/week1/python-hello/sources/series.py @@ -0,0 +1,7 @@ + + +def computeSeries(Niterations): + s = 0 + for k in range(1, Niterations + 1): # n additions are necessary + s += k + return s diff --git a/exercises/week1/python-hello/sujet.pdf b/exercises/week1/python-hello/sujet.pdf new file mode 100644 index 0000000..042de8e Binary files /dev/null and b/exercises/week1/python-hello/sujet.pdf differ diff --git a/exercises/week2/float/sources-solution/CMakeLists.txt b/exercises/week2/float/sources-solution/CMakeLists.txt new file mode 100644 index 0000000..4115451 --- /dev/null +++ b/exercises/week2/float/sources-solution/CMakeLists.txt @@ -0,0 +1,4 @@ +cmake_minimum_required(VERSION 2.6) +project(hello-exercise) + +add_executable(main main.cc) diff --git a/exercises/week2/float/sources-solution/main.cc b/exercises/week2/float/sources-solution/main.cc new file mode 100644 index 0000000..24ddf7c --- /dev/null +++ b/exercises/week2/float/sources-solution/main.cc @@ -0,0 +1,100 @@ +/* -------------------------------------------------------------------------- */ +#include +#include +#include +/* -------------------------------------------------------------------------- */ + +void exo1(){ + + std::cout << "Exo1" << std::endl; + + int a = 0.5; + std::cout << a << std::endl; + + double b = 1/2; + std::cout << b << std::endl; + +} +/* -------------------------------------------------------------------------- */ +float tanh1(double x){ + double res = (exp(x) - exp(-x))/(exp(x) + exp(-x)); + return res; +} + +float tanh2(double x){ + double res = (1 - exp(-2.*x))/(1 + exp(-2.*x)); + return res; +} + + +void exo2(){ + + std::cout << "Exo2" << std::endl; + + int nstep = 10; + double dx = 1000./nstep; + for (int i = 0; i < nstep; ++i) { + double a = tanh1(dx*i); + double b = tanh2(dx*i); + std::cout << dx*i << " " << tanh(dx*i) << " " + << a << " " << b << std::endl; + } +} +/* -------------------------------------------------------------------------- */ + +double tanh3(double x){ + double res = ( -2.*exp(-2.*x))/(1 + exp(-2.*x)); + return res; +} + +double evolution(double pn, double v, double dt){ + return pn + dt*v; +} + + +void exo3(){ + + std::cout << "Exo3.a" << std::endl; + + int nstep = 10; + double dx = 1000./nstep; + for (int i = 0; i < nstep; ++i) { + double a = tanh3(dx*i); + std::cout << dx*i << " " << tanh(dx*i) -1 << " " + << a << std::endl; + } + + std::cout << "Exo3.b" << std::endl; + + double a = 0; + double b = a + 1e-3; + double dt = 1e3; + double v = 3e8; + + + + for (int i = 0; i < 40; ++i) { + double res = b - a; + std::cout << i << " " << res << " " << a << " " << b << std::endl; + a = evolution(a,v,dt); + b = evolution(b,v,dt); + } + + +} + +/* -------------------------------------------------------------------------- */ + + +int main(int argc, char ** argv){ + + + exo1(); + exo2(); + exo3(); + + return EXIT_SUCCESS; +} + + + diff --git a/exercises/week2/float/sources/CMakeLists.txt b/exercises/week2/float/sources/CMakeLists.txt new file mode 100644 index 0000000..4115451 --- /dev/null +++ b/exercises/week2/float/sources/CMakeLists.txt @@ -0,0 +1,4 @@ +cmake_minimum_required(VERSION 2.6) +project(hello-exercise) + +add_executable(main main.cc) diff --git a/exercises/week2/float/sources/main.cc b/exercises/week2/float/sources/main.cc new file mode 100644 index 0000000..be05830 --- /dev/null +++ b/exercises/week2/float/sources/main.cc @@ -0,0 +1,31 @@ +/* -------------------------------------------------------------------------- */ +#include +#include +#include +/* -------------------------------------------------------------------------- */ + +void exo1(){ + + +} +/* -------------------------------------------------------------------------- */ +void exo2(){ +} +/* -------------------------------------------------------------------------- */ +void exo3(){ +} +/* -------------------------------------------------------------------------- */ + + +int main(int argc, char ** argv){ + + + exo1(); + exo2(); + exo3(); + + return EXIT_SUCCESS; +} + + + diff --git a/exercises/week2/float/sujet.pdf b/exercises/week2/float/sujet.pdf new file mode 100644 index 0000000..21d03ac Binary files /dev/null and b/exercises/week2/float/sujet.pdf differ diff --git a/exercises/week2/hello/sources-solution/CMakeLists.txt b/exercises/week2/hello/sources-solution/CMakeLists.txt new file mode 100644 index 0000000..8c8e534 --- /dev/null +++ b/exercises/week2/hello/sources-solution/CMakeLists.txt @@ -0,0 +1,4 @@ +cmake_minimum_required(VERSION 2.6) +project(hello-exercise) + +add_executable(hello hello.cc series.cc) diff --git a/exercises/week2/hello/sources-solution/hello.cc b/exercises/week2/hello/sources-solution/hello.cc new file mode 100644 index 0000000..489dc0d --- /dev/null +++ b/exercises/week2/hello/sources-solution/hello.cc @@ -0,0 +1,14 @@ +#include "series.hh" +#include +#include +/* -------------------------------------------------------------------------- */ + +int main(int argc, char **charv) { + + int N = atoi(charv[1]); + int res = computeSeries(N); + + std::cout << "Hello " << N << " res " << res << std::endl; + + return EXIT_SUCCESS; +} diff --git a/exercises/week2/hello/sources-solution/series.cc b/exercises/week2/hello/sources-solution/series.cc new file mode 100644 index 0000000..7aa7d40 --- /dev/null +++ b/exercises/week2/hello/sources-solution/series.cc @@ -0,0 +1,8 @@ +int computeSeries(int N) { + int res = 0; + + for (int i = 0; i <= N; ++i) { + res += i; + } + return res; +} diff --git a/exercises/week2/hello/sources-solution/series.hh b/exercises/week2/hello/sources-solution/series.hh new file mode 100644 index 0000000..373b10f --- /dev/null +++ b/exercises/week2/hello/sources-solution/series.hh @@ -0,0 +1,6 @@ +#ifndef SERIES_HH +#define SERIES_HH + +int computeSeries(int N); + +#endif diff --git a/exercises/week2/hello/sources/CMakeLists.txt b/exercises/week2/hello/sources/CMakeLists.txt new file mode 100644 index 0000000..ab0f7b5 --- /dev/null +++ b/exercises/week2/hello/sources/CMakeLists.txt @@ -0,0 +1,4 @@ +cmake_minimum_required(VERSION 2.6) +project(hello-exercise) + +add_executable(hello hello.cc) diff --git a/exercises/week2/hello/sources/hello.cc b/exercises/week2/hello/sources/hello.cc new file mode 100644 index 0000000..4ab78a4 --- /dev/null +++ b/exercises/week2/hello/sources/hello.cc @@ -0,0 +1,11 @@ +#include +#include +#include "series.hh" +/* -------------------------------------------------------------------------- */ + + +int main(int argc, char ** argv){ + + // write your code here + return EXIT_SUCCESS; +} diff --git a/exercises/week2/hello/sources/series.cc b/exercises/week2/hello/sources/series.cc new file mode 100644 index 0000000..c409279 --- /dev/null +++ b/exercises/week2/hello/sources/series.cc @@ -0,0 +1,5 @@ +#include "series.hh" + +int computeSeries(int Niteratrions){ + //... +} diff --git a/exercises/week2/hello/sources/series.hh b/exercises/week2/hello/sources/series.hh new file mode 100644 index 0000000..6ed0169 --- /dev/null +++ b/exercises/week2/hello/sources/series.hh @@ -0,0 +1,6 @@ +#ifndef SERIES_HH +#define SERIES_HH + +int computeSeries(int Niterations); + +#endif diff --git a/exercises/week2/hello/sujet.pdf b/exercises/week2/hello/sujet.pdf new file mode 100644 index 0000000..23ca370 Binary files /dev/null and b/exercises/week2/hello/sujet.pdf differ diff --git a/exercises/week2/pi/sources-solution/CMakeLists.txt b/exercises/week2/pi/sources-solution/CMakeLists.txt new file mode 100644 index 0000000..4115451 --- /dev/null +++ b/exercises/week2/pi/sources-solution/CMakeLists.txt @@ -0,0 +1,4 @@ +cmake_minimum_required(VERSION 2.6) +project(hello-exercise) + +add_executable(main main.cc) diff --git a/exercises/week2/pi/sources-solution/main.cc b/exercises/week2/pi/sources-solution/main.cc new file mode 100644 index 0000000..4bf766e --- /dev/null +++ b/exercises/week2/pi/sources-solution/main.cc @@ -0,0 +1,33 @@ +/* -------------------------------------------------------------------------- */ +#include +#include +#include +#include +/* -------------------------------------------------------------------------- */ + +int main(int argc, char ** argv){ + + unsigned long maxiter = atof(argv[1]); + float pi = 0.; + float pi2 = 0.; + + for (unsigned long k = 1 ; k < maxiter ; ++k){ + pi += 1./(1.*k*k); + + unsigned long k2 = maxiter-k; + pi2 += 1./(1.*k2*k2); + + + } + pi *= 6.; + pi2 *= 6.; + + std::cout << std::scientific << std::setprecision(15) + << pi << " " << pi2 << " " << M_PI*M_PI + << " " << pi - M_PI*M_PI << " " << pi2 - M_PI*M_PI << std::endl; + + return EXIT_SUCCESS; +} + + + diff --git a/exercises/week2/pi/sources/CMakeLists.txt b/exercises/week2/pi/sources/CMakeLists.txt new file mode 100644 index 0000000..4115451 --- /dev/null +++ b/exercises/week2/pi/sources/CMakeLists.txt @@ -0,0 +1,4 @@ +cmake_minimum_required(VERSION 2.6) +project(hello-exercise) + +add_executable(main main.cc) diff --git a/exercises/week2/pi/sources/main.cc b/exercises/week2/pi/sources/main.cc new file mode 100644 index 0000000..cee344f --- /dev/null +++ b/exercises/week2/pi/sources/main.cc @@ -0,0 +1,15 @@ +/* -------------------------------------------------------------------------- */ +#include +#include +#include +#include +/* -------------------------------------------------------------------------- */ + +int main(int argc, char ** argv){ + + // your code here + return EXIT_SUCCESS; +} + + + diff --git a/exercises/week2/pi/sujet.pdf b/exercises/week2/pi/sujet.pdf new file mode 100644 index 0000000..0a24237 Binary files /dev/null and b/exercises/week2/pi/sujet.pdf differ diff --git a/exercises/week3/stl/solution/CMakeLists.txt b/exercises/week3/stl/solution/CMakeLists.txt new file mode 100644 index 0000000..73f478d --- /dev/null +++ b/exercises/week3/stl/solution/CMakeLists.txt @@ -0,0 +1,15 @@ +cmake_minimum_required(VERSION 2.6) + +add_executable(stl + main.cc +) + +set (CMAKE_CXX_STANDARD 17) + +add_executable(algorithms + algorithms.cc +) + +add_executable(memory + memory.cc +) diff --git a/exercises/week3/stl/solution/algorithms.cc b/exercises/week3/stl/solution/algorithms.cc new file mode 100644 index 0000000..6aaf28c --- /dev/null +++ b/exercises/week3/stl/solution/algorithms.cc @@ -0,0 +1,69 @@ +#include +#include +#include +#include +#include +#include + +void print_vector(std::vector& v) { + for (double x : v) + std::cout << x << " "; + std::cout << std::endl; +} + +int main() { + unsigned int n = 20; // size of vector + + std::vector values(n); // create vector with n numbers + + // Filling with zeros + std::fill(values.begin(), values.end(), 0); + print_vector(values); + + // Applying std::iota + std::iota(values.begin(), values.end(), 1); + print_vector(values); // should print "1 2 3 4 5 ..." + + // Squaring a value + auto square_it = [](double & x) { x *= x; }; + double y = 3.; + square_it(y); + std::cout << "3*3 = " << y << std::endl; // should print 9. + + // Squaring values of the vector + for (double & y : values) + square_it(y); + print_vector(values); // should print "1 4 9 16 25 ..." + + + // [resetting values] + std::iota(values.begin(), values.end(), 1); + + // Squaring values using std::for_each + std::for_each(values.begin(), values.end(), square_it); + print_vector(values); // should print "1 4 9 16 25 ..." + + // Summing the squares + double answer = n*(n+1)*(2*n+1)/6.; + double result = 0; // will contain the result + // capture the result variable by-reference + auto summation = [&result] (double & x) { result += x; }; + // apply the summation function + std::for_each(values.begin(), values.end(), summation); + std::cout << result << " = " << answer << std::endl; + + // Do the same with std::reduce + result = std::accumulate(values.begin(), values.end(), 0.); + std::cout << result << " = " << answer << std::endl; + + // We need to invert the squares + auto inverse = [](double & x) { x = 1. / x; }; + std::for_each(values.begin(), values.end(), inverse); // apply inverse + + // Sum all squares in reverse order to avoid roundoff errors + result = std::accumulate(values.rbegin(), values.rend(), 0.); + double pi_estimate = std::sqrt(6. * result); + std::cout << pi_estimate << " ~ " << M_PI << std::endl; + + return 0; +} diff --git a/exercises/week3/stl/solution/main.cc b/exercises/week3/stl/solution/main.cc new file mode 100644 index 0000000..0d5fcc6 --- /dev/null +++ b/exercises/week3/stl/solution/main.cc @@ -0,0 +1,182 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +/* -------------------------------------------------------------------------- */ +using Triplet = std::array; + +/* -------------------------------------------------------------------------- */ +inline std::ostream & operator <<(std::ostream & stream, Triplet & _this) +{ + stream << _this[0] << " " << _this[1] << " " << _this[2]; + return stream; +} + + +/* -------------------------------------------------------------------------- */ + +int main(int argc, char ** argv){ + + + /* + Exercice 1 + */ + + if (argc != 2) { + std::cerr << "missing argument: your name" << std::endl; + return EXIT_FAILURE; + } + + std::string myName = "Guillaume"; + std::string argument = std::string(argv[1]); + if (myName == argument){ + std::cout << "You have a nive name" << std::endl; + } + + + /* + Exercice 2 + + */ + + std::ofstream f("toto.txt"); + f << 1.5 << " " << 1.0 << " " << 2.0 << std::endl; + + std::ifstream is("toto.txt"); + std::string str; + + if (is.is_open() == false) { + std::cerr << "cannot open file toto.txt" << std::endl; + throw; + } + + getline(is, str); + std::stringstream sstr(str); + + double x, y, z; + sstr >> x; + sstr >> y; + sstr >> z; + + std::cout << x << " " << y << " " << z << std::endl; + + + /* + Exercice 3 + */ + + std::array point = { x, y, z}; + for (auto & p: point) { + std::cout << p << " "; + } + std::cout << "\n"; + + std::vector vect; + int npoints = 100; + + for (int i = 0; i < npoints; ++i) { + double step = 2.*M_PI / npoints; + vect.push_back(step*i); + } + + std::cout << vect.size() << std::endl; + + std::vector< std::pair > sin_vect; + for (auto & pi: vect) { + sin_vect.push_back(std::make_pair(pi, sin(pi)) ); + } + + std::ofstream of("sin_pi.txt"); + for (auto & pairs: sin_vect){ + of << std::scientific << std::setprecision(20) + << pairs.first << " " << pairs.second << std::endl; + } + + + + + /* + Exercice 5 + */ + + std::map map; + Triplet origin_coordinates = {0., 0., 0.}; + + //Triplet origin_coordinates(0.,0.,0.); + map["sun"] = origin_coordinates; + + std::map::iterator end3 = map.end(); + + //origin_coordinates.coords[0] = 1.; + origin_coordinates[0] = 1.; + std::map::iterator it3 = map.find("earth"); + if (it3 == end3) map["earth"] = origin_coordinates; + + std::set keys; + + std::cout << std::endl << "The complete map content is:" << std::endl; + for (auto & planet: map ){ + auto & key = planet.first; + auto & values = planet.second; + std::cout << key << std::endl; + std::cout << values << std::endl; + keys.insert(key); + } + + std::map map2; + + Triplet mercury_coordinates = {0.25, 0., 0.}; + map2["mercury"] = mercury_coordinates; + + Triplet earth_coordinates = {1.25, 0., 0.}; + map2["earth"] = earth_coordinates; + + Triplet jupiter_coordinates = {5.25, 0., 0.}; + map2["jupiter"] = jupiter_coordinates; + + Triplet sun_coordinates = {0., 0., 0.}; + map2["sun"] = sun_coordinates; + + std::set keys2; + + std::cout << std::endl << "The complete map 2 content is:" << std::endl; + for (auto & planet: map2) { + auto & key = planet.first; + auto & values = planet.second; + std::cout << key << std::endl; + std::cout << values << std::endl; + keys2.insert(key); + } + + + std::set intersect; + std::set_intersection( keys.begin(), keys.end(), keys2.begin(), keys2.end(), + std::inserter( intersect, intersect.begin() ) ); + + std::map map_intersect; + for(auto & key: intersect) { + map_intersect[key] = map2[key]; + } + + std::cout << std::endl << "The complete intersected map content is:" << std::endl; + for(auto & planet: map_intersect) { + std::cout << planet.first << std::endl; + std::cout << planet.second << std::endl; + } + + + + return EXIT_SUCCESS; +} + + + diff --git a/exercises/week3/stl/solution/memory.cc b/exercises/week3/stl/solution/memory.cc new file mode 100644 index 0000000..ac5b28c --- /dev/null +++ b/exercises/week3/stl/solution/memory.cc @@ -0,0 +1,113 @@ +#include +#include +#include + +void question1_stack() { + int values[10]; + + for (int& v : values) + v = 0; + + for (int i = 0; i < 10; ++i) + std::cout << values[i] << " "; + std::cout << std::endl; +} + +void question1_heap() { + int * values = new int[10]; + + // We can't use range-for with heap allocated arrays + // the best solution would use a std::vector + for (int i = 0; i < 10; ++i) + values[0] = 0; + + for (int i = 0; i < 10; ++i) + std::cout << values[i] << " "; + std::cout << std::endl; + + // The memory should be deallocated, otherwise we + // have a dangling pointer + delete[] values; +} + +std::vector* stack_allocation(int n) { + std::vector values(n); + return &values; // good compilers show a warning here +} + +std::vector* heap_allocation(int n) { + std::vector* values = new std::vector(n); + return values; +} + +void question2() { + std::vector * stack_values = stack_allocation(10); + std::vector * heap_values = heap_allocation(10); + + // stack_values->size() should fail because memory was freed + // at the end of the function stack_allocation + std::cout << stack_values->size() << ", " << heap_values->size() << std::endl; + + // We still need to delete + delete heap_values; +} + +void question1_bis() { + std::array stack_values; + + for (int& v : stack_values) + v = 0; + + std::vector heap_values(10); + + for (int& v : heap_values) + v = 0; + + // no need to delete, everything is managed +} + +std::unique_ptr> unique_heap_allocation(int n) { + return std::make_unique>(n); +} + +void question2_bis() { + std::unique_ptr> heap_vector = unique_heap_allocation(10); + std::cout << heap_vector->size() << std::endl; + + // no need to delete: the unique pointer will deallocate everything at + // the end of the function +} + +void question3() { + auto unique = std::make_unique>(10); + + std::unique_ptr> other = nullptr; + + // the move operation will make "unique" invalid + // so that there is ONLY ONE pointer to the resource + // hence "unique_ptr" + other = std::move(unique); + + // memory will be deallocated nicely by the pointer "other" +} + +void question3_bis() { + auto shared = std::make_shared>(10); + std::shared_ptr> other = nullptr; + + // This works because they are shared pointer + other = shared; + + // memory will be deallocated nicely +} + +int main() { + question1_stack(); + question1_heap(); + //question2(); <-- this causes an error + question1_bis(); + question2_bis(); + question3(); + question3_bis(); + return 0; +} diff --git a/exercises/week3/stl/starting_point/CMakeLists.txt b/exercises/week3/stl/starting_point/CMakeLists.txt new file mode 100644 index 0000000..c45059a --- /dev/null +++ b/exercises/week3/stl/starting_point/CMakeLists.txt @@ -0,0 +1,6 @@ +cmake_minimum_required(VERSION 2.6) + +add_executable(main empty_main.cc) +# add_executable(memory_first memory_first.cc) +# add_executable(memory_second memory_second.cc) +# add_executable(memory_third memory_third.cc) diff --git a/exercises/week3/stl/starting_point/empty_main.cc b/exercises/week3/stl/starting_point/empty_main.cc new file mode 100644 index 0000000..7d65f05 --- /dev/null +++ b/exercises/week3/stl/starting_point/empty_main.cc @@ -0,0 +1,19 @@ +#include +#include +#include +#include +#include +#include +#include +#include +/* -------------------------------------------------------------------------- */ + +int main(int argc, char ** argv){ + + + + return EXIT_SUCCESS; +} + + + diff --git a/exercises/week3/stl/starting_point/memory_first.cc b/exercises/week3/stl/starting_point/memory_first.cc new file mode 100644 index 0000000..6511961 --- /dev/null +++ b/exercises/week3/stl/starting_point/memory_first.cc @@ -0,0 +1,16 @@ +#include +#include +#include +#include + +int main() { + int values; + + for (int& v : values) + v = 0; + + for (int i = 0; i < 10; ++i) + std::cout << values[i] << " "; + std::cout << std::endl; + return 0; +} diff --git a/exercises/week3/stl/starting_point/memory_second.cc b/exercises/week3/stl/starting_point/memory_second.cc new file mode 100644 index 0000000..ef5780a --- /dev/null +++ b/exercises/week3/stl/starting_point/memory_second.cc @@ -0,0 +1,20 @@ +#include +#include +#include +#include + +std::vector* stack_allocation(int n) { + return nullptr; +} + +std::vector* heap_allocation(int n) { + return nullptr; +} + +int main() { + std::vector * stack_values = stack_allocation(10); + std::vector * heap_values = heap_allocation(10); + + std::cout << stack_values->size() << ", " << heap_values->size() << std::endl; + return 0; +} diff --git a/exercises/week3/stl/starting_point/memory_third.cc b/exercises/week3/stl/starting_point/memory_third.cc new file mode 100644 index 0000000..c373b58 --- /dev/null +++ b/exercises/week3/stl/starting_point/memory_third.cc @@ -0,0 +1,12 @@ +#include +#include +#include +#include + + +int main() { + auto unique = std::make_unique>(10); + + std::unique_ptr> other = nullptr; + other = unique; +} diff --git a/exercises/week3/stl/sujet.pdf b/exercises/week3/stl/sujet.pdf new file mode 100644 index 0000000..5aaec2f Binary files /dev/null and b/exercises/week3/stl/sujet.pdf differ diff --git a/exercises/week4/conjugate_gradient/auto/sujet.el b/exercises/week4/conjugate_gradient/auto/sujet.el new file mode 100644 index 0000000..25c7023 --- /dev/null +++ b/exercises/week4/conjugate_gradient/auto/sujet.el @@ -0,0 +1,15 @@ +(TeX-add-style-hook + "sujet" + (lambda () + (TeX-add-to-alist 'LaTeX-provided-class-options + '(("article" "a4paper" "11pt"))) + (TeX-run-style-hooks + "latex2e" + "article" + "art11" + "color" + "float") + (TeX-add-symbols + '("mycomment" 1))) + :latex) + diff --git a/exercises/week4/conjugate_gradient/sujet.pdf b/exercises/week4/conjugate_gradient/sujet.pdf new file mode 100644 index 0000000..32a5354 Binary files /dev/null and b/exercises/week4/conjugate_gradient/sujet.pdf differ diff --git a/exercises/week4/matplotlib/auto/sujet.el b/exercises/week4/matplotlib/auto/sujet.el new file mode 100644 index 0000000..7fe21e0 --- /dev/null +++ b/exercises/week4/matplotlib/auto/sujet.el @@ -0,0 +1,12 @@ +(TeX-add-style-hook + "sujet" + (lambda () + (TeX-add-to-alist 'LaTeX-provided-class-options + '(("article" "a4paper" "11pt"))) + (TeX-run-style-hooks + "latex2e" + "../td" + "article" + "art11")) + :latex) + diff --git a/exercises/week4/matplotlib/sujet.pdf b/exercises/week4/matplotlib/sujet.pdf new file mode 100644 index 0000000..08b4823 Binary files /dev/null and b/exercises/week4/matplotlib/sujet.pdf differ diff --git a/lectures/.gitignore b/lectures/.gitignore new file mode 100644 index 0000000..e4e5f6c --- /dev/null +++ b/lectures/.gitignore @@ -0,0 +1 @@ +*~ \ No newline at end of file diff --git a/lectures/code_snippets/.gitignore b/lectures/code_snippets/.gitignore new file mode 100644 index 0000000..512a446 --- /dev/null +++ b/lectures/code_snippets/.gitignore @@ -0,0 +1,3 @@ +build +.idea +cmake-build* \ No newline at end of file diff --git a/lectures/code_snippets/CMakeLists.txt b/lectures/code_snippets/CMakeLists.txt new file mode 100644 index 0000000..610d3a2 --- /dev/null +++ b/lectures/code_snippets/CMakeLists.txt @@ -0,0 +1,12 @@ + +cmake_minimum_required(VERSION 2.6) +project(snippet) + +set(CMAKE_CXX_STANDARD 14) + +file(GLOB SOURCES ${PROJECT_SOURCE_DIR}/*.cpp) +foreach(f ${SOURCES}) + get_filename_component(basename ${f} NAME_WE) + get_filename_component(dir ${f} DIRECTORY) + add_executable(${basename} ${f}) +endforeach() diff --git a/lectures/code_snippets/array.cpp b/lectures/code_snippets/array.cpp new file mode 100644 index 0000000..da0bb43 --- /dev/null +++ b/lectures/code_snippets/array.cpp @@ -0,0 +1,10 @@ +#include +#include + +int main() { + std::array vec; + vec[2] = 10.; + + std::array vec2; + vec2[8] = "mars"; +} \ No newline at end of file diff --git a/lectures/code_snippets/for_each.cpp b/lectures/code_snippets/for_each.cpp new file mode 100644 index 0000000..c591681 --- /dev/null +++ b/lectures/code_snippets/for_each.cpp @@ -0,0 +1,20 @@ +#include +#include +#include + +int main() { + + std::vector vec(10); + + // indirect call + auto foo = [](auto &v) { std::cout << v; }; + std::for_each(vec.begin(), vec.end(), foo); + + // inline call + std::for_each(vec.begin(), vec.end(), [](auto &v) { v += 1; }); + + // storing result in another array + std::vector res; + std::transform(vec.begin(), vec.end(), std::back_inserter(res), + [](auto &val) { return val + 1; }); +} \ No newline at end of file diff --git a/lectures/code_snippets/fstream.cpp b/lectures/code_snippets/fstream.cpp new file mode 100644 index 0000000..92ad52a --- /dev/null +++ b/lectures/code_snippets/fstream.cpp @@ -0,0 +1,17 @@ +#include +#include +#include +#include + +int main() { + + std::ofstream fout("test.plot"); + fout << M_PI << std::endl; + fout.close(); + + double pi_val; + std::ifstream fin("test.plot"); + fin >> pi_val; + std::cout << pi_val << std::endl; + fin.close(); +} \ No newline at end of file diff --git a/lectures/code_snippets/hello.cpp b/lectures/code_snippets/hello.cpp new file mode 100644 index 0000000..aa02274 --- /dev/null +++ b/lectures/code_snippets/hello.cpp @@ -0,0 +1,9 @@ +#include +int main(int argc, char *argv[]) { + + /* This is a comment */ + + // Print "Hello World" to the screen + std::cout << "Hello World\n"; + return 0; +} \ No newline at end of file diff --git a/lectures/code_snippets/iostream.cpp b/lectures/code_snippets/iostream.cpp new file mode 100644 index 0000000..d9c0d5d --- /dev/null +++ b/lectures/code_snippets/iostream.cpp @@ -0,0 +1,11 @@ +#include + +int main() { + int obj; + + std::cout << obj << std::endl; + + std::cout << "flush now!" << std::flush << std::endl; + + std::cerr << obj << std::endl; +} \ No newline at end of file diff --git a/lectures/code_snippets/lambda.cpp b/lectures/code_snippets/lambda.cpp new file mode 100644 index 0000000..aba9400 --- /dev/null +++ b/lectures/code_snippets/lambda.cpp @@ -0,0 +1,36 @@ +#include + +void foo1() { std::cout << "Hey" << std::endl; } + +int main() { + + // call a standard function + foo1(); + + auto foo2 = []() { std::cout << "Hey again !" << std::endl; }; + + foo2(); + + auto foo3 = [](int a, double b) { std::cout << a << "," << b << std::endl; }; + + foo3(10, 102.3); + + int toto = 2; + // captures 'toto' variable + auto foo4 = [toto]() { std::cout << toto << std::endl; }; + + foo4(); + + // captures all in current scope + auto foo5 = [&]() { std::cout << toto << std::endl; }; + + foo5(); + + // explicit declaration + auto foo6 = []() -> int { return 19; }; + auto res = foo6(); + + // implicit declaration + auto foo7 = []() { return 19.3; }; + auto res2 = foo7(); +} \ No newline at end of file diff --git a/lectures/code_snippets/loops.cpp b/lectures/code_snippets/loops.cpp new file mode 100644 index 0000000..e326780 --- /dev/null +++ b/lectures/code_snippets/loops.cpp @@ -0,0 +1,40 @@ +#include +#include + +int main() { + + std::vector vec(10); + for (int i = 0; i < 10; ++i) { + vec[i] = 10; + } + + std::array array; + for (int i = 0; i < 10; ++i) { + array[i] = 10; + } + + { + // vector loop with iterators + std::vector::iterator it = vec.begin(); + std::vector::iterator end = vec.end(); + for (; it != end; ++it) { + *it = 10.; + } + } + + { + // with the auto + auto it = vec.begin(); + auto end = vec.end(); + for (; it != end; ++it) { + *it = 10.; + } + } + + { + // with the range loop + for (auto &v : vec) { + v = 10.; + } + } +} \ No newline at end of file diff --git a/lectures/code_snippets/map.cpp b/lectures/code_snippets/map.cpp new file mode 100644 index 0000000..acf56dc --- /dev/null +++ b/lectures/code_snippets/map.cpp @@ -0,0 +1,10 @@ +#include + +int main() { + + std::map particle_mass; + + particle_mass["mars"] = 6.4171e23; + particle_mass["sun"] = 1.9885e30; + particle_mass["copper"] = 1.0552061e-25; +} \ No newline at end of file diff --git a/lectures/code_snippets/new.cpp b/lectures/code_snippets/new.cpp new file mode 100644 index 0000000..295bd4b --- /dev/null +++ b/lectures/code_snippets/new.cpp @@ -0,0 +1,22 @@ +double *get_scalar() { + + double *v = new double; + return v; +} + +double *get_vector(int n) { + + double *v = new double[n]; + return v; +} + +int main() { + + double *scalar = get_scalar(); + // ... do what I need + delete scalar; + + double *vector = get_vector(10); + // ... do what I need + delete[] vector; +} \ No newline at end of file diff --git a/lectures/code_snippets/scientific_precision.cpp b/lectures/code_snippets/scientific_precision.cpp new file mode 100644 index 0000000..1e49a7c --- /dev/null +++ b/lectures/code_snippets/scientific_precision.cpp @@ -0,0 +1,15 @@ +#include +#include +#include + +int main(){ + + // for this output + std::cout << std::scientific + << std::setprecision(15) + << M_PI << std::endl; + + //permanent + std::cout.precision(15); + std::cout.setf(std::ios::scientific); +} \ No newline at end of file diff --git a/lectures/code_snippets/set.cpp b/lectures/code_snippets/set.cpp new file mode 100644 index 0000000..a6bb8de --- /dev/null +++ b/lectures/code_snippets/set.cpp @@ -0,0 +1,9 @@ +#include + +int main() { + std::set set1; + set1.insert(100); + set1.insert(101); + set1.insert(101); + set1.erase(100); +} \ No newline at end of file diff --git a/lectures/code_snippets/shared_pointers.cpp b/lectures/code_snippets/shared_pointers.cpp new file mode 100644 index 0000000..795e2d3 --- /dev/null +++ b/lectures/code_snippets/shared_pointers.cpp @@ -0,0 +1,14 @@ +#include +#include + +std::shared_ptr get_vector(int n) { + return std::shared_ptr(new double[n]); +} + +int main() { + + std::shared_ptr ptr1 = get_vector(10); + std::shared_ptr ptr2 = ptr1; + + // memory of pointer freed when ptr1 and ptr2 are out of scope +} \ No newline at end of file diff --git a/lectures/code_snippets/sstream.cpp b/lectures/code_snippets/sstream.cpp new file mode 100644 index 0000000..36bab24 --- /dev/null +++ b/lectures/code_snippets/sstream.cpp @@ -0,0 +1,15 @@ +#include +#include + +int main() { + std::stringstream sstr("1 2 3.14"); + int i, j; + double k; + + sstr >> i >> j >> k; + std::cout << i << " " << j << " " << k << std::endl; + + std::stringstream sstr2; + sstr2 << 142; + std::cout << sstr2.str() << std::endl; +} \ No newline at end of file diff --git a/lectures/code_snippets/sstream_main_arguments.cpp b/lectures/code_snippets/sstream_main_arguments.cpp new file mode 100644 index 0000000..40e38b2 --- /dev/null +++ b/lectures/code_snippets/sstream_main_arguments.cpp @@ -0,0 +1,14 @@ +#include + +int main(int argc, char **argv) { + std::stringstream sstr; + for (int i = 1; i < argc; ++i) { + sstr << argv[i] << " "; + } + + double arg1; + sstr >> arg1; + + int arg2; + sstr >> arg2; +} \ No newline at end of file diff --git a/lectures/code_snippets/string.cc b/lectures/code_snippets/string.cc new file mode 100644 index 0000000..a40460f --- /dev/null +++ b/lectures/code_snippets/string.cc @@ -0,0 +1,7 @@ +#include +#include + +int main() { + std::string my_string = "test.plot"; + std::cout << my_string << std::endl; +} \ No newline at end of file diff --git a/lectures/code_snippets/unique_pointers.cpp b/lectures/code_snippets/unique_pointers.cpp new file mode 100644 index 0000000..cafd493 --- /dev/null +++ b/lectures/code_snippets/unique_pointers.cpp @@ -0,0 +1,18 @@ +#include +#include + +std::unique_ptr get_scalar() { + // create a unique pointer + return std::make_unique(3); +} + +int main() { + + std::unique_ptr ptr = get_scalar(); + // ... do what I need like... + std::cout << *ptr; + // no need to delete scalar (will be automatically) + + // cannot be copied => compilation error + // std::unique_ptr ptr_copy = ptr; +} \ No newline at end of file diff --git a/lectures/code_snippets/vector.cpp b/lectures/code_snippets/vector.cpp new file mode 100644 index 0000000..c88aac9 --- /dev/null +++ b/lectures/code_snippets/vector.cpp @@ -0,0 +1,6 @@ +#include + +int main() { + std::vector vec(10); + vec.resize(100); +} \ No newline at end of file diff --git a/lectures/difficulties-scientific-programming.png b/lectures/difficulties-scientific-programming.png new file mode 100644 index 0000000..e927d89 Binary files /dev/null and b/lectures/difficulties-scientific-programming.png differ diff --git a/lectures/figures/automation.png b/lectures/figures/automation.png new file mode 100644 index 0000000..1ef32f5 Binary files /dev/null and b/lectures/figures/automation.png differ diff --git a/lectures/figures/branches.jpg b/lectures/figures/branches.jpg new file mode 100644 index 0000000..cddea5e Binary files /dev/null and b/lectures/figures/branches.jpg differ diff --git a/lectures/figures/git-cloning.png b/lectures/figures/git-cloning.png new file mode 100644 index 0000000..ffdf1d5 Binary files /dev/null and b/lectures/figures/git-cloning.png differ diff --git a/lectures/figures/git-commit.png b/lectures/figures/git-commit.png new file mode 100644 index 0000000..8e46b99 Binary files /dev/null and b/lectures/figures/git-commit.png differ diff --git a/lectures/figures/git-pull.png b/lectures/figures/git-pull.png new file mode 100644 index 0000000..c8b685f Binary files /dev/null and b/lectures/figures/git-pull.png differ diff --git a/lectures/figures/git-push.png b/lectures/figures/git-push.png new file mode 100644 index 0000000..7fe61c2 Binary files /dev/null and b/lectures/figures/git-push.png differ diff --git a/lectures/figures/git-xkcd.png b/lectures/figures/git-xkcd.png new file mode 100644 index 0000000..3f35d2d Binary files /dev/null and b/lectures/figures/git-xkcd.png differ diff --git a/lectures/figures/is_it_worth_the_time.png b/lectures/figures/is_it_worth_the_time.png new file mode 100644 index 0000000..d9ac46e Binary files /dev/null and b/lectures/figures/is_it_worth_the_time.png differ diff --git a/lectures/figures/phd-comics-sp4e.png b/lectures/figures/phd-comics-sp4e.png new file mode 100644 index 0000000..146a756 Binary files /dev/null and b/lectures/figures/phd-comics-sp4e.png differ diff --git a/lectures/figures/ssh.png b/lectures/figures/ssh.png new file mode 100644 index 0000000..fe9cb40 Binary files /dev/null and b/lectures/figures/ssh.png differ diff --git a/lectures/list-package-Debian.txt b/lectures/list-package-Debian.txt new file mode 100644 index 0000000..580f0b0 --- /dev/null +++ b/lectures/list-package-Debian.txt @@ -0,0 +1,3 @@ +List of packages installed on the VirtualBox of the class: + +sudo apt install xfce4 xterm lightdm emacs virtualbox-guest-utils virtualbox-guest-x11 g++ cmake cmake-curses-gui git doxygen graphviz doxygen-gui firefox-esr spyder3 valgrind libeigen3-dev libeigen3-doc libfftw3-3 libfftw3-dev python3-pybind11 paraview binutils kcachegrind googletest googletest-tools google-mock python3-matplotlib python3-scipy ipython3 python3-sympy xfce4-terminal xpdf diff --git a/lectures/week1.html b/lectures/week1.html new file mode 100644 index 0000000..b772189 --- /dev/null +++ b/lectures/week1.html @@ -0,0 +1,1176 @@ + + + + + + + + + + + +talk slides + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

Scientific Programming
for Engineers (SP4E)

+
+
+
+
+
+ +
+

Welcome

    +
  • About the class
      +
    • The goal is to provide some useful knowledge (tool box) to the job of a PhD student who wants to perform a numerical work
    • +
    • Uncover the details of computers and numerical simulations: bring power (analogy blue/red pill of Matrix movie)
    • +
    • The class will be a bit particular (uncovering knowledge), thus it is personal and needs participation.
    • +
    • Students have to build their own understanding/experience on the various tasks required.
    • +
    • Evaluation will be made by evaluating homeworks.
    • +
    +
  • +
+ +
+
+
+
+ +
+

Difficulties in making scientific software

+
+
+ +
+
    +
  • Real numbers (and all rounding errors) +
  • +
  • Units
      +
    • Conversion of units to be able to plug modules together
    • +
    • Non SI unit system needs explicit conversion between quantities
    • +
    • Mars Orbiter disaster
    • +
    +
  • +
  • Rapid changes

    +
      +
    • Need of quick and easy implementation/insertion of new features
    • +
    • Need non regression tests
    • +
    +
  • +
  • Large problems

    +
      +
    • Need to manipulate large number of DOFs to increase accuracy
    • +
    • Need for collaborative tools to make cutting edge applications
    • +
    +
  • +
+ +
+
+
+
+ +
+

"Computer scientists are/should be LAZY (but smartly)"

+
+
+ +
+

+
+
+
+
+ +
+
+
+
+
+
+ +
+

Cycles for engineering production of scientific software

+
+
+ +
+
    +
  1. Scientific question
  2. +
  3. Analysis and formulation of the problem
  4. +
  5. Conception: algorithmic decision
  6. +
  7. Implementation
  8. +
  9. Deployment of the code
  10. +
  11. Analysis/post-treatment of the results
  12. +
+ +
+
+
+
+ +
+

Scientific question

+
+
+
+
+ +
+

Analysis and formulation of the problem

    +
  • Math formulation: PDE, optimization, statistical, ...
  • +
  • Define the input and output of the model
  • +
  • Separate the post-treatment
  • +
  • If there are some analytical solutions you need to be aware
  • +
+ +
+
+
+
+ +
+

Conception: algorithmic decision

    +
  • Make a chart diagram of the algorithm: separate the subparts
  • +
  • Choose/identify how to solve the subparts
  • +
  • Choose the appropriate data structures
  • +
  • For new algorithms, evaluate the complexity, make an effort of generalization
  • +
  • If global complexity unaffordable with the desired grain (number of DOFs) consider changing the model (back to 2:formulation )
  • +
+ +
+
+
+
+ +
+

Implementation

    +
  • Identify existing software for the entire project and for the subparts
  • +
  • Decide a programming language
  • +
  • Decide a coding convention (question of style)
  • +
  • Decide where the code is hosted (for backups and revisions)
  • +
  • Decide a source documentation format
  • +
  • Program the thing
  • +
  • Setup of tests for each necessary sub-part (during programming)
  • +
  • Debug and check for memory leaks
  • +
  • The programming feasibility could here lead to change algorithms or model (back to 2:formulation or 3:conception)
  • +
+ +
+
+
+
+ +
+

Deployment of the code

    +
  • Identify the target machine
  • +
  • Fix compilation issues (multi-system, portability, architecture CPU vs. GPU)
  • +
  • Parametric study management (scripting the launch)
  • +
  • Computing shared/cluster of resources: queue system management
  • +
  • Compilation issue, version issues, could lead to implementation change (back to 4:implementation)
  • +
  • Specific hardware could invalidate the algorithmic decision (back to 3:conception)
  • +
+ +
+
+
+
+ +
+

Analysis/post-treatment of the results

    +
  • Sorting/treating the output
  • +
  • Compute digested measures for the brute output (this should be faster than the computation itself otherwise back to 2:formulation)
  • +
  • Produce graphs (for papers and presentations)
  • +
  • 3D vizualization
  • +
  • Validate numerical results, stability, coherence, comparison to experiment
  • +
  • If the validation fail get back to 5,4,3 or 2 is possible
  • +
+ +
+
+
+
+ +
+

The method for this class

    +
  • Computer place: Your laptop
      +
    • Linux as main OS, Dualboot, or on a VirtualBox(might get slow)
    • +
    • Python framework
    • +
    • C++ framework
    • +
    +
  • +
+ +
+
+ +
+
    +
  • Open source philosophy $\Rightarrow$ access to source
      +
    • Possibility to check the content of the code
    • +
    • Possibility to modify the code for your own purpose
    • +
    • Power of the community
    • +
    • Business model based on knowledge rather than license
    • +
    +
  • +
+ +
+
+
+
+ +
+

The method for this class

    +
  • Why C++ and in python
      +
    • Object oriented is a way to organize the programs for re-usability
    • +
    • C++ allows objects and efficiency
    • +
    • Python allows interactivity and quick testing
    • +
    +
  • +
+ +
+
+ +
+
    +
  • On the repositories
      +
    • Program = bug
    • +
    • Since programs can be complex we need a tool to tag source revisions
    • +
    • Collaborative tool to software development
    • +
    • cvs, svn, git. There is a git at EPFL that we will use.
    • +
    +
  • +
+ +
+
+
+
+ +
+

The method for this class

    +
  • On post-treatment programs
      +
    • Python is perfect for manipulating files, for parsing outputs, for making graphs
    • +
    • Many program exists for visualization. An opensource one: Paraview
    • +
    +
  • +
+ +
+
+
+
+ +
+

Class plan description

+
+
+ +
+ +
+ +
+
    +
  • Tuesday 18-th Sep: Introduction, GIT, python hello world
  • +
  • Tuesday 25-th Sep: C++ hello world, floating point numbers, pi computation
  • +
  • Tuesday 02-th Oct: C++ STL, Coding convention (C++11)
  • +
  • Tuesday 09-th Oct: Paraview, Numpy&Scipy, Matplotlib, Exercise: conjugate gradient (Homework)
  • +
+ +
+ +
+ +
+
+ +
+ +
+ +
+
    +
  • Tuesday 16-th Oct: Object oriented with python
  • +
  • Tuesday 23-th Oct: Object oriented with C++ (Homework)
  • +
  • Tuesday 30-th Oct: Interactive session to design Particle's code, Design patterns, Implementation of simple kepler orbit
  • +
  • Tuesday 06-th Nov: Continuing adimentional kepler's orbit
  • +
+ +
+ +
+ +
+
+
+
+ +
+

Class plan description

+
+
+ +
+ +
+ +
+
    +
  • Tuesday 13-th Nov: Google test. Exercise Produce a test suite for particle's code
  • +
  • Tuesday 20-th Nov: Code optimization and Templates + pingpong ball. (Homework)
  • +
  • Tuesday 27-th Nov: Homework about trajectory optimization (Homework)
  • +
+ +
+ +
+ +
+
+ +
+ +
+ +
+
    +
  • Tuesday 04-th Dec: Using external libraries. Exercise with FFTW (porting to C++)
  • +
  • Tuesday 11-th Dec: Template library: Eigen. Exercise: mass-spring equilibrium
  • +
  • Tuesday 18-th Dec: PyBind+cppimport. Exercise porting the particle's code to python
  • +
+ +
+ +
+ +
+
+
+ +
+
+ +
+

The GIT

+
+
+
+
+ +
+

What would you demand to a tool that will hold your program sources ?

+
+
+ +
+
    +
  • Manage history (evolution in time)
  • +
  • Rewind time
  • +
  • Transport/Backup through network
  • +
  • Team/Concurrent working
  • +
+

This is the standard of most Version control systems such as GIT

+ +
+
+
+
+ +
+

Revision manager:
The GIT & c4science

+
    +
  • Git is a free distributed version control system (DVCS), used for source code management (SCM)
  • +
  • Git operates on a decentralized architecture, so every git working directory has the complete history
  • +
  • Git was initiallydesigned and created by Linus Torvalds for Linux kernel development
  • +
  • EPFL has a GIT repository service (http://c4science.ch/)
  • +
+

wikipedia: revision control system
+wikipedia: git

+ +
+
+
+
+ +
+

GIT - Clone repositories

+
git clone ssh://git@c4science.ch/source/sp4e.git mydir
+
+
+
+ +
+
    +
  • The working copy is the state (can be modified) of a selected branch (definition comes later)
  • +
  • To know the status of the working copy: +
    git status
    +
  • +
  • See the log +
    git log
    +
  • +
+ +
+
+
+
+ +
+

GIT - Commit your modifications

+
git commit -m "interesting modification" file.cc
+
+
+
+
+
+ +
+

GIT - Branches

+
    +
  • All modern VCSs have a mechanism for branches
  • +
  • Branching means you diverge from the main line of development and continue without perturbing the code
  • +
  • Branches can evolve independently
  • +
  • The main branch in GIT is usually called master
  • +
  • GIT doc on branches
  • +
+ +
+
+
+
+ +
+
    +
  • See/create branches: +
    git branch
    +
  • +
  • Change the working copy to another branch +
    git checkout stable-branch
    +
  • +
+ +
+
+
+
+ +
+

GIT - Push your modifications

+
git push origin master
+
    +
  • This operation sends the current branch and merge it into the remote branch
  • +
+ +
+
+
+
+ +
+

GIT - Pull modifications

+
git pull origin master
+
    +
  • This operation actually fetch the remote branch and merge into current branch
  • +
+ +
+
+
+
+ +
+

GIT - remotes

    +
  • You can pull/push to more than a single remote
  • +
  • list the declared remotes: +
    git remote -v
    +
  • +
  • add/remove remotes +
    git remote add/remove
    +
  • +
+ +
+
+
+
+ +
+

GIT - commands

git log
+
+
git status
+
+
git checkout
+
+
git add file.cc
+
+
git rm file.cc
+
+
git mv file.cc
+
+
git commit -m "nice message" file.cc
+
+
git push remote_name branch_name
+git push origin master
+
+
git diff
+git diff revision_hash
+
+
git help whatever_command
+
+ +
+
+
+
+ +
+

GIT - creation/import

    +
  • Create a repository: git init
  • +
  • Adding new files: git add file1 file2 file3
  • +
  • Commit the status: git commit
  • +
  • Add the remote: git remote add origin URI
  • +
+ +
+
+ +
+

.gitignore

    +
  • File to place file patterns to be ignored
  • +
  • example: *~ *.o *.pyc
  • +
+ +
+
+
+
+ +
+

Implicit rule: do not commit something
that is not compiling
to a shared/public repository

+ +
+
+
+
+ + +
+
+
+ +
+

c4science.ch

What is c4science ?

+

C4 Science is a co-creation platform, curation and code sharing. This platform includes:

+
    +
  • Version management system
  • +
  • Common authentication to all Swiss universities to local + external collaborators
  • +
  • Social dimension (wikis, bug tracking, ...)
  • +
  • Code test system (continuous integration)
  • +
  • Swiss alternative to github
  • +
+ +
+
+
+
+ +
+

c4science.ch

Connect to c4science

+

The recommended way to connect to the c4science server (and actually any distant linux machine) is through the SSH protocol:

+
    +
  • You need a pair of keys: one public and one private
  • +
  • They are stored in the directory .ssh in your home directory
  • +
  • The public can be distributed, the private should stay secret
  • +
  • A good habit is to generate one key-pair per client and never transport the private key
  • +
+ +
+
+
+
+ +
+

Interactive session on manipulating git

    +
  • installing git
  • +
  • creating a repository on c4science
  • +
  • cloning it to private laptop
  • +
  • fix permissions
  • +
  • manage conflicts
  • +
+ +
+
+
+
+ +
+

Python language
concepts and syntax

+ +
+
+ +
+
Please install Python/Anaconda on you laptop
+
+
+
+
+ +
+
    +
  • comments
  • +
+
#my super comment
+
+
    +
  • command print
  • +
+
print(10)
+
+
    +
  • type
  • +
+
a = 10
+b = 10.
+type(a)
+type(b)
+
+
    +
  • Converting string to integer or float
  • +
+
a = "1.2"
+print(a)
+a_int = int(a)
+print(a_int)
+a_float = float(a)
+print(a_float)
+
+ +
+
+
+
+ +
+
    +
  • list
    a = list()
    +a.append(2)
    +print(a)
    +a = [2,4,5]
    +a.append([2,4,5])
    +print(a)
    +a += [2,4,5]
    +b = [1,2]*4
    +print(a[1])
    +print(a[2])
    +
    +
  • +
  • maps/dictionaries
    planet = dict()
    +planet["name"] = "mars"  
    +planet["radius"] = 1.2
    +planet["mass"] = 0.4
    +print(planet)
    +
    +
  • +
+ +
+
+
+
+ +
+
    +
  • blocks in python identified by ':' and with the indentation
    block_start:
    + #start of the block
    + instruction1
    + instruction2
    + instruction3
    + #end of the block
    +
    +
  • +
+ +
+
+
+
+ +
+
    +
  • if conditions
    a = 1
    +if not a == 0:
    +     print("a != 0")
    +else:
    + print("a == 0")
    +
    +
  • +
+ +
+
+
+
+ +
+
    +
  • for loops (beware the indentation)
  • +
+
for i in range(0,10):
+    print(i)
+
+
for i in mylist:
+    print(i)
+
+ +
+
+
+
+ +
+
    +
  • defining function
    def foo(arg1, arg2, arg3):
    + ... 
    + some_code
    + ...
    +
    +
  • +
+ +
+
+
+
+ +
+
    +
  • opening files for writing
  • +
+
f = open("my_super_filename.csv", 'w')
+f.write("#X Y Z VX VY VZ FX FY FZ mass radius name\n")
+
+
    +
  • opening a file and read line by line
  • +
+
f = open("my_super_filename.csv", 'r')
+for line in f:
+    entries = line.split()
+    print(entries)
+
+ +
+
+
+
+ +
+
    +
  • using other modules
  • +
+
# request to use another module
+import sys
+
+
    +
  • splitting your program in several files
  • +
+
#my_module.py
+
+def foo(arg):
+    return arg+1
+
+

I can call this function from another file with

+
import my_module
+
+res = my_module.foo(10)
+print(res)
+
+
    +
  • The file must be accessible
  • +
  • To control what is accessible, the environment variable PYTHONPATH is checked
  • +
+ +
+
+
+
+ +
+
    +
  • launching a python script from the terminal
  • +
+ +
python3 exe.py arg1 arg2 arg3
+
    +
  • how to get the arguments passed to the program ?
  • +
+
import sys
+
+# the arguments are stored in the list sys.argv
+# for instance you can print it with
+
+print(sys.argv)
+
+ +
+
+
+
+ +
+

Interactive session on the Hello world

    +
  • Use GIT to access the first exercise
  • +
  • How to split a source file into modules
  • +
  • Manipulating program arguments (argv)
  • +
  • Series calculation
  • +
  • Debugger PDB
  • +
+ +
+
+
+
+
+ + + + + + + diff --git a/lectures/week2.html b/lectures/week2.html new file mode 100644 index 0000000..2a8c6a0 --- /dev/null +++ b/lectures/week2.html @@ -0,0 +1,4016 @@ + + + + + + + + + + + +talk slides + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

git pull upstream master

+
+
+
+
+ +
+

Answer questions from
the previous session

+ +
+
+
+
+ +
+

Programmation

    +
  • How is working/what is a computer ?
  • +
  • What is a program ?
  • +
+ +
+
+ +
+
    +
  • Animation with 3 people:
      +
    • One central memory
    • +
    • One program memory
    • +
    • One arithmetic logic unit
    • +
    +
  • +
+ +
+
+
+
+ +
+
    +
  • First program: +
     *0 = 1
    + *1 = 2
    +
  • +
+ +
+
+ +
+
    +
  • Second program: +
    1:      *1 = 0
    +2:      *2 = 0
    +3:      *0 = *1 >= 4
    +4:      if *0 goto 8
    +5:      *2 = *2 + *1
    +6:      *1 = *1 +1
    +7:      goto 3
    +8:      END
    +
  • +
+ +
+
+
+
+ +
+

Assembly language

An assembly language:

+
    +
  • low-level programming language
  • +
  • strong (generally one-to-one) correspondence between the language +and the computer code instructions.
  • +
+

wikipedia: assembly language

+ +
+
+ +
+

High level language

    +
  • strong abstraction from the details of the computer
  • +
+

wikipedia: High level programming language

+ +
+
+
+
+ +
+

Examples of Compiled language:

+ +
+
+ +
+
    +
  • Fortran
  • +
  • C
  • +
  • C++
  • +
  • Java
  • +
+ +
+
+ +
+

Examples of interpreted language:

+ +
+
+ +
+
    +
  • python
  • +
  • perl
  • +
  • matlab
  • +
+ +
+
+
+
+ +
+

Compilation and linking
C++

+ +
+
+
+
+ +
+

Compiler

    +
  • A computer program transforming source code (in the +source language) into another computer language (the target +language)
  • +
+

wikipedia: compiler

+ +
+
+ +
+ +
+ +
+ +
+ +
+ +
+
+ +
+

GNU C++ compiler: g++

+
g++ -Wall -c source_file.cc
+
    +
  • This will produce a file object source_file.o
  • +
  • "-Wall" to output all warnings and errors
  • +
  • Multiple files with multiple symbols.
  • +
+ +
+
+
+
+ +
+ +
+ +
+ +
+ +
+ +
+
+ +
+
Question: What are the addresses when files are separated ?
+
+
+
+
+ +
+
    +
  • takes one or more object files (generated by a compiler)
  • +
  • combines them into a single executable program.
  • +
+ +
+
+ +
+ +
+ +
+ +
+ +
+ +
+
+ +
+
g++  object1.o object2.o object3.o -o exec
+
+ +
+
+
+
+ +
+

A first C++ program

Open the file 'hello.cpp'

+
+
+
+
+ +
+ +
+ +
+ +
#include <iostream>
+int main(int argc, char *argv[]) {
+
+  /* This is a comment */
+
+  // Print "Hello World" to the screen
+  std::cout << "Hello World\n";
+  return 0;
+}
+
+ + +
+ +
+ +
+
+
+
+ +
+ +
+ +
+ +
#include <iostream>
+int main(int argc, char *argv[]) {
+
+  /* This is a comment */
+
+  // Print "Hello World" to the screen
+  std::cout << "Hello World\n";
+  return 0;
+}
+
+ + +
+ +
+ +
+
+
+
+ +
+ +
+ +
+ +
#include <iostream>
+int main(int argc, char *argv[]) {
+
+  /* This is a comment */
+
+  // Print "Hello World" to the screen
+  std::cout << "Hello World\n";
+  return 0;
+}
+
+ + +
+ +
+ +
+
+
+
+ +
+ +
+ +
+ +
#include <iostream>
+int main(int argc, char *argv[]) {
+
+  /* This is a comment */
+
+
+  // Print "Hello World" to the screen
+  std::cout << "Hello World\n";
+  return 0;
+}
+
+
+ + +
+ +
+ +
+
+
+
+ +
+ +
+ +
+ +
#include <iostream>
+int main(int argc, char *argv[]) {
+
+  /* This is a comment */
+
+  // Print "Hello World" to the screen
+  std::cout << "Hello World\n";
+  return 0;
+}
+
+ + +
+ +
+ +
+
+
+
+ +
+ +
+ +
+ +
#include <iostream>
+int main(int argc, char *argv[]) {
+
+  /* This is a comment */
+
+  // Print "Hello World" to the screen
+  std::cout << "Hello World\n";
+  return 0;
+}
+
+ + +
+ +
+ +
+
+
+
+ +
+ +
+ +
+ +
#include <iostream>
+int main(int argc, char *argv[]) {
+
+  /* This is a comment */
+
+  // Print "Hello World" to the screen
+  std::cout << "Hello World\n";
+  return 0;
+}
+
+ + +
+ +
+ +
+
+
+
+ +
+

Let's compile the code

g++ -Wall hello.cpp -o hello
+
+

Let's launch it

./hello
+
+ +
+
+
+
+ +
+

Build systems and Makefiles

    +
  • Make: utility to automatically build executable programs and libraries
  • +
  • target program rules specified in file makefile
  • +
+

wikipedia: Makefiles

+ +
+
+
+
+ +
+

Rules syntax

target: dependency1 dependency2 dependency3
+<TAB> rule
+
+
    +
  • A simple example for building several files into an executable
  • +
+
all: file1.o file1.hh main.o 
+    gcc -o exec file1.o main.o 
+
+file1.o: file1.hh
+    g++ -c file1.cc
+
+main.o: file1.hh
+    g++ -c main.cc
+
+ +
+
+
+
+ +
+
    +
  • Using intermediate variables
  • +
+
CXX=g++
+LD=gcc 
+CXXFLAGS=-g -Wall
+LDFLAGS=-g -Wall
+
+all: file1.o file1.hh main.o 
+    $(LD) $(LDFLAGS) -o exec file1.o main.o 
+
+file1.o: file1.hh
+    $(CXX) $(CXXFLAGS) -c file1.cc
+
+main.o: file1.hh
+    $(CXX) $(CXXFLAGS) -c main.cc
+
+ +
+
+
+
+ +
+

CMake

What is CMake ?

    +
  • CMake is cross-platform free and open-source software for managing the build process of software using a compiler-independent method.
  • +
  • It is designed to support directory hierarchies and applications that depend on multiple libraries.
  • +
  • It is used in conjunction with native build environments such as make, Apple's Xcode, and Microsoft Visual Studio.
  • +
  • It has minimal dependencies, requiring only a C++ compiler on its own build system.
  • +
  • Concretely, it is a build-system generator, which is multi-plateform.
  • +
+ +
+
+
+
+ +
+

CMake basic syntax

cmake_minimum_required (VERSION 2.6)
+project (GeneratedFromCodeGenerator)
+
+add_executable(main 
+main.cc
+)
+
+

The first lines provide indication about the project and CMake version +requirements.

+

The command add_executable specifies that there is an executable to add, +named main, and the files to include are listed below: main.cc.

+ +
+
+
+
+ +
+
cmake_minimum_required (VERSION 2.6)
+project (GeneratedFromCodeGenerator)
+
+add_executable(main 
+main.cc
+)
+
+target_link_libraries(main m)
+
+ +
+
+
+
+ +
+

The advantages of cmake

    +
  • You can have two build directory, one configured in Debug, one in Release. Building the +Debug/Release can be made simply by changing directory.

    +
  • +
  • CMake has many generators

    +
  • +
+ +
+
+ +
+
    +
  • Borland Makefiles
  • +
  • MSYS Makefiles
  • +
  • MinGW Makefiles
  • +
  • NMake Makefiles
  • +
  • NMake Makefiles JOM
  • +
  • Ninja
  • +
  • Unix Makefiles
  • +
  • Watcom WMake
  • +
  • Visual Studio 6
  • +
  • Visual Studio 7
  • +
  • Visual Studio 7 .NET 2003
  • +
  • Visual Studio 8 2005
  • +
+ +
+
+ +
+
    +
  • Visual Studio 9 2008
  • +
  • Visual Studio 10 2010
  • +
  • Visual Studio 11 2012
  • +
  • Visual Studio 12 2013
  • +
  • Xcode
  • +
  • CodeBlocks
  • +
  • CodeLite
  • +
  • Eclipse CDT4
  • +
  • KDevelop3
  • +
  • Kate
  • +
  • Sublime Text 2
  • +
+ +
+
+
+
+ +
+

CMake default generator

In general, Makefiles have to be generated with CMake. For this, the procedure is:

+
mkdir build
+cd build
+ccmake ../
+
+

Then the GUI should launch. Hit 'c' to configure. +Hit 'g' to generate.

+

CMAKE_BUILD_TYPE (debug or not)

    +
  • Debug (with debug symbols)
  • +
  • Release (optimized)
  • +
+

CLion reads automatically CMakeLists (recommended)

+
+
+
+
+ +
+

C/C++ basic syntax

+
+
+
+
+ +
+
    +
  • comments:
  • +
+ +
+
+ +
+ +
+ +
+ +
// my single line comment
+
+/* here is
+   my multiline comment
+*/
+
+ + +
+ +
+ +
+
+
+
+ +
+
    +
  • generic instruction syntax: Ends with ;
  • +
+ +
+
+ +
+ +
+ +
+ +
instruction;
+
+ + +
+ +
+ +
+
+
+
+ +
+
    +
  • blocks (scope concept)
  • +
+ +
+
+ +
+ +
+ +
+ +
{
+SOMECODE;
+}
+
+ + +
+ +
+ +
+
+ + +
+
+
+ +
+

Variables

+
+
+ +
+ +
+ +
+ +
// definition of some variables
+type var_name;
+
+ + +
+ +
+ +
+
+ +
+

Possible (basic) types: +char, short, int, long int, float, double, long double, bool

+
    +
  • naming convention: name must make sense
  • +
  • const, signed, unsigned
  • +
+

wikipedia: types

+ +
+
+ +
+ +
+ +
+ +
int a = 2;
+double t = 34e10;
+
+ + +
+ +
+ +
+
+ +
+

Type conversion (needs to be explicitly converted)

+
+
+ +
+ +
+ +
+ +
#include <cstdlib>
+
+int a = atoi("2");
+double b = atof("2.3");
+
+ + +
+ +
+ +
+
+
+
+ +
+

Variable scope

    +
  • A variable defined outside of any scope is global.
  • +
  • Otherwise its name makes sense only in the block they are defined.
  • +
+ +
+
+ +
+ +
+ +
+ +
{
+  int a = 1;
+  { int a = 2; }
+  // here a is still 1
+}
+
+ + +
+ +
+ +
+
+
+
+ +
+

Operators

    +
  • Algebra: + - * / = ()
  • +
+ +
+
+ +
+ +
+ +
+ +
int a = 2;
+int b = 1;
+int d = 3;
+int e = (a + b) / d;
+e += 1;
+e++;
+e--;
+int f = e++;
+int g = ++f;
+
+ + +
+ +
+ +
+
+
+
+ +
+

Arrays

+
+
+ +
+ +
+ +
+ +
int a[2];
+a[0] = 1;
+a[1] = 2;
+
+ + +
+ +
+ +
+
+
+
+ +
+

Pointers

    +
  • A pointer is a specific variable type to store the address +of a variable:
  • +
+ +
+
+ +
+ +
+ +
+ +
int a;
+int *ptr = &a;
+
+ + +
+ +
+ +
+
+ +
+
    +
  • You can access the contained value using the * operator
  • +
+ +
+
+ +
+ +
+ +
+ +
*ptr = 1;
+
+ + +
+ +
+ +
+
+ +
+
    +
  • Pointers are incrementable:
  • +
+ +
+
+ +
+ +
+ +
+ +
int a[2];
+int *ptr = a;
+*ptr = 0; // a[0] = 0;
+ptr++;
+*ptr = 1; // a[1] = 1;
+
+ + +
+ +
+ +
+
+
+
+ +
+

References

    +
  • Constant pointers, aliases
  • +
+ +
+
+ +
+ +
+ +
+ +
int a[2];
+int &ref = a[0];
+ref = 0; // a[0] = 0;
+
+ + +
+ +
+ +
+
+
+
+ +
+

if statement: decisional branching

+
+
+ +
+ +
+ +
+ +
int a = 1;
+bool c;
+
+if (a == 2) {
+  c = true;
+} else {
+  c = false;
+}
+
+ + +
+ +
+ +
+
+
+
+ +
+

switch & case: decisional branching with cases

+
+
+ +
+ +
+ +
+ +
int a;
+int res;
+switch (a) {
+case 1:
+  res = 1;
+  break;
+case 2:
+  res = 2;
+case 3:
+  res = 3;
+  break;
+default:
+  res = -1;
+}
+
+ + +
+ +
+ +
+
+ +
+

beware the break keyword to finish a case !

+ +
+
+
+
+ +
+

while loops

+
+
+ +
+ +
+ +
+ +
while (condition) {
+  instructions;
+}
+
+ + +
+ +
+ +
+
+
+
+ +
+

for loops:

+
+
+ +
+ +
+ +
+ +
for (init; test_condition; increment_instruction) {
+  instructions;
+}
+
+ + +
+ +
+ +
+
+ +
+ +
+ +
+ +
int res = 0;
+for (int a = 0; a < 10; ++a) {
+  res += a;
+}
+
+ + +
+ +
+ +
+
+
+
+ +
+

Functions

+
+
+ +
+ +
+ +
+ +
return_type function_name(type1 param1, type2 param2, ...) {
+  instructions;
+  return res;
+}
+
+ + +
+ +
+ +
+
+
+
+ +
+

Main function: entry point of any program.

+
+
+ +
+ +
+ +
+ +
int main(int argc, char ** argv){
+   ...
+}
+
+ + +
+ +
+ +
+
+ +
+

When you call your program like

+
> ./hello tata 12 67
+
+

argc is 4, and argv is a pointer of string (char array) containing "hello" "tata" "12" and "67"

+

wikipedia: main function

+ +
+
+ +
+

What is the memory structure of argv ?

+ +
+
+
+
+ +
+

Preprocessing macro

    +
  • Operation performed before compilation
  • +
  • Text replacement & macro-function
  • +
  • Include other files
  • +
+ +
+
+ +
+ +
+ +
+ +
#include "some_other_file.hh"
+#include <standard_header.hh>
+
+ + +
+ +
+ +
+
+ +
+
    +
  • define/undef
  • +
+ +
+
+ +
+ +
+ +
+ +
#define AVOGADRO 6.02214129e23
+instructions;
+
+#undef AVOGADRO
+
+ + +
+ +
+ +
+
+
+
+ +
+

Simple output to screen

+
+
+ +
+ +
+ +
+ +
#include <iostream>
+
+int main() {
+  int a = 1e6;
+  std::cout << "wanna have fun a " << a << " times" << std::endl;
+}
+
+ + +
+ +
+ +
+
+
+
+ +
+ +
+ +
+ +
#include <iostream>
+
+int main() {
+  int a = 1e6;
+  std::cout << "wanna have fun a " << a << " times" << std::endl;
+}
+
+ + +
+ +
+ +
+
+
+
+ +
+ +
+ +
+ +
#include <iostream>
+
+int main() {
+  int a = 1e6;
+  std::cout << "wanna have fun a " << a << " times" << std::endl;
+}
+
+ + +
+ +
+ +
+
+
+
+ +
+

Interactive session on (C++)

    +
  • Source files (.cc .cxx .cpp .hh .hpp convention)
  • +
  • CMake
  • +
  • Exercise to split a source file into header and implementation
  • +
  • Manipulating the argc and argv
  • +
  • Loops
  • +
  • Debugger GDB
  • +
  • Implementing the computation of pi in C++
  • +
+ +
+
+
+
+ +
+

Numbers

Integer numbers

Integers are numbers stored with a fixed number of bits

+
    +
  • char or unsigned char: 8bits (1 Byte) $[-128,127]$ or $[0,255]$
  • +
  • short or unsigned short: 16bits (2 Bytes) $[-2^{15},2^{15}-1]$ or $[0,2^{16}-1 = 65535]$
  • +
  • integer or unsigned int: 32bits (4 Bytes) $[-2^{31},2^{31}-1]$ or $[0,2^{32}-1 = 4294967295]$
  • +
+ +
+
+
+
+ +
+

Floating point numbers

Any floating point number in a computer are stored with the representation: +$$(-1)^s \times c \times b^q$$

+
    +
  • $(-1)^s$ is the sign ($s$ is its encoding)
  • +
  • $c$ is the significand, an integer
  • +
  • $b$ is the base
  • +
  • $q$ is an (integer) exponent
  • +
+ +
+
+
+
+ +
+

Standards (wikipedia: IEEE floating point standard)

    +
  • float (single) precision (4 Bytes = 32 bits), significand 24 bits ~ 7.22 decimal digits.
  • +
  • double precision (8 Bytes = 64 bits), significand 53 bits ~ 15.95 decimal digits.
  • +
  • long double (16 Bytes = 128 bits), significand 113 bits ~ 34.02 decimal digits.
  • +
+

wikipedia: floating point in modern computers

+ +
+
+ +
+
    +
  • Special values
      +
    • $\pm$ 0
    • +
    • $\pm$ inf
    • +
    • NaN (not a number)
    • +
    +
  • +
+ +
+
+ +
+
    +
  • Rounding problems (for demo assume 4 digits available)
      +
    • $1. + 10^{-4} = 1.$
    • +
    +
  • +
+ +
+
+
+
+ +
+

Interactive session Manipulating floating point numbers

    +
  • Casting from integer to float/double
  • +
  • Overflow
  • +
  • Underflow
  • +
+ +
+
+
+
+
+ + + + + + + diff --git a/lectures/week3.html b/lectures/week3.html new file mode 100644 index 0000000..0ebb536 --- /dev/null +++ b/lectures/week3.html @@ -0,0 +1,4478 @@ + + + + + + + + + + + +talk slides + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

git pull upstream master

+
+
+
+
+ +
+

Answer questions from
the previous session

+ +
+
+
+ +
+
+ +
+

Strings and Streams

+
+
+
+
+ +
+

std::string

    +
  • Strings are list of characters representation: include string
  • +
+ +
+
+ +
+ +
+ +
+ +
#include <iostream>
+#include <string>
+
+int main() {
+  std::string my_string = "test.plot";
+  std::cout << my_string << std::endl;
+}
+
+ + +
+ +
+ +
+
+
+
+ +
+

std::cout and std::cerr

    +
  • To use the std::cout, std::cerr, std::endl, std::flush features of the STL you have to include iostream
  • +
+ +
+
+ +
+ +
+ +
+ +
#include <iostream>
+
+ + +
+ +
+ +
+
+ +
+
    +
  • The object std::cout can be used to output things to screen via the so-called standard output channel
  • +
+ +
+
+ +
+ +
+ +
+ +
  std::cout << obj << std::endl;
+
+  std::cout << "flush now!" << std::flush << std::endl;
+
+ + +
+ +
+ +
+
+ +
+
    +
  • The error channel is accessible via the std::cerr (identical but no need to flush).
  • +
+ +
+
+ +
+ +
+ +
+ +
  std::cerr << obj << std::endl;
+
+ + +
+ +
+ +
+
+
+
+ +
+

std::scientific and std::setprecision

+ +
+
+ +
+ +
+ +
+ +
#include <iomanip>
+
+ + +
+ +
+ +
+
+ +
+ +
+ +
+ +
    
+  // for this output
+  std::cout << std::scientific 
+            << std::setprecision(15)
+            << M_PI << std::endl;
+
+ + +
+ +
+ +
+
+ +
+ +
+ +
+ +
  //permanent
+  std::cout.precision(15);
+  std::cout.setf(std::ios::scientific);
+
+ + +
+ +
+ +
+
+
+
+ +
+

std::ifstream / std::ofstream

    +
  • STL features to read/write files
  • +
+ +
+
+ +
+ +
+ +
+ +
#include <fstream>
+
+ + +
+ +
+ +
+
+ +
+ +
+ +
+ +
  std::ofstream fout("test.plot");
+  fout << M_PI << std::endl;
+  fout.close();
+
+ + +
+ +
+ +
+
+ +
+ +
+ +
+ +
  double pi_val;
+  std::ifstream fin("test.plot");
+  fin >> pi_val;
+
+ + +
+ +
+ +
+
+
+
+ +
+

std::stringstream

    +
  • Special stream: buffer is a string (and not a file)
  • +
+ +
+
+ +
+ +
+ +
+ +
#include <sstream>
+
+ + +
+ +
+ +
+
+ +
+ +
+ +
+ +
  std::stringstream sstr("1 2 3.14");
+  int i, j;
+  double k;
+
+  sstr >> i >> j >> k;
+  std::cout << i << " " << j << " " << k << std::endl;
+
+ + +
+ +
+ +
+
+ +
+ +
+ +
+ +
  std::stringstream sstr2;
+  sstr2 << 142;
+  std::cout << sstr2.str() << std::endl;
+
+ + +
+ +
+ +
+
+
+
+ +
+

std::stringstream

    +
  • Example: parsing the argc arguments using stringstream:
  • +
+ +
+
+ +
+ +
+ +
+ +
#include <sstream>
+
+int main(int argc, char **argv) {
+  std::stringstream sstr;
+  for (int i = 1; i < argc; ++i) {
+    sstr << argv[i] << " ";
+  }
+
+  double arg1;
+  sstr >> arg1;
+
+  int arg2;
+  sstr >> arg2;
+}
+
+ + +
+ +
+ +
+
+
+
+ +
+

Memory management

+
+
+
+
+ +
+

"Stack" memory allocation (static)

+
+
+ +
+ +
+ +
+ +
int main(int argc, char **argv) {
+
+  // static allocation
+  int vec[5];
+}
+
+ + +
+ +
+ +
+
+ +
+
    +
  • is this legit ?
  • +
+ +
+
+ +
+ +
+ +
+ +
double *get_vector(int n) {
+
+  double v[n];
+  for (int i = 0; i < n; i++)
+    v[i] = 10;
+  return v;
+}
+
+ + +
+ +
+ +
+
+
+
+ +
+

"Stack" memory allocation (static)

    +
  • Memory allocated available within the scope only (life duration)
  • +
  • Should be used for small arrays
  • +
  • Cannot make functions that create objects and return them (without a copy)
  • +
+ +
+
+
+
+ +
+

"Heap" memory allocation (dynamic)

    +
  • using the new keyword
  • +
  • life duration of allocated space: until delete
  • +
  • ommiting to delete: memory leak
  • +
+ +
+
+ +
+ +
+ +
+ +
double *get_scalar() {
+
+  double *v = new double;
+  return v;
+}
+
+ + +
+ +
+ +
+
+ +
+
    +
  • to use it beware to free/delete it:
  • +
+ +
+
+ +
+ +
+ +
+ +
  double *scalar = get_scalar();
+  // ... do what I need
+  delete scalar;
+
+ + +
+ +
+ +
+
+
+
+ +
+

"Heap" memory allocation (dynamic)

    +
  • using the new keyword for arrays
  • +
+ +
+
+ +
+ +
+ +
+ +
double *get_vector(int n) {
+
+  double *v = new double[n];
+  return v;
+}
+
+ + +
+ +
+ +
+
+ +
+ +
+ +
+ +
  double *vector = get_vector(10);
+  // ... do what I need
+  delete[] vector;
+
+ + +
+ +
+ +
+
+
+
+ +
+

Smart pointers: std::unique_ptr / std::shared_ptr

    +
  • Memory allocated on the heap needs to be freed
  • +
  • Forgetting is prone to memory leaks
  • +
  • Accessing freed memory: unknown result (Segmentation Fault usually)
  • +
+ +
+
+ +
+ + +
+
+
+
+ +
+ +
+ +
+ +
#include <iostream>
+#include <memory>
+
+std::unique_ptr<double> get_scalar() {
+  // create a unique pointer
+  return std::make_unique<double>(3);
+}
+
+int main() {
+
+  std::unique_ptr<double> ptr = get_scalar();
+  // ... do what I need like...
+  std::cout << *ptr;
+  // no need to delete scalar (will be automatically)
+
+  // cannot be copied => compilation error
+  // std::unique_ptr<double> ptr_copy = ptr;
+}
+
+ + +
+ +
+ +
+
+
+
+ +
+ +
+ +
+ +
#include <iostream>
+#include <memory>
+
+std::shared_ptr<double> get_vector(int n) {
+  return std::shared_ptr<double>(new double[n]);
+}
+
+int main() {
+
+  std::shared_ptr<double> ptr1 = get_vector(10);
+  std::shared_ptr<double> ptr2 = ptr1;
+
+  // memory of pointer freed when ptr1 and ptr2 are out of scope
+}
+
+ + +
+ +
+ +
+
+
+
+ +
+

Containers

+
+
+
+
+ +
+

std::array

    +
  • Arrays are sequence containers of fixed sizes
  • +
  • allocation is made on the stack
  • +
+ +
+
+ +
+ +
+ +
+ +
#include <array>
+
+ + +
+ +
+ +
+
+ +
+ +
+ +
+ +
  std::array<double, 3> vec;
+  vec[2] = 10.;
+
+  std::array<std::string, 10> vec2;
+  vec2[8] = "mars";
+
+ + +
+ +
+ +
+
+
+
+ +
+

std::vector

    +
  • Vectors are sequence containers representing arrays that can change in size
  • +
  • The memory is stored contiguously in the heap
  • +
  • Resizing needs reallocation (and possibly copy) which is a demanding operation.
  • +
+ +
+
+ +
+ +
+ +
+ +
#include <vector>
+
+ + +
+ +
+ +
+
+ +
+ +
+ +
+ +
  std::vector<double> vec(10);
+  vec.resize(100);
+
+ + +
+ +
+ +
+
+
+
+ +
+

std::set

    +
  • Sets are ensemble of unique objects
  • +
+ +
+
+ +
+ +
+ +
+ +
#include <set>
+
+ + +
+ +
+ +
+
+ +
+ +
+ +
+ +
  std::set<int> set1;
+  set1.insert(100);
+  set1.insert(101);
+  set1.insert(101);
+  set1.erase(100);
+
+ + +
+ +
+ +
+
+
+
+ +
+

loops over containers

+
+
+ +
+ +
+ +
+ +
  std::vector<int> vec(10);
+  for (int i = 0; i < 10; ++i) {
+    vec[i] = 10;
+  }
+
+ + +
+ +
+ +
+
+ +
+ +
+ +
+ +
  std::array<int, 10> array;
+  for (int i = 0; i < 10; ++i) {
+    array[i] = 10;
+  }
+
+ + +
+ +
+ +
+
+
+
+ +
+

iterators

    +
  • loops agnostic to container type: using iterators
  • +
+ +
+
+ +
+ +
+ +
+ +
    // vector loop with iterators
+    std::vector<int>::iterator it = vec.begin();
+    std::vector<int>::iterator end = vec.end();
+    for (; it != end; ++it) {
+      *it = 10.;
+    }
+
+ + +
+ +
+ +
+
+ +
+ +
+ +
+ +
    // with the auto
+    auto it = vec.begin();
+    auto end = vec.end();
+    for (; it != end; ++it) {
+      *it = 10.;
+    }
+
+ + +
+ +
+ +
+
+ +
+ +
+ +
+ +
    // with the range loop
+    for (auto &v : vec) {
+      v = 10.;
+    }
+
+ + +
+ +
+ +
+
+
+
+ +
+

Access costs

    +
  • For std::vector, the complexities are

    +
      +
    • random access: $O(1)$
    • +
    • insertion/deletion: $O(N)$
    • +
    • insertion/deletion from ends: $O(1)$
    • +
    +
  • +
  • Whereas for std::list:

    +
      +
    • random access: $O(N)$
    • +
    • insertion/deletion: $O(1)$
    • +
    +
  • +
+ +
+
+
+
+ +
+

std::map

    +
  • Maps allow to associate uniquely a value of any type to a value of any type
  • +
+ +
+
+ +
+ +
+ +
+ +
#include <map>
+
+int main() {
+
+  std::map<std::string, double> particle_mass;
+
+  particle_mass["mars"] = 6.4171e23;
+  particle_mass["sun"] = 1.9885e30;
+  particle_mass["copper"] = 1.0552061e-25;
+}
+
+ + +
+ +
+ +
+
+
+
+ +
+

std::algorithms

There are many STL algorithms available.

+

For instance three of them are presented below:

+
    +
  • std::find searches for a match in a container in $O(N)$ advances
  • +
  • std::sort sorts a container +in $N*log2(N)$ swaps (which then is not the same for list, vectors)

    +
  • +
  • std::binary_search searches into a sorted container in $O(log2(N))$ advances +(which is then long for non random access iterators like lists)

    +
  • +
  • std::set_intersection returns the intersection between sets
  • +
+ +
+
+
+
+ +
+

Lambda expressions and Functors

+
+
+
+
+ +
+

lambda expressions

    +
  • A lambda function is an unnamed function object capable of capturing variables in scope
  • +
+ +
+
+ +
+ +
+ +
+ +
void foo1() { std::cout << "Hey" << std::endl; }
+
+ + +
+ +
+ +
+
+ +
+ +
+ +
+ +
  // call a standard function
+  foo1();
+
+ + +
+ +
+ +
+
+ +
+
    +
  • declaration and call of a functor
  • +
+ +
+
+ +
+ +
+ +
+ +
  auto foo2 = []() { std::cout << "Hey again !" << std::endl; };
+
+  foo2();
+
+ + +
+ +
+ +
+
+
+
+ +
+

lambda expressions

    +
  • lambda with parameters
  • +
+ +
+
+ +
+ +
+ +
+ +
  auto foo3 = [](int a, double b) { std::cout << a << "," << b << std::endl; };
+
+  foo3(10, 102.3);
+
+ + +
+ +
+ +
+
+
+
+ +
+

lambda expressions

    +
  • capturing a variable
  • +
+ +
+
+ +
+ +
+ +
+ +
  int toto = 2;
+  // captures 'toto' variable
+  auto foo4 = [toto]() { std::cout << toto << std::endl; };
+
+ + +
+ +
+ +
+
+ +
+ +
+ +
+ +
  // captures all in current scope
+  auto foo5 = [&]() { std::cout << toto << std::endl; };
+
+  foo5();
+
+ + +
+ +
+ +
+
+
+
+ +
+

lambda expressions

    +
  • return a value
  • +
+ +
+
+ +
+ +
+ +
+ +
  // explicit declaration
+  auto foo6 = []() -> int { return 19; };
+  auto res = foo6();
+
+  // implicit declaration
+  auto foo7 = []() { return 19.3; };
+  auto res2 = foo7();
+
+ + +
+ +
+ +
+
+
+
+ + +
+ +
+ +
+ +
+ +
  std::vector<int> vec(10);
+
+  // indirect call
+  auto foo = [](auto &v) { std::cout << v; };
+  std::for_each(vec.begin(), vec.end(), foo);
+
+  // inline call
+  std::for_each(vec.begin(), vec.end(), [](auto &v) { v += 1; });
+
+  // storing result in another array
+  std::vector<int> res;
+  std::transform(vec.begin(), vec.end(), std::back_inserter(res),
+                 [](auto &val) { return val + 1; });
+
+ + +
+ +
+ +
+
+
+
+ +
+

Interactive session on STL

    +
  • string
  • +
  • streams
  • +
  • containers
  • +
  • algorithms
  • +
  • lambda
  • +
  • smart pointers
  • +
+ +
+
+
+
+
+ + + + + + + diff --git a/lectures/week4.html b/lectures/week4.html new file mode 100644 index 0000000..9674827 --- /dev/null +++ b/lectures/week4.html @@ -0,0 +1,863 @@ + + + + + + + + + + + +talk slides + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
+
+
+
+ +
+

git pull upstream master

+
+
+
+
+ +
+

Answer questions from
the previous session

+ +
+
+
+
+ +
+

Python complements

+
+
+
+
+ +
+

Default parameters of functions

def foo(a, b=1):
+   return a+b
+
+ +
+
+ +
+

args and kwargs

    +
  • args: list containing un-named arguments
  • +
  • kwargs: dictionary containing the named arguments
  • +
+
def foo(a, *args, **kwargs):
+    print('args:', args)
+    print('kwrags:', kwargs)
+    return a+1
+
+foo(1, 2, 3, toto=3, tata=4)
+
+ +
+
+
+
+ +
+

lambda functions: for_each

def foo(a):
+    print(a*10)
+
+l = range(1, 4)
+
+def for_each(_list, func):
+    for i in _list:
+        func(i)
+
+for_each(l, foo)
+for_each(l, lambda x: print(x*10))
+
+ +
+
+ +
+

lambda functions: transform

applied = [foo(i) for i in l]
+applied = [(lambda x: x*10)(i) for i in l]
+
+ +
+
+
+
+ +
+

Numpy

Numpy reference

+
import numpy as np
+
+ +
+
+
+
+ +
+

Creating multi-dimentional array zero-filled

m = np.zeros((2,3))
+
+ +
+
+ +
+

Creating multi-dimentional array from list/tuple

l = [[1,2,3],[4,5,6],[7,8,9]]
+m = np.array(l)
+
+t = ((1,2,3),(4,5,6),(7,8,9))
+m = np.array(t)
+
+ +
+
+
+
+ +
+

Creating special matrix

# Identity matrix
+m = np.eye(3)
+np.ones((2,3))
+# diagonal matrix
+m = np.diag((2,3,4))
+# random matrix
+np.random.rand(2,3)
+
+ +
+
+
+
+ +
+

Numpy Slicing

m = np.random.rand(4)
+
+
    +
  • Slicing syntax: m[start:end:stride]
  • +
+ +
+
+ +
+
m[2] # access index 2
+m[-1] # access last index
+m[:2] # sub vector m[0],m[1]
+m[1:] # access m[1], m[2], m[3]
+m[::2] # access even indexes
+m[1::2] # access odd indexes
+m[::-1,:] # access in decreasing order
+
+ +
+
+
+
+ +
+

Component-based algebra

m = np.ones((3,3))
+
+#component by component operation
+n = m*2
+print(m,n)
+print(m+n)
+print(m*n)
+print(m+1)
+print((m-n)**2))
+
+ +
+
+
+
+ +
+

Scipy linear algebra routines

m = np.array([[1,2,3],[4,5,6],[7,8,9]])
+n = np.array([[1,0,0],[0,1,0],[0,0,1]])
+v = np.array([1,1,1])
+
+# matrix-matrix operation
+np.dot(m,n)
+
+# matrix-vector operation
+np.dot(m,v)
+np.dot(v,m)
+np.dot(v,v)
+
+#matrix inversion
+np.linalg.inv(m)
+
+ +
+
+
+
+ +
+

Numpy summations

m = np.array([[1,2,3],[4,5,6],[7,8,9]])
+
+
    +
  • $\sum_{i,j} m_{ij}$

    +
    m.sum()
    +
    +
  • +
  • $\sum_{i} m_{ij}$ and $\sum_{j} m_{ij}$

    +
  • +
+
m.sum(axis=0)
+m.sum(axis=1)
+
+
    +
  • norm: $\sqrt{\sum_{ij} m_{ij}^2}$
  • +
+
np.sqrt((m**2).sum())
+
+ +
+
+
+
+ +
+

Einsum

    +
  • Tensor product with einstein notation
  • +
  • mat-vec product: $u_i = m_{ik} v_k$
  • +
+
u = np.einsum('ik,k->i', m, v)
+
+
    +
  • dot product: $norm = v_k v_k$
  • +
+
norm = np.einsum('k,k->', v, v)
+
+
    +
  • Transposition
  • +
+
np.einsum('ij->ji', m)
+
+ +
+
+
+
+ +
+

Scipy optimization

import scipy.optimize
+
+# with a lambda
+ret = scipy.optimize.minimize(lambda x: ((x-1)**2).sum(),
+                              0.,
+                              tol=1e-9)
+
+ +
+
+ +
+
# without a lambda
+def foo(x,center):
+    return (x-center)**2 
+
+ret = scipy.optimize.minimize(foo, 0., args=[1, ],
+                              tol=1e-9)
+
+ +
+
+
+
+ +
+
def foo(x,center):
+    return (x-center)**2 
+
+ret = scipy.optimize.minimize(foo, 0., args=[1, ],
+                              tol=1e-9)
+
+
    +
  • Return of the function gives information about the convergence:
  • +
+ +
+
+ +
+ +
+ + +
+
      fun: 5.5507662238258444e-17
+ hess_inv: array([[0.5]])
+      jac: array([4.68181046e-13])
+  message: 'Optimization terminated successfully.'
+     nfev: 9
+      nit: 2
+     njev: 3
+   status: 0
+  success: True
+        x: array([0.99999999])
+
+ +
+ +
+
+
+
+ +
+

Matplotlib

    +
  • 2D/3D plotting library
  • +
  • publication quality figures
  • +
  • Combined with Numpy/Scipy: gets post-treatment close to figure scripts
  • +
+
import matplotlib.pyplot as plt
+
+ +
+
+
+
+ +
+

Figure&Axe creation

# Figure object
+fig = plt.figure()
+# Axe object
+axe = fig.add_subplot(nrows, ncols, n_plot)
+
+
    +
  • Assumes a grid of plots $nrows \times ncols$
  • +
  • Returns plot asociated to n_plot (row major count)

    +
  • +
  • For a single plot:

    +
    axe = fig.add_subplot(1,1,1)
    +axe = fig.add_subplot(111)
    +
    +
  • +
+ +
+
+
+
+ +
+

The plot function

    +
  • takes 2 numpy arrays, one for x one for y
  • +
+
x = np.arange(0,10)
+y = x**2
+axe.plot(x,y)
+
+# Display/Save figures
+plt.show()
+plt.savefig("figure.pdf")
+
+ +
+
+ +
+ +
+ + +
+ +
+ +
+ +
+
+ +
+
import numpy as np
+import matplotlib.pyplot as plt
+%matplotlib inline
+
+x = np.arange(0,10)
+y = x**2
+fig = plt.figure()
+axe = fig.add_subplot(111)
+ret = axe.plot(x,y)
+
+ +
+
+
+
+ +
+

Axes labels

axe.set_xlabel("X axis")
+axe.set_ylabel("$X^2$")
+
+

Axes ranges

axe.set_ylim((ymin,ymax))
+axe.set_xlim((xmin,xmax))
+
+ +
+
+ +
+ +
+ + +
+ +
+ +
+ +
+
+
+
+ +
+

Curves legend

x = np.arange(0,10)
+y1 = x**2
+y2 = x**3
+y3 = x**4
+axe.plot(x,y1,label="$x^2$")
+axe.plot(x,y2,label="$x^3$")
+axe.plot(x,y3,label="$x^4$")
+axe.legend()
+
+ +
+
+ +
+ +
+ + +
+ +
+ +
+ +
+
+
+
+ +
+

Line style

#line only
+axe.plot(x,y1,'-',
+         label="$x^2$")
+
+#points only
+axe.plot(x,y2,'o',
+         label="$x^2$")
+
+#lines points
+axe.plot(x,y3,'o-',
+         label="$x^2$")
+
+ +
+
+ +
+ +
+ + +
+ +
+ +
+ +
+
+
+
+ +
+

Axes 3D

import matplotlib.pyplot as plt
+from mpl_toolkits.mplot3d import Axes3D
+
+fig = plt.figure()
+axe = Axes3D(fig)
+
+ +
+
+ +
+
theta = np.linspace(
+    -4 * np.pi, 4 * np.pi, 
+    100)
+z = np.linspace(-2, 2, 100)
+r = z**2 + 1
+x = r * np.sin(theta)
+y = r * np.cos(theta)
+axe.plot(x, y, z)
+
+ +
+
+ +
+ +
+ + +
+ +
+ +
+ +
+
+
+ +
+
+
+ + + + + + + diff --git a/work/.gitignore b/work/.gitignore new file mode 100644 index 0000000..6e2019d --- /dev/null +++ b/work/.gitignore @@ -0,0 +1,249 @@ + +# Created by https://www.gitignore.io/api/c++,cmake,linux,python,windows,sublimetext + +### C++ ### +# Prerequisites +*.d + +# Compiled Object files +*.slo +*.lo +*.o +*.obj + +# Precompiled Headers +*.gch +*.pch + +# Compiled Dynamic libraries +*.so +*.dylib +*.dll + +# Fortran module files +*.mod +*.smod + +# Compiled Static libraries +*.lai +*.la +*.a +*.lib + +# Executables +*.exe +*.out +*.app + +### CMake ### +CMakeCache.txt +CMakeFiles +CMakeScripts +Testing +Makefile +cmake_install.cmake +install_manifest.txt +compile_commands.json +CTestTestfile.cmake + +### Linux ### +*~ + +# temporary files which can be created if a process still has a handle open of a deleted file +.fuse_hidden* + +# KDE directory preferences +.directory + +# Linux trash folder which might appear on any partition or disk +.Trash-* + +# .nfs files are created when an open file is removed but is still being accessed +.nfs* + +### Python ### +# Byte-compiled / optimized / DLL files +__pycache__/ +*.py[cod] +*$py.class + +# C extensions + +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +*.egg-info/ +.installed.cfg +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec + +# Installer logs +pip-log.txt +pip-delete-this-directory.txt + +# Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ +.coverage +.coverage.* +.cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ + +# Translations +*.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject + +# Rope project settings +.ropeproject + +# mkdocs documentation +/site + +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json + +### Python Patch ### +.venv/ + +### Python.VirtualEnv Stack ### +# Virtualenv +# http://iamzed.com/2009/05/07/a-primer-on-virtualenv/ +[Bb]in +[Ii]nclude +[Ll]ib +[Ll]ib64 +[Ll]ocal +[Ss]cripts +pyvenv.cfg +pip-selfcheck.json + +### SublimeText ### +# Cache files for Sublime Text +*.tmlanguage.cache +*.tmPreferences.cache +*.stTheme.cache + +# Workspace files are user-specific +*.sublime-workspace + +# Project files should be checked into the repository, unless a significant +# proportion of contributors will probably not be using Sublime Text +.sublime-project + +# SFTP configuration file +sftp-config.json + +# Package control specific files +Package Control.last-run +Package Control.ca-list +Package Control.ca-bundle +Package Control.system-ca-bundle +Package Control.cache/ +Package Control.ca-certs/ +Package Control.merged-ca-bundle +Package Control.user-ca-bundle +oscrypto-ca-bundle.crt +bh_unicode_properties.cache + +# Sublime-github package stores a github token in this file +# https://packagecontrol.io/packages/sublime-github +GitHub.sublime-settings + +### Windows ### +# Windows thumbnail cache files +Thumbs.db +ehthumbs.db +ehthumbs_vista.db + +# Dump file +*.stackdump + +# Folder config file +[Dd]esktop.ini + +# Recycle Bin used on file shares +$RECYCLE.BIN/ + +# Windows Installer files +*.cab +*.msi +*.msix +*.msm +*.msp + +# Windows shortcuts +*.lnk + + +# End of https://www.gitignore.io/api/c++,cmake,linux,python,windows,sublimetext \ No newline at end of file diff --git a/work/week1/git/auto/sujet.el b/work/week1/git/auto/sujet.el new file mode 100644 index 0000000..4b83741 --- /dev/null +++ b/work/week1/git/auto/sujet.el @@ -0,0 +1,16 @@ +(TeX-add-style-hook + "sujet" + (lambda () + (TeX-add-to-alist 'LaTeX-provided-class-options + '(("article" "a4paper" "11pt"))) + (TeX-run-style-hooks + "latex2e" + "../td" + "article" + "art11") + (TeX-add-symbols + '("mycomment" 1)) + (LaTeX-add-environments + '("exercice" LaTeX-env-args ["argument"] 0))) + :latex) + diff --git a/work/week1/git/sujet.pdf b/work/week1/git/sujet.pdf new file mode 100644 index 0000000..fa2563d Binary files /dev/null and b/work/week1/git/sujet.pdf differ diff --git a/work/week1/python-hello/sources/hello.py b/work/week1/python-hello/sources/hello.py new file mode 100644 index 0000000..b31f50f --- /dev/null +++ b/work/week1/python-hello/sources/hello.py @@ -0,0 +1,26 @@ +import sys + + +# 1 +print("Hello World") +print(len(sys.argv)) +print(type(sys.argv)) # sys.argv is a list + +# 2 +n = int(sys.argv[1]) +print("Hello {}".format(n)) + +# 3 +n = int(sys.argv[1]) +s = 0 +for k in range(1, n + 1): # n additions are necessary + s += k +print("Hello {}".format(s)) +# overhead? + +# 4 +n = int(sys.argv[1]) +s = 0 +for k in range(1, n + 1): + s += k +print("Hello {}".format(s)) diff --git a/work/week1/python-hello/sources/main.py b/work/week1/python-hello/sources/main.py new file mode 100644 index 0000000..c4a3f08 --- /dev/null +++ b/work/week1/python-hello/sources/main.py @@ -0,0 +1,5 @@ +import sys +from series import computeSeries + +n = int(sys.argv[1]) +print("Hello {}".format(computeSeries(n))) diff --git a/work/week1/python-hello/sources/series.py b/work/week1/python-hello/sources/series.py new file mode 100644 index 0000000..32942d5 --- /dev/null +++ b/work/week1/python-hello/sources/series.py @@ -0,0 +1,7 @@ + + +def computeSeries(Niterations): + s = 0 + for k in range(1, Niterations + 1): # n additions are necessary + s += k + return s diff --git a/work/week1/python-hello/sujet.pdf b/work/week1/python-hello/sujet.pdf new file mode 100644 index 0000000..569acb7 Binary files /dev/null and b/work/week1/python-hello/sujet.pdf differ diff --git a/work/week1/test.cpp b/work/week1/test.cpp new file mode 100644 index 0000000..2b78be9 --- /dev/null +++ b/work/week1/test.cpp @@ -0,0 +1 @@ +// This is a test file for SP4E class \ No newline at end of file diff --git a/work/week2/float/sources/CMakeLists.txt b/work/week2/float/sources/CMakeLists.txt new file mode 100644 index 0000000..4115451 --- /dev/null +++ b/work/week2/float/sources/CMakeLists.txt @@ -0,0 +1,4 @@ +cmake_minimum_required(VERSION 2.6) +project(hello-exercise) + +add_executable(main main.cc) diff --git a/work/week2/float/sources/main.cc b/work/week2/float/sources/main.cc new file mode 100644 index 0000000..d3fbf70 --- /dev/null +++ b/work/week2/float/sources/main.cc @@ -0,0 +1,102 @@ +/* -------------------------------------------------------------------------- */ +#include +#include +#include +/* -------------------------------------------------------------------------- */ + +void ex1(){ + std::cout << "EXERCISE 1" << std::endl; + + int a = 0.5; + std::cout << a << std::endl; + // conversion from double to int + + double a2 = 1/2; + std::cout << a2 << std::endl; + // Using int variables to "make it double" + + // It does not happen in python because of dynamic typing. +} + + +double tanhx(double x){ + return (exp(x) - exp(-x)) / (exp(x) + exp(-x)); +} + +double tanhx2(double x){ + return (1 - exp(-2 * x)) / (1 + exp(-2 * x)); +} + +double tanhx3(double x){ + return (2 * exp(-2 * x)) / (1 + exp(-2 * x)); +} + +void ex2(){ + std::cout << "EXERCISE 2" << std::endl; + + double x = 10.; + double a = exp(x); + std::cout << "x = " << x << ", exp(x) = " << a << std::endl; + + for (double x = 0; x< 1000; x += 100){ + std::cout << "x = " << x << + ": tanh(x) = " << tanhx(x) << + ", tanhx2(x) = " << tanhx2(x) << + ", tanhx3(x) = " << tanhx3(x) << std::endl; + } +} + +double evolution(double pn, double v, double dt){ + return (pn + dt *v); +} + +void ex3(){ + std::cout << "EXERCISE 3" << std::endl; + + double v = 3e8; + double p0 = 0; + double p1 = 1e-3; + double dt = 1000; + for (int i = 0; i < 40; i++){ + p0 = evolution(p0, v, dt); + p1 = evolution(p1, v, dt); + std::cout << "Cycle " << i << + ": P0 = " << p0 << ", P1 = " << p1 << + ", distance = " << p1 - p0 << std::endl; + } + // Initially, p0 and p1 are very small numbers hence the computer can + // compute their distance accurately. + // As the photons evolve, p0 and p1 become very big, the subtraction p1 - p0 + // loses information about their smallest decimals, hence their distance + // is approximated as zero. +} + + +int main(int argc, char ** argv){ + + int n = 0; + if (argc > 1) { + n = atoi(argv[1]); + } + + switch (n) { + case 0: + ex1(); + ex2(); + ex3(); + break; + case 1: + ex1(); + break; + case 2: + ex2(); + break; + case 3: + ex3(); + break; + default: + std::cout << "Unkown exercise ID: " << n << std::endl; + } + + return EXIT_SUCCESS; +} diff --git a/work/week2/float/sujet.pdf b/work/week2/float/sujet.pdf new file mode 100644 index 0000000..21d03ac Binary files /dev/null and b/work/week2/float/sujet.pdf differ diff --git a/work/week2/hello/sources/CMakeLists.txt b/work/week2/hello/sources/CMakeLists.txt new file mode 100644 index 0000000..8c8e534 --- /dev/null +++ b/work/week2/hello/sources/CMakeLists.txt @@ -0,0 +1,4 @@ +cmake_minimum_required(VERSION 2.6) +project(hello-exercise) + +add_executable(hello hello.cc series.cc) diff --git a/work/week2/hello/sources/hello.cc b/work/week2/hello/sources/hello.cc new file mode 100644 index 0000000..6b1ad29 --- /dev/null +++ b/work/week2/hello/sources/hello.cc @@ -0,0 +1,33 @@ +#include +#include +#include +#include "series.hh" +/* -------------------------------------------------------------------------- */ + + +int main(int argc, char ** argv) { + + // Hello N + std::cout << "type of argc is: " << typeid(argc).name() << std::endl; + std::cout << "type of argv is: " << typeid(argv).name() << std::endl; + std::cout << "Number of inputs: " << argc - 1 << "\n"; + int n; + if (argc > 1) { + n = atoi(argv[1]); + } else { + n = 0; + } + std::cout << "Hello " << n << std::endl; + + // Print result from series (n operations necessary) + int S = 0; + for (int k = 1; k < n + 1; ++k) { + S += k; + } + std::cout << "main: S" << n << " = " << S << "\n"; + + // Print result from serie using function + std::cout << "computeSeries: S" << n << " = " << computeSeries(n) << "\n"; + + return EXIT_SUCCESS; +} diff --git a/work/week2/hello/sources/series.cc b/work/week2/hello/sources/series.cc new file mode 100644 index 0000000..5a55d74 --- /dev/null +++ b/work/week2/hello/sources/series.cc @@ -0,0 +1,9 @@ +#include "series.hh" + +int computeSeries(int n) { + int S = 0; + for (int k = 1; k < n + 1; ++k) { + S += k; + } + return S; +} diff --git a/work/week2/hello/sources/series.hh b/work/week2/hello/sources/series.hh new file mode 100644 index 0000000..7ee6a21 --- /dev/null +++ b/work/week2/hello/sources/series.hh @@ -0,0 +1,6 @@ +#ifndef SERIES_HH +#define SERIES_HH + +int computeSeries(int n); + +#endif diff --git a/work/week2/hello/sujet.pdf b/work/week2/hello/sujet.pdf new file mode 100644 index 0000000..0cc7b5e Binary files /dev/null and b/work/week2/hello/sujet.pdf differ diff --git a/work/week2/pi/sources/CMakeLists.txt b/work/week2/pi/sources/CMakeLists.txt new file mode 100644 index 0000000..4115451 --- /dev/null +++ b/work/week2/pi/sources/CMakeLists.txt @@ -0,0 +1,4 @@ +cmake_minimum_required(VERSION 2.6) +project(hello-exercise) + +add_executable(main main.cc) diff --git a/work/week2/pi/sources/main.cc b/work/week2/pi/sources/main.cc new file mode 100644 index 0000000..e2965dd --- /dev/null +++ b/work/week2/pi/sources/main.cc @@ -0,0 +1,61 @@ +/* -------------------------------------------------------------------------- */ +#include +#include +#include +#include +/* -------------------------------------------------------------------------- */ + +int main(int argc, char ** argv){ + + int precision = 20; + + // Number of iterations + int n; + int nmax = 1e7; + if (argc > 1) { + n = atoi(argv[1]); + if (n > nmax) { + std::cout << "\033[31m" << "Warning: n = " << + n << " is too high -> setting n = " << nmax << + "\033[0m" << std::endl; + n = nmax; + } + } else { + n = 10; + } + + // Normal Pi computation + float sum = 0; + for (float k = 1; k < n + 1; k++){ + sum = sum + 1 / (k * k); + // std::cout<< std::fixed << std::setprecision(precision) + // << "k = " << k << ", PI = " << sqrt(6 * sum) << std::endl; + } + float pi = sqrt(6 * sum); + std::cout<< std::fixed << std::setprecision(precision) + << n << " iterations (normal): PI = " << pi << std::endl; + + // Reversed Pi computation + sum = 0; + for (float k = n; k > 0; k--){ + sum = sum + 1/(k*k); + // std::cout<< std::fixed << std::setprecision(precision) + // << "k = " << k << ", PI = " << sqrt(6 * sum) << std::endl; + } + float rev_pi = sqrt(6 * sum); + std::cout<< std::fixed << std::setprecision(precision) + << n << " iterations (reversed): PI = " << rev_pi << std::endl; + + std::string str; + if (abs(pi - M_PI) < abs(rev_pi - M_PI)) { + str = "normal"; + } else { + str = "reversed"; + } + std::cout << str << " computation is more accurate" << std::endl; + + return EXIT_SUCCESS; +} + + + diff --git a/work/week2/pi/sujet.pdf b/work/week2/pi/sujet.pdf new file mode 100644 index 0000000..0a24237 Binary files /dev/null and b/work/week2/pi/sujet.pdf differ diff --git a/work/week3/stl/starting_point/CMakeLists.txt b/work/week3/stl/starting_point/CMakeLists.txt new file mode 100644 index 0000000..3ebe8b8 --- /dev/null +++ b/work/week3/stl/starting_point/CMakeLists.txt @@ -0,0 +1,11 @@ +cmake_minimum_required(VERSION 2.6) +set (CMAKE_CXX_FLAGS "${CMAKE_CXX_FLAGS} -std=c++14") + +add_executable(ex1 ex1.cc) +add_executable(ex2 ex2.cc) +add_executable(ex3 ex3.cc) +add_executable(memory_first memory_first.cc) +add_executable(memory_second memory_second.cc) +add_executable(memory_third memory_third.cc) +add_executable(ex5 ex5.cc) +add_executable(ex6 ex6.cc) \ No newline at end of file diff --git a/work/week3/stl/starting_point/empty_main.cc b/work/week3/stl/starting_point/empty_main.cc new file mode 100644 index 0000000..7610223 --- /dev/null +++ b/work/week3/stl/starting_point/empty_main.cc @@ -0,0 +1,19 @@ +#include +#include +#include +#include +#include +#include +#include +#include +/* -------------------------------------------------------------------------- */ + + +int main(int argc, char ** argv){ + + + return EXIT_SUCCESS; +} + + + diff --git a/work/week3/stl/starting_point/ex1.cc b/work/week3/stl/starting_point/ex1.cc new file mode 100644 index 0000000..9dd7516 --- /dev/null +++ b/work/week3/stl/starting_point/ex1.cc @@ -0,0 +1,29 @@ +#include +#include +#include +#include +#include +#include +#include +#include +/* -------------------------------------------------------------------------- */ + + +int main(int argc, char ** argv){ + std::string myName = "TNErocks"; + if (argc > 1) { + std::string argument = std::string(argv[1]); + if (argument == myName){ + std::cout << "You are a rockstar" << std::endl; + } else { + std::cout << "You are a NOT rockstar" << std::endl; + } + } else { + std::cout << "You are nothing" << std::endl; + } + + return EXIT_SUCCESS; +} + + + diff --git a/work/week3/stl/starting_point/ex2.cc b/work/week3/stl/starting_point/ex2.cc new file mode 100644 index 0000000..0fdcacd --- /dev/null +++ b/work/week3/stl/starting_point/ex2.cc @@ -0,0 +1,58 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +/* -------------------------------------------------------------------------- */ + +void write(const char * filename, double x, double y, double z) { + // write 3D point to file + std::ofstream fout(filename); + std::cout << "Writing coordinates (" << x << ", " << y << ", " << z << + ") into " << filename << std::endl; + fout << x << " " << y << " " << z; + fout.close(); +} + +void read(const char * filename) { + // read 3D point from file + std::ifstream fin(filename); + std::stringstream ss; + ss << fin.rdbuf(); + double x, y, z; + ss >> x >> y >> z; + std::cout << "Reading coordinates from " << filename << ": (" << + x << ", " << y << ", " << z << ")" << std::endl; +} + +int main(int argc, char ** argv){ + + const char* filename = "toto.txt"; + double x, y, z; + if (argc == 4) { // x, y, z provided + x = atof(argv[1]); + y = atof(argv[2]); + z = atof(argv[3]); + } else if (argc == 1) { // x, y, z not provided + x = 1.7; + y = 1.0; + z = 2.0; + } else { + std::cout << "\033[31m" << "Invalid number of arguments: " << argc << + "\033[0m" << std::endl; + return 0; + } + + write(filename, x, y, z); + read(filename); + + return EXIT_SUCCESS; +} + + + + diff --git a/work/week3/stl/starting_point/ex3.cc b/work/week3/stl/starting_point/ex3.cc new file mode 100644 index 0000000..841f45c --- /dev/null +++ b/work/week3/stl/starting_point/ex3.cc @@ -0,0 +1,72 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +/* -------------------------------------------------------------------------- */ + + +int main(int argc, char ** argv){ + + // read 3D point from file into array + const char* filename = "toto.txt"; + std::ifstream fin(filename); + std::stringstream ss; + ss << fin.rdbuf(); + std::array arr; + for (int i = 0; i < 3; ++i) { + ss >> arr[i]; + } + std::cout << "Reading coordinates from " << filename << " into array: "; + for (const auto& e : arr){ + std::cout << e << " "; + } + std::cout << std::endl; + + // vector: 100 values from 0 to 2 PI + std::vector vec; + int size = 100; + for (int i = 0; i < size; ++i){ + vec.push_back(2.0 * M_PI / (size - 1) * i); + } + std::cout << "vec = " << vec.size() << " elements vector ranging from " << + vec[0] << " to " << vec[size - 1] << std::endl; + + // resize to 200 values -> indexes 100 to 199 are assigned to 0 + vec.resize(2 * size); + std::cout << "vec resized to " << vec.size() << " elements. " << + "New elements contain the value " << vec[size] << std::endl; + /* the "assign" method would assign new content to the vector, replacing its current content, + and modifying its size accordingly. */ + vec.resize(size); + std::cout << "vec resized to " << vec.size() << " elements " << std::endl; + + // Generate sinus vector + std::vector> sin_vect; + for (int i = 0; i < 100; ++i) { + sin_vect.push_back(std::make_pair(vec[i], sin(vec[i]))); + } + std::cout << "sin_vect = " << sin_vect.size() << " pairs vector ranging from (" << + sin_vect[0].first << ", " << sin_vect[0].second << ") to (" << + sin_vect[size - 1].first << ", " << sin_vect[size -1].second << ")" << std::endl; + + // Output sinus vector to text file + filename = "sinus.csv"; + std::ofstream fout(filename); + for (int i = 0; i < size; ++i) { + fout << std::scientific << std::setprecision(20) << + sin_vect[i].first << ',' << sin_vect[i].second << std::endl; + } + fout.close(); + std::cout << "outputed sinus vector to " << filename << std::endl; + + return EXIT_SUCCESS; +} + + + diff --git a/work/week3/stl/starting_point/ex5.cc b/work/week3/stl/starting_point/ex5.cc new file mode 100644 index 0000000..08a06c8 --- /dev/null +++ b/work/week3/stl/starting_point/ex5.cc @@ -0,0 +1,109 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +/* -------------------------------------------------------------------------- */ + + +std::string printPoint(std::array p) { + char buffer[256]; + std::snprintf(buffer, sizeof(buffer), "(%.1f, %.1f, %.1f)", p[0], p[1], p[2]); + std::string s(buffer); + return s; +} + +void addToMap(std::map> &map, + std::string key, std::array p) { + std::map>::iterator it = map.find(key); + if (it != map.end()) { + std::cout << "Warning: " << it->first << " already in the map" << std::endl; + } else { + std::cout << "Adding " << key << ": " << printPoint(p) << " to map" << std::endl; + map[key] = p; + } +} + +void printMap(std::map> map) { + for (auto const &e : map) { + std::cout << e.first << ": " << printPoint(e.second) << std::endl; + } +} + +std::set map2Set(std::map> map) { + std::set set; + for (auto const &e : map) { + set.insert(e.first); + } + return set; +} + +std::set intersectSets(std::set set1, std::set set2) { + std::set set3; + std::set_intersection(set1.begin(), set1.end(), + set2.begin(), set2.end(), + std::inserter(set3, set3.begin())); + return set3; +} + +std::map> intersectMaps( + std::map> map1, + std::map> map2) { + std::set set = intersectSets(map2Set(map1), map2Set(map2)); + std::map> map; + for (auto const &e : set) { + map[e] = map1[e]; + } + return map; +} + +int main(int argc, char ** argv){ + + using Point = std::array; + + // Map 1 creation + std::map map1; + map1["earth"] = Point {1., 0., 0.}; + std::cout << "map1 created:" << std::endl; + printMap(map1); + + // Bad practice: Overwrite + map1["earth"] = Point {3., 3., 3.}; // --> overwrite! + std::cout << "map1 after earth overwrite:" << std::endl; + printMap(map1); + std::cout << std::endl; + + // Better practice: with key check + addToMap(map1, "earth", Point {4., 4., 4.}); + printMap(map1); + std::cout << std::endl; + addToMap(map1, "pluton", Point {4., 4., 4.}); + printMap(map1); + std::cout << std::endl; + + // Map 2 creation + std::map map2; + map2["mercury"] = Point {0.25, 0., 0.}; + map2["earth"] = Point {1.0, 0., 0.}; + map2["jupiter"] = Point {5.0, 0., 0.}; + map2["sun"] = Point {0., 0., 0.}; + std::cout << "map2 created:" << std::endl; + printMap(map2); + std::cout << std::endl; + + // Intersection map + std::map map3 = intersectMaps(map1, map2); + std::cout << "intersection of maps 1 and 2:" << std::endl; + printMap(map3); + std::cout << std::endl; + + return EXIT_SUCCESS; +} + + + diff --git a/work/week3/stl/starting_point/ex6.cc b/work/week3/stl/starting_point/ex6.cc new file mode 100644 index 0000000..b6cae58 --- /dev/null +++ b/work/week3/stl/starting_point/ex6.cc @@ -0,0 +1,71 @@ +#include +#include +#include +#include +#include +#include +#include // std::iota +#include +#include +/* -------------------------------------------------------------------------- */ + +void printVec(std::vector v) { + std::cout << " v = ["; + for (auto const &e : v) { + std::cout << e << " "; + } + std::cout << "]" << std::endl; +} + + +int main(int argc, char ** argv){ + + int n = 10; + std::cout << "Initialization: "; + std::vector v(n); + printVec(v); + + std::cout << "Filling with zeros: "; + std::fill(v.begin(), v.end(), 0); + printVec(v); + + std::cout << "Filling with incremental values from 1: "; + std::iota(v.begin(), v.end(), 1); + printVec(v); + + auto squarer = [](double x) { return x * x; }; + double x = 10; + std::cout << "x = " << x << ", x2 = " << squarer(x) << std::endl; + + for (auto &e : v) { e = squarer(e); } + std::cout << "Squaring vector with range loop: "; + printVec(v); + + std::iota(v.begin(), v.end(), 1); + std::for_each(v.begin(), v.end(), [](auto &x) { x = x * x; }); + std::cout << "Squaring vector with for_each: "; + printVec(v); + + // Natural squares sum formula + int s = n * (n + 1) * (2 * n + 1) / 6; + std::cout << "n(n+1)(2n+1)/6 = " << s << std::endl; + + // Compute sum in different ways + double sum = 0.; + auto adder = [&sum] (double x) { sum += x; }; + std::for_each(v.begin(), v.end(), adder); + std::cout << "Summing vector using for_each: s = " << sum << std::endl; + sum = std::accumulate(v.begin(), v.end(), 0.); + std::cout << "Summing vector with accumulate: s = " << sum << std::endl; + + // Compute Pi without loop + std::reverse(v.begin(), v.end()); // reverse + std::for_each(v.begin(), v.end(), [](auto &x) { x = 1. / x; }); // loop through and invert + double pi = sqrt(6 * std::accumulate(v.begin(), v.end(), 0.)); // sum, times 6 and sqrt + std::cout<< std::fixed << std::setprecision(20) << "Pi = " << pi << std::endl; + + return EXIT_SUCCESS; +} + + + diff --git a/work/week3/stl/starting_point/memory_first.cc b/work/week3/stl/starting_point/memory_first.cc new file mode 100644 index 0000000..070a2d4 --- /dev/null +++ b/work/week3/stl/starting_point/memory_first.cc @@ -0,0 +1,35 @@ +#include +#include +#include +#include + + +int main() { + + // stack array + // int values[10]; + std::array values; + for (int& v : values) { + v = 0; + } + std::cout << "stack array: "; + for (int i = 0; i < 10; ++i) { + std::cout << values[i] << " "; + } + std::cout << std::endl; + + // heap array + // int *values2 = new int[10]; + std::vector values2(10); + for (int i = 0; i < 10; ++i) { // cannot use default iterator + values2[i] = 0; + } + std::cout << "heap array: "; + for (int i = 0; i < 10; ++i) { + std::cout << values2[i] << " "; + } + std::cout << std::endl; + // delete[] values2; + + return 0; +} diff --git a/work/week3/stl/starting_point/memory_second.cc b/work/week3/stl/starting_point/memory_second.cc new file mode 100644 index 0000000..30e4afb --- /dev/null +++ b/work/week3/stl/starting_point/memory_second.cc @@ -0,0 +1,32 @@ +#include +#include +#include +#include + + +std::vector* stack_allocation(int n) { + std::vector stack_vec(n); + return &stack_vec; +} + +std::vector* heap_allocation(int n) { + return new std::vector(n); +} + +std::unique_ptr> heap_allocation_cpp14(int n) { + return std::make_unique>(n); +} + + +int main() { + std::vector* stack_values = stack_allocation(10); + // std::cout << "size of stack array: " << stack_values->size() << std::endl; // -->seg fault !!! + + // std::vector* heap_values = heap_allocation(10); + std::unique_ptr> heap_values = heap_allocation_cpp14(10); + std::cout << "size of heap array: " << heap_values->size() << std::endl; + // would require delete statement: delete [] heap_values; ??? + // delete[] heap_values; // --> seg fault !!! + + return 0; +} diff --git a/work/week3/stl/starting_point/memory_third.cc b/work/week3/stl/starting_point/memory_third.cc new file mode 100644 index 0000000..50c4ad0 --- /dev/null +++ b/work/week3/stl/starting_point/memory_third.cc @@ -0,0 +1,19 @@ +#include +#include +#include +#include + + +int main() { + + // Cannot share unique pointers + // auto unique = std::make_unique>(10); + // std::unique_ptr> other = nullptr; + // other = unique; + + // Solution: work with shared pointers + auto shared = std::shared_ptr>(new std::vector(10)); + std::shared_ptr> other = nullptr; + other = shared; + std::cout << "Successful!" << std::endl; +} diff --git a/work/week3/stl/sujet.pdf b/work/week3/stl/sujet.pdf new file mode 100644 index 0000000..5aaec2f Binary files /dev/null and b/work/week3/stl/sujet.pdf differ diff --git a/work/week4/conjugate_gradient/auto/sujet.el b/work/week4/conjugate_gradient/auto/sujet.el new file mode 100644 index 0000000..25c7023 --- /dev/null +++ b/work/week4/conjugate_gradient/auto/sujet.el @@ -0,0 +1,15 @@ +(TeX-add-style-hook + "sujet" + (lambda () + (TeX-add-to-alist 'LaTeX-provided-class-options + '(("article" "a4paper" "11pt"))) + (TeX-run-style-hooks + "latex2e" + "article" + "art11" + "color" + "float") + (TeX-add-symbols + '("mycomment" 1))) + :latex) + diff --git a/work/week4/conjugate_gradient/conjugate_gradient.py b/work/week4/conjugate_gradient/conjugate_gradient.py new file mode 100644 index 0000000..9bb06a8 --- /dev/null +++ b/work/week4/conjugate_gradient/conjugate_gradient.py @@ -0,0 +1,67 @@ +# -*- coding: utf-8 -*- +# @Author: Theo Lemaire +# @Date: 2018-10-09 14:18:16 +# @Last Modified by: Theo Lemaire +# @Last Modified time: 2018-10-09 16:08:19 + +import numpy as np +import matplotlib.pyplot as plt + +from optimizer import S, plotSurface + + +# dSdx = 4x + y - 1 +# dSdy = 3y + x - 2 +A = np.array([[4, 1], [1, 3]]) # 2nd derivative matrix (D2{S(x, y)}) +b = np.array([1, 2]) # (x, y) vector that cancels D{S(x, y)} + + +def getIterationSteps(coords): + ''' Optimizer callback, appending current x and y coordinates to an existing list. ''' + x_opt.append(coords) + + +def ConjugateGradient(A, b, x, tol): + ''' Conjugate Gradient implementation (from Wikipedia) to find the minimum + of a quadratic function. + + :param A: function's 2nd derivative matrix + :param b: vector that cancels the function's derivative matrix + :param x: vector of initial coordinates + :param tol: residual absolute tolerance + :return: vector of final coordinates + ''' + + # make sure input is float typed + x = np.array(x, dtype=float) + + # initialize residual and basis vector + r = b - np.einsum('ik,k->i', A, x) + p = r + rsold = np.einsum('k,k->', r.T, r) + + # iterate until residual is below given tolerance + rsnew = np.inf + niter = 0 + while np.sqrt(rsnew) >= tol: + Ap = np.einsum('ik,k->i', A, p) + alpha = rsold / np.einsum('k,k->', p.T, Ap) + x += alpha * p + r -= alpha * Ap + rsnew = np.einsum('k,k->', r.T, r) + p = r + rsnew / rsold * p + rsold = rsnew + getIterationSteps(x) + niter += 1 + return x, niter + + +if __name__ == '__main__': + x_opt = [(2, 2)] + tol = 1e-9 + _, niter = ConjugateGradient(A, b, x_opt[0], tol) + x, y = zip(*x_opt) + fig = plotSurface(S, np.array(x), np.array(y)) + fig.suptitle('Custom Conjugate Gradient (tol = {:.0e}, {} iterations)'.format( + tol, niter), fontsize=15) + plt.show() diff --git a/work/week4/conjugate_gradient/optimizer.py b/work/week4/conjugate_gradient/optimizer.py new file mode 100644 index 0000000..b998a13 --- /dev/null +++ b/work/week4/conjugate_gradient/optimizer.py @@ -0,0 +1,58 @@ +# -*- coding: utf-8 -*- +# @Author: Theo Lemaire +# @Date: 2018-10-09 13:25:52 +# @Last Modified by: Theo Lemaire +# @Last Modified time: 2018-10-09 16:07:42 + + +import numpy as np +from scipy.optimize import minimize +import matplotlib.pyplot as plt +from mpl_toolkits.mplot3d import Axes3D + + +def S(x, y): + ''' The function to optimize. ''' + return 2 * x**2 + 3 / 2 * y**2 + x * y - x - 2 * y + 6 + + +def optimizer(fun, x0, method, tol): + ''' The optimizer. ''' + return minimize(fun, x0, tol=tol, callback=getIterationSteps, + method=method) + + +def getIterationSteps(coords): + ''' Optimizer callback, appending current x and y coordinates to an existing list. ''' + x_opt.append(coords) + + +def plotSurface(fun, x_opt, y_opt, fs=12): + ''' Plot the 2D surface and the optimization solution at each iteration step. ''' + fig = plt.figure(figsize=(8, 6)) + ax = Axes3D(fig) + ax.set_xlabel('x', fontsize=fs) + ax.set_ylabel('y', fontsize=fs) + ax.set_zlabel('S(x, y)', fontsize=fs) + ax.view_init(elev=30, azim=130) + + x = np.linspace(-3, 3, 100) + X, Y = np.meshgrid(x, x) + ax.contour(X, Y, fun(X, Y), levels=np.linspace(5, 40, 10), colors='k', origin='lower') + ax.plot_surface(X, Y, fun(X, Y), rstride=1, cstride=1, cmap='coolwarm', alpha=0.5) + ax.plot(x_opt, y_opt, S(x_opt, y_opt), 'o--', c='r') + + return fig + + +if __name__ == '__main__': + x_opt = [(2, 2)] + method = 'BFGS' + tol = 1e-9 + res = optimizer(lambda x: S(*x), x_opt[0], method, tol) + x, y = zip(*x_opt) + fig = plotSurface(S, np.array(x), np.array(y)) + fig.suptitle('{} (tol = {:.0e}, {} iterations)'.format( + method, tol, res['nfev']), fontsize=15) + + plt.show() diff --git a/work/week4/conjugate_gradient/sujet.pdf b/work/week4/conjugate_gradient/sujet.pdf new file mode 100644 index 0000000..32a5354 Binary files /dev/null and b/work/week4/conjugate_gradient/sujet.pdf differ diff --git a/work/week4/matplotlib/auto/sujet.el b/work/week4/matplotlib/auto/sujet.el new file mode 100644 index 0000000..7fe21e0 --- /dev/null +++ b/work/week4/matplotlib/auto/sujet.el @@ -0,0 +1,12 @@ +(TeX-add-style-hook + "sujet" + (lambda () + (TeX-add-to-alist 'LaTeX-provided-class-options + '(("article" "a4paper" "11pt"))) + (TeX-run-style-hooks + "latex2e" + "../td" + "article" + "art11")) + :latex) + diff --git a/work/week4/matplotlib/sujet.pdf b/work/week4/matplotlib/sujet.pdf new file mode 100644 index 0000000..08b4823 Binary files /dev/null and b/work/week4/matplotlib/sujet.pdf differ