diff --git a/.travis.yml b/.travis.yml new file mode 100644 index 0000000..65250f6 --- /dev/null +++ b/.travis.yml @@ -0,0 +1,11 @@ +language: python +dist: xenial +cache: + - pip +install: + - pip install --upgrade -r requirements.txt +script: + - mkdir build_html + - sphinx-build -nW -b html source build_html + - mkdir build_pdf + - sphinx-build -nW -b pdf source build_pdf \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..1b3a6e8 --- /dev/null +++ b/requirements.txt @@ -0,0 +1 @@ +sphinx \ No newline at end of file diff --git a/source/PvL_01.rst b/source/PvL_01.rst index 1277f68..b164de0 100644 --- a/source/PvL_01.rst +++ b/source/PvL_01.rst @@ -75,8 +75,23 @@ Working directly in the interpreter is convenient for testing short bits of code get immediate feedback. Think of it as scratch paper used to help you work out problems. Anything longer than a few lines should be put into a script. +When you are writing a script you need something like a text editor. With this we mean a program on +your computer that changes text files, not something that also does layout like a word processor +such as Microsoft Word or LibreOffice Writer. A few examples of text editors are +Notepad, Notepad++, vim, emacs and sublime. -.. index:: program, algorithm +For Python (and many other programming languages) there are programs that include both a text editor +and a way to interact with the interpreter. We call these development environments (sometimes +Integrated Development Environment or IDE). For Python these can include (among many others) Spyder, Thonny or IDLE. +There are also development environments that run in your browser. One example of this is Jupyter Notebook. + +The choice of development environment is quite personal, but if you are following a course based on this book +the teacher will probably recommend one. That recommendation is handy to follow if you need help using the environment. + +The important thing to remember is that Python itself does not care in what editor you write your code. As long as +you write correct syntax (with the right tabs and spaces) Python can run your program. The editor is only there to help you. + +.. index:: program, algorithm, editor, IDE What is a program? ------------------ @@ -467,9 +482,7 @@ Glossary An interactive user interface to the Python interpreter. The user of a Python shell types commands at the prompt (>>>), and presses the return key to send these commands immediately to the interpreter for - processing. The word *shell* comes from Unix. In the PyScripter - used in this RLE version of the book, the Interpreter Window is where - we'd do the immediate mode interaction. + processing. The word *shell* comes from Unix. runtime error An error that does not occur until the program has started to execute diff --git a/source/PvL_03.rst b/source/PvL_03.rst index 002fdc8..2e16b65 100644 --- a/source/PvL_03.rst +++ b/source/PvL_03.rst @@ -1212,7 +1212,7 @@ Here is a fragment of code that demonstrates the use of the ``while`` statement: n = 6 current_sum = 0 - i = 1 + i = 0 while i <= n: current_sum += i i += 1 @@ -1245,8 +1245,8 @@ loop will repeat forever, which is called an **infinite loop**. In the case here, we can prove that the loop terminates because we know that the value of ``n`` is finite, and we can see that the value of ``i`` increments each time through the loop, so eventually it will have to exceed ``n``. In -other cases, it is not so easy, even impossible in some cases, -to tell if the loop will ever terminate. +other cases it is not so easy, maybe even impossible, to tell if the loop will ever +terminate. What you will notice here is that the ``while`` loop is more work for you --- the programmer --- than the equivalent ``for`` loop. When using a ``while`` @@ -1266,7 +1266,7 @@ terminates. By comparison, here is an equivalent snippet that uses ``for`` inst Notice the slightly tricky call to the ``range`` function --- we had to add one onto ``n``, because ``range`` generates its list up to but excluding the value you give it. -It would be easy to make a programming mistake and overlook this. +It would be easy to make a programming mistake and overlook this. So why have two kinds of loop if ``for`` looks easier? This next example shows a case where we need the extra power that we get from the ``while`` loop. diff --git a/source/PvL_05.rst b/source/PvL_05.rst index 3c33f6f..376b8c7 100644 --- a/source/PvL_05.rst +++ b/source/PvL_05.rst @@ -66,14 +66,14 @@ simply type the following into an editor like Spyder or PyScripter script: new_string = our_string. When you type the period to select one of the methods of ``our_string``, your editor might pop up a -selection window showing all the methods (there are around 70 of them --- thank goodness we'll only +selection window — typically by pressing ``Tab`` — showing all the methods (there are around 70 of them --- thank goodness we'll only use a few of those!) that could be used on your string. .. image:: illustrations/string_methods.png When you type the name of the method, some further help about its parameter and return -type, and its docstring, will be displayed. This is a good example of a tool --- PyScripter --- -using the meta-information --- the docstrings --- provided by the module programmers. +type, and its docstring, may be displayed by your scripting environments (for instance, in a Jupyter +notebook you can get this inofrmation by pressing ``Shift+Tab`` after a function name). .. image:: illustrations/swapcase.png @@ -91,8 +91,8 @@ selects a single character substring from a string: The expression ``fruit[1]`` selects character number 1 from ``fruit``, and creates a new -string containing just this one character. The variable ``m`` refers to the result. -When we display ``m``, we could get a surprise: +string containing just this one character. The variable ``letter`` refers to the result. +When we display ``letter``, we could get a surprise: .. sourcecode:: pycon @@ -521,7 +521,7 @@ string, and is another example of the counter pattern introduced in count += 1 return(count) - test(count_a("banana") == 3) + print(count_a("banana") == 3) .. index:: optional parameter, default value, parameter; optional @@ -538,14 +538,14 @@ starting position in the search string: :linenos: def find2(haystack, needle, start): - for index,letter in enumerate(haystack[start:]) + for index,letter in enumerate(haystack[start:]): if letter == needle: - return index + return index + start return -1 - test(find2("banana", "a", 2) == 3) + print(find2("banana", "a", 2) == 3) The call ``find2("banana", "a", 2)`` now returns ``3``, the index of the first occurrence of "a" in "banana" starting the search at index 2. What does @@ -580,10 +580,10 @@ position, up to but not including the end position: .. sourcecode:: python3 :linenos: - def find(haystack, needle, start=0,end=-1): + def find(haystack, needle, start=0, end=-1): for index,letter in enumerate(haystack[start:end]) if letter == needle: - return index + return index + start return -1 The semantics of ``start`` and ``end`` in this function are precisely the same as they are in @@ -2342,8 +2342,8 @@ computation short-circuits a search and returns early, as in this case: return i - test(f(110) == 105) - test(f(1000000000) == 105) + print(f(110) == 105) + print(f(1000000000) == 105) In the second test, if range were to eagerly go about building a list with all those elements, you would soon exhaust your computer's available @@ -2704,10 +2704,10 @@ Exercises replace("Mississippi", "i", "I") == "MIssIssIppI" song = "I love spom! Spom is my favorite food. Spom, spom, yum!" - replace(s, "om", "am") == + replace(song, "om", "am") == "I love spam! Spam is my favorite food. Spam, spam, yum!" - replace(s, "o", "a") == + replace(song, "o", "a") == "I lave spam! Spam is my favarite faad. Spam, spam, yum!" *Hint*: use the ``split`` and ``join`` methods. @@ -3167,10 +3167,10 @@ Exercises # Make these tests work... new_inventory = {} add_fruit(new_inventory, "strawberries", 10) - test("strawberries" in new_inventory) - test(new_inventory["strawberries"] == 10) + print("strawberries" in new_inventory) + print(new_inventory["strawberries"] == 10) add_fruit(new_inventory, "strawberries", 25) - test(new_inventory["strawberries"] == 35) + print(new_inventory["strawberries"] == 35) #. Write a program called ``alice_words.py`` that creates a text file named ``alice_words.txt`` containing an alphabetical listing of all the words, and the diff --git a/source/PvL_06.rst b/source/PvL_06.rst index e3d207d..84a0613 100644 --- a/source/PvL_06.rst +++ b/source/PvL_06.rst @@ -311,7 +311,7 @@ Advanced Usage Numpy has vast capabilities. It has way too many options to discuss here. More information can be found in -#. the `Quickstart Numpy Tutorial `_; +#. the `Quickstart Numpy Tutorial `_; #. the `Numpy indexing documentation `_ (for advanced slicing and indexing); #. and the `Numpy broadcasting rules `_ (for what happens when performing operations between arrays of different shapes and sizes). diff --git a/source/PvL_07.rst b/source/PvL_07.rst index fa63ea6..e4026d7 100644 --- a/source/PvL_07.rst +++ b/source/PvL_07.rst @@ -243,6 +243,15 @@ strings is the same! We cannot use ``/`` or ``\`` as part of a filename; they are reserved as a **delimiter** between directory and filenames. +When working with files in directories it is a good idea to let Python deal with all +the slashes and escaping them. The ``os.path`` module does this for different operating systems. +Using ``os.path.join("directory", "filename")`` will automatically return ``"directory/filename"`` +on Unix/Linux, and ``"directory\\filename"`` on Windows. This can not only be of great help +when moving code from one system to another, or when sharing with colleagues. It also means +that you do not have to take care of it yourself, and it might save you some issues with string handling. + +You can also explore the ``os.path`` module for other handy features that will help you handling files. + The file ``/usr/share/dict/words`` should exist on Unix-based systems, and contains a list of words in alphabetical order. @@ -273,6 +282,10 @@ We'll need to get a few things right before this works: * If we are behind a proxy server that requires authentication, (as some students are), this may require some more special handling to work around our proxy. Use a local resource for the purpose of this demonstration! + * We need to make sure that if we use any data from the web, that we check if the contents are still + as we expect them to be. A website may change, or it may disappear. It can also be taken over by a new owner + who might change the contents completely. So before you use data from the internet, make your program check if + the data is what you want it to be, before executing any code or showing it to any important users! Here is a slightly different example using the *requests* module. This module is not part of the standard library distributed with python, however it is easier to use and significantly more potent than the *urllib* module distributed with python. Read *requests* documentation on ``_ to learn how to install and use the module. Here, rather than save the web resource to our local disk, we read it directly into a string, and we print that string: diff --git a/source/PvL_E.rst b/source/PvL_E.rst index 1211045..b57db10 100644 --- a/source/PvL_E.rst +++ b/source/PvL_E.rst @@ -108,7 +108,7 @@ If the ``try`` block can fail if various way, you can handle different exceptions in the same ``try`` clause: .. sourcecode:: python3 - :lineos: + :linenos: try: with open(filename) as infile: diff --git a/source/PvL_F.rst b/source/PvL_F.rst index 372a0d2..bb942f7 100644 --- a/source/PvL_F.rst +++ b/source/PvL_F.rst @@ -24,25 +24,27 @@ y t n Since the model predicts a parabola, we want to fit the data to this model to see how good it works. It might be a bit confusing, but :math:`h` is our x axis, and :math:`t` is the y axis. -We use the `symfit` package to do our fitting. You can find the installation instructions `here -`_. +We use the ``symfit`` package to do our fitting. You can find the installation instructions `here +`__. To fit the data to the model we run the following code: .. sourcecode:: python3 import numpy as np - from symfit.api import Variable, Parameter, Fit, sqrt + from symfit import Variable, Parameter, Fit, Model, sqrt t_data = np.array([1.4, 2.1, 2.6, 3.0, 3.3]) h_data = np.array([10, 20, 30, 40, 50]) # We now define our model - h = Variable() - g = Parameter() - t_model = sqrt(2 * h / g) + h = Variable('h') + t = Variable('t') + g = Parameter('g') - fit = Fit(t_model, h_data, t_data) + t_model = Model({t: sqrt(2 * h / g)}) + + fit = Fit(t_model, h=h_data, t=t_data) fit_result = fit.execute() print(fit_result) @@ -52,14 +54,21 @@ Looking at these results, we see that :math:`g = 9.09 \pm 0.15` for this dataset # Make an array from 0 to 50 in 1000 steps h_range = np.linspace(0, 50, 1000) - fit_data = t_model(h=h_range, g=fit_result.params.g) + fit_data = t_model(h=h_range, g=fit_result.value(g)) + t_fit = fit_data.t + + .. note:: + When calling a ``symfit.Model``, a ``namedtuple`` is returned with + all the components of the model evaluated. In this case there is only + one component, and can be accessed by requesting ``fit_data.t`` or + ``fit_data[0]``. .. image:: illustrations/fit_example.png :alt: Fitting curve for the gravity data. -This gives the model evaluated at all the points in `h_range`. Making the actual plot is left to you as an exercise. We see that we can reach the value of g by calling `fit_result.params.g`, this returns :math:`9.09`. +This gives the model evaluated at all the points in ``h_range``. Making the actual plot is left to you as an exercise. We see that we can request the fitted value of g by calling ``fit_result.value(g)``, which returns :math:`9.09`. Let's think for a second about the implications. The value of :math:`g` is :math:`g = 9.81` in the Netherlands. Based on our result, the textbooks should be rewritten because that value is extremely unlikely to be true given the small standard deviation in our data. It is at this point that we remember that our data point were not infinitely precise: we took many measurements and averaged them. This means there is an uncertainty in each of our data points. We will now account for this additional uncertainty and see what this does to our conclusion. To do this we first have to describe how the fitting actually works. @@ -78,8 +87,8 @@ Here we have written the parameters as a vector :math:`\vec{p}`, to indicate tha Now if we minimize :math:`Q^2`, we get the best possible values for our parameters. The fitting algorithm actually just takes some values for the parameters, calculates :math:`Q^2`, then changes the values slightly by adding or subtracting a number, and checks if this new value is smaller than the old one. If this is true it keeps going in the same direction until the value of :math:`Q^2` starts to increase. That's when you know you've hit a minimum. Of cource the trick is to do this smartly, and a lot of algorithms have been developed in order to do this. -Propagating Uncertanties ------------------------- +Propagating Uncertainties +------------------------- In the example above we the fitting process assumed that every measurement was equally reliable. But this is not true. By repeating a measurement and averaging the result, we can improve the accuracy. So in our example, we dropped our object from every height a couple of times and took the average. Therefore, we want to assign a weight depending on how accurate the average value for that height is. Statistically the weight :math:`w_i` to use is :math:`w_i = \frac{1}{\sigma_i^2}`, where :math:`\sigma_i` is the standard deviation for each point. @@ -119,7 +128,7 @@ The values of :math:`\sigma_t` have been calculated by using the above formula. .. sourcecode:: python3 import numpy as np - from symfit.api import Variable, Parameter, Fit, sqrt + from symfit import Variable, Parameter, Fit, Model, sqrt t_data = np.array([1.4, 2.1, 2.6, 3.0, 3.3]) h_data = np.array([10, 20, 30, 40, 50]) @@ -128,18 +137,20 @@ The values of :math:`\sigma_t` have been calculated by using the above formula. sigma_t = sigma / np.sqrt(n) # We now define our model - h = Variable() - t = Variable() - g = Parameter() - t_model = {t: sqrt(2 * h / g)} + h = Variable('h') + t = Variable('t') + g = Parameter('g') + t_model = Model({t: sqrt(2 * h / g)}) fit = Fit(t_model, h=h_data, t=t_data, sigma_t=sigma_t) fit_result = fit.execute() print(fit_result) - .. note:: Named Models + .. note:: - Looking at the definition of `t_model`, we see it is now a dict. This has been done so we can tell `symfit` which of our variables are uncertain by the name of the variable, in this case `t` has an uncertainty `sigma_t`. + Looking at the initiation of ``Fit``, we see that uncertainties can be + provided to ``Variable``'s by prepending their name with ``sigma_``, in + this case ``sigma_t``. Including these uncertainties in the fit yields :math:`g = 9.10 \pm 0.16`. The accepted value of :math:`g = 9.81` is well outside the uncertainty in this data. Therefore the textbooks must be rewriten! @@ -149,7 +160,8 @@ This example shows the importance of propagating your errors consistently. (And More on symfit -------------- -There are a lot more features in `symfit` to help you on your quest to fitting the universe. You can find the tutorial `there -`_. +There are a lot more features in ``symfit`` to help you on your quest to fitting +the universe. You can find the tutorial `here +`__. It is recommended you read this as well before starting to fit your own data. diff --git a/source/PvL_H.rst b/source/PvL_H.rst index 2e84104..b9f3afc 100644 --- a/source/PvL_H.rst +++ b/source/PvL_H.rst @@ -140,7 +140,7 @@ that define the plotting style: The style strings, one per *x*--*y* pair, specify color and shape: 'rx' stands for red crosses, and 'b-.' stands for blue dash-point line. Check the -`documentation `_ +`documentation `__ of ``pyplot.plot`` for the list of colors and shapes. Finally, ``plt.plot`` can also, conveniently, take numpy arrays as its arguments. @@ -152,7 +152,7 @@ More plots While ``plt.plot`` can satisfy basic plotting needs, ``matplotlib`` provides many more plotting functions. Below we try out the ``plt.bar`` function, for plotting bar charts. The full list of plotting functions can be found -in the the ``matplotlib.pyplot`` `documentation `_. +in the the ``matplotlib.pyplot`` `documentation `__. Bar charts can be plotted using ``plt.bar``, in a similar fashion to ``plt.plot``: @@ -253,7 +253,7 @@ calling ``plt.savefig``: .. note:: When saving a plot, you'll want to choose a `vector format - `_ + `__ (either pdf, ps, eps, or svg). These are resolution-independent formats and will yield the best quality, even if printed at very large sizes. Saving as png should be avoided, and saving as jpg diff --git a/source/conf.py b/source/conf.py index d6893e1..ec7be41 100644 --- a/source/conf.py +++ b/source/conf.py @@ -22,7 +22,7 @@ # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. -extensions = ['sphinx.ext.pngmath'] +extensions = ['sphinx.ext.imgmath'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] diff --git a/source/index.rst b/source/index.rst index 6a4327c..8b6c549 100644 --- a/source/index.rst +++ b/source/index.rst @@ -55,6 +55,7 @@ illustrated by Dario Mitchell PvL_E.rst PvL_F.rst PvL_G.rst + PvL_H.rst .. toctree:: :maxdepth: 1