We also note that the program is flat in the sense that it does not contain features. The main program must be executed (via statements or a function call) in a test block.
Documenting Functions and Modules
A call to thisexperiment_compare_schemesfunction must be placed in the test block, or you can run the program from IPython instead:. We do not present how the flat program from Sect.5.1.3 should be refactored to produce the desired plots, but simply state that the danger of introducing errors is significantly greater than when just writing an extra function in thedecay module . with steps of 'dt' and the method implied by 'theta'.
Logging Intermediate Results
Setting the level to debug (logging.DEBUG) prints all messages, while the critical level prints only critical messages. To examine the numerator and denominator of the forunC1 formula in more detail, we can change the logging level to level=logging.DEBUG and get decay.loglike output.
User Interfaces
- Command-Line Arguments
- Positional Command-Line Arguments
- Option-Value Pairs on the Command Line
- Creating a Graphical Web User Interface
Positional arguments: Define a series of parameters on the command line and read their values directly from the thesys.argv[1:] list. Option value pairs: Use –option value on the command line to override the default value of an input parameter option with value (and use the argparse.ArgumentParsertool for implementation). Suppose we want to run a programprog.py specifying two parameterspanddelta on the command line.
For ourdecay.pymodule file, we want to include functionality such that we can read I,a,T, and array values from the command line. The technical details of entering command line information into the program are covered in the next two sections. The simplest way to read the input parameters is to decide their sequence on the command line and simply index thesys.argvlist accordingly.
Each parameter should have a reasonable default value, so we specify the option on the command line only if the default value is not suitable. When the command line is parsed, we get an object where the option values are stored as attributes. As can be seen, command line option values are available as attributes in args: args.opthole holds the option–opt value, unless we used destargument (as in --dt_values) to specify the attribute name.
Tests for Verifying Implementations
- Doctests
- Unit Tests and Test Functions
- Test Function for the Solver
- Test Function for Reading Positional Command-Line Arguments
- Test Function for Reading Option-Value Pairs
- Classical Class-Based Unit Testing
All we need to do in the current example is to run the filedecay.pywith module. This command imports the document test module, which runs all document tests found in the file and reports the deviations between the expected and calculated results. Doctests can also be embedded in nos/pytest unit tests as explained in the next section.
These work (almost) the same way, but our recommendation is to go for pytest. In fact, nose and pytest can recursively run all test functions in alltest*.pyfiles in the current directory, as well as in all subdirectories. The Decay.py12 module file contains test functions in the module, but we could have just as well made a tests subfolder and put the test functions in tests/test_decay.py13.
The -option ensures that the output of the test functions is printed in the terminal window, while -v prints the output of each individual test function. Note that sys.argv[0] is always the program name and that we need to copy that string from the originalsys.argvarray to the new one we construct in the test function. So, when developing a test function, it can be convenient to insert print statements into the function to monitor that the function body is actually executed.
Sharing the Software with Other Users
Organizing the Software Directory Tree
Our software consists of one module file, decay.py, and possibly some unit tests in a separate file located in the tests directory. Then the software is just one file and all we need is the directory with that file. The setup.py file can be as short as from distutils.core import setup setup(name=’decay’, . version=’0.1’, py_modules=[’decay’], scripts=[’decay.py’],.
Our decay.py can be used as a module or as an executable, so we want users to have both options. Package Distribution If the software consists of more files than one or two modules, it must be made into a Python package. The reader is referred to the Distutils16 documentation for more information on how to write setup.py scripts.
The executable, decay.py, is in the above installation script that is taken as the complete filedecay.py module. Normally one would prefer to instead write a very short script essentially importing decay and running the indecay.py test block. In this example package, we move the unit tests from thedecay.pymodule into a separate file, test_decay.py, and place this file in a tests directory.
Publishing the Software at GitHub
To create a new project, click New Repository on the main page and enter a project name. Click the Initialize this repository with the README file checkbox and click Create Repository. The next step is to clone (copy) the GitHub repo (short for repository) to your computer(s) and populate it with files.
The above git commands seem cryptic, but these commands plus 2–3 more are the core of what you need in your daily work with files in small or large software projects. Anyone can get the software using the listedgit clonecommand you used above, or by clicking on the links for zip and tar files. Every time you update the project files, you must register the update with GitHub.
And you need to put all your writing and programming projects in cloud repositories.
Downloading and Installing the Software
Install only a module file The software package in the above case contains a folder expiration with three files. This command installs the software into system directories, so the user must run the command as root on Unix systems (which is why the command starts with sudo). A user can easily install the software on her personal account if a system-wide installation is not desirable.
We refer to the installation documentation19 for the many arguments that can be given tosetup.py. Note that if the software is installed on a personal account, the PATH and PYTHONPATH environment variables must contain the relevant directories. Modules are typically installed in some lib directory on the computer system, eg /usr/local/lib/python2.7/dist-packages, while executables go to /usr/local/bin.
You can make it easier to use packages by offering a somewhat simpler import, such as import expiration. This is achieved by placing an import statement in the __init__.py file, which is executed whenever the importimport decay or from decay import package is run. Of course, it is the package developer who decides whether an __init__.py file should simply be empty.
Classes for Problem and Solution Method
The Problem Class
The purpose of the problem class is to store all the information about the mathematical model. Since we have an analytical solution to the ODE problem, we can add this solution in terms of a Python function (or method) to the problem class as well. We could have in theu_exact method written self.I*exp(-self.a*t), but using local variablesIanda allows the prettier formulaI*exp(-a*t), which looks much closer to the mathematical expressionIeat.
This is not a significant issue with the actual compact formula, but is useful in more complicated problems with longer formulas to get the closest possible relationship between the code and the math. The coding style in this book is to drop this prefix when the code expresses mathematical formulas. Class data can be set either as arguments to the constructor or at any time later, e.g.
To this end, we add a method to define a set of command-line options and a method that sets the local properties equal to those found on the command line. The default values associated with the command line options are taken as the values supplied to the constructor. Note that if the user already has an ArgumentParser object, it can be provided, but if she doesn't, class Problem creates one.
The Solver Class
Note that we see no need to repeat the body of a previously developed and tested rescuer function. With a single classSolver object, we have all physical and numerical data bundled together with a numerical solver method.
Improving the Problem and Solver Classes
Provided that a problem or solver class defines these three dictionaries in the constructor, we can create a superclassParameters with common code to define and read command-line options, as well as methods to set and get each parameter.
Automating Scientific Experiments
- Available Software
- The Results We Want to Produce
- Combining Plot Files
- Running a Program from Python
- The Automating Script
- Making a Report
- Publishing a Complete Project
For example, if 4t values are performed, the summary for the BE method has 22 subplots, with the subplot corresponding to the largest t in the upper left corner and the smallest in the lower right corner. We need to create a table containing the t values in the first column and the numerical error E for D0; 0:5; 1 in the next three columns. A script that automates the execution of our computational experiments will ensure that the experiments can easily be repeated by anyone in the future, either for validation.
In addition, everything we did to produce the results is documented in great detail in the script. The montage25andconvert26 programs in the ImageMagick software suite can be used to combine image files. At least the part of the report containing the plots should be automatically generated by the script running the set of experiments, because in the script we know exactly what inputs were used to generate a specific plot, ensuring that each figure is linked to the correct data.
For output in the PDF format36, see Fig.5.6 for an example, LATEX is the definite choice when it comes to set quality. For output to the web via HTML code (ie not just showing the PDF in the browser window), LATEX struggles with rendering high quality typesetting. Or vice versa: software can be equipped with documentation in the style of scientific reports.
Exercises
Make a tool for differentiating curves
Make solid software for the Trapezoidal rule An integral
Hint Note that even if you know the value of the integral, you do not know the error in approximation produced by the Trapezoid rule. Note that thetrapezoidal.pyfile must still be a valid module file, so command line data interpretation and integral computation must be performed by calls to a test block. Note that it needs the namespace math.__dict__, i.e., all the names in their module, in order to understand it as well as other math functions.
Implement classes for the Trapezoidal rule
Write a doctest and a test function Type in the following program
Investigate the size of tolerances in comparisons
Make use of a class implementation
Make solid software for a difference equation