Truncation error analysis provides a widely applicable framework for analyzing the accuracy of finite difference schemes. 2u00.tn/tCO.t2/ : (B.3) The dominant term for smalltis12u00.tn/t, which is proportional tot, and is said to be a first-order truncation error.
Overview of Leading-Order Error Terms in Finite Difference Formulas
The next class takes some symbols for the function in question and makes a list of symbols for the derivatives. The module file trunc/truncation_errors.py contains another DiffOp class with symbolic expressions for most of the truncation errors listed in the previous section.
Exponential Decay ODEs
- Forward Euler Scheme
- Crank-Nicolson Scheme
- The -Rule
- Using Symbolic Software
- Empirical Verification of the Truncation Error
- Increasing the Accuracy by Adding Correction Terms
- Extension to Variable Coefficients Let us address the decay ODE with variable coefficients,
- Exact Solutions of the Finite Difference Equations
- Computing Truncation Errors in Nonlinear Problems The general nonlinear ODE
For example, the truncation error of the Forward Euler scheme is applied to the decomposition of ODEu0D uais. Let's implement this function to estimate the truncation error of the Forward Euler scheme.
Vibration ODEs
- Linear Model Without Damping
- Model with Damping and Nonlinearity
- Extension to Quadratic Damping
- The General Model Formulated as First-Order ODEs
The truncation error of a centered finite difference scheme Using a standard, second-order, central difference for the second-order derivative in time, we have the scheme. ŒmDtDtuenCˇjŒDtuen12jŒDtuenC12 Cs.une/FnDRn: (B.61) We start by expressing the truncation error of the geometric mean.
Wave Equations
- Linear Wave Equation in 1D
- Finding Correction Terms
- Extension to Variable Coefficients
- Linear Wave Equation in 2D/3D
- Linear Diffusion Equation in 1D
- Nonlinear Diffusion Equation in 1D We address the PDE
We either have to discretize these fourth order derivatives directly or rewrite them in terms of lower order derivatives with the help of PDE. The reason for O.x4/in the remainder is that there are coefficients before this term, say Hx4, and subtracting and dividing byx results in ŒDxH nix4. Therefore, the result of the spatial derivative truncation error analysis is summarized as.
The main conclusion is that the scheme is of the second order in time and space also in this case of variable coefficient. The key ingredients for second-order are the center differences and the arithmetic mean for: all these building blocks have second-order precision. ŒDtDtueDc2.DxDxueCDyDyueCDzDzue/Cf CRni;j;k: (B.83) The calculations from the 1D case can be repeated with terms in the and z directions.
To find the truncation error, we start by expressing the arithmetic mean in terms of values at time C1.
Exercises
Use the ideas and tools in Section B.3.5 to estimate the truncation error rate of the Backward Euler and Crank-Nicolson schemes applied to the u0D au,u.0/DI exponential decay model. Hint In the backward Euler scheme, the truncation error can be evaluated at the grid points n D N, while the truncation error must be evaluated at the intermediate points tnC1. Use the ideas of Sect.B.3.6 to add a correction term to the ODE so that the inverse Euler scheme applied to the perturbed ODE problem will be second-order int.
Run the program to check that the error of the forward and backward Euler scheme is with perturbedaO.t2/, while the error resulting from the Crank-Nicolson scheme is with perturbedaO.t4/. Verify that the derived truncation error is consistent with the previous results for casef .u; t /D au. The programvib_undamped.pysolvesu00C!2uD0 with ŒD2tu D 00 and has the function convergence_rates to calculate the order of error in the numerical solution.
Modify this program to apply the forward difference –DCt u D00 and report how this simpler and easier approach affects the overall convergence rate of the scheme.
Software Engineering; Wave Equation Model
A 1D Wave Equation Simulator .1 Mathematical Model
- Numerical Discretization
- A Solver Function
Saving Large Arrays in Files
- Using savez to Store Arrays in Files
- Using joblib to Store Arrays in Files
- Using a Hash to Create a File or Directory Name
Merge the individual zip archives created with numpy.savez into one archive named archive_name. Individual archives can be given as a list of names or as a Unix wild chard filename expression for glob.glob. Here we notice that savez automatically adds the .npzekstension extension to the string names we save.
The name of the folder where the byjoblib arrays are stored can be specified by the user. You may be used to hashing strings from the Git version control system: each committed version of the files in Git is recognized by a hash string.). Suppose you have input data in the form of functions, numpy arrays, and other objects.
To turn this input data into a string, we can grab the source code of the functions, use a very efficient hashing method for potentially large strings, and simply convert all other viastr objects to a string representation.
Software for the 1D Wave Equation
- Making Hash Strings from Input Data
- Avoiding Rerunning Previously Run Cases
- Verification
Thehashed_inputargument used to name the resulting archive file with all solutions is supposed to be a hash that reflects all import parameters in the problem, so that this simulation has a unique name. All input, functions as well as variables, are then merged into a string data, and then hashlib.sha1 creates a unique, much shorter (40 characters long), fixed-length string out of data that we can use in the archive filename. With Dirichlet boundary conditions we can construct a function that is linear intand quadratic inx which is also an exact solution of the scheme, while with Neumann conditions we are left with testing a constant solution (see comments in Sect.2.6.5) .
To calculate the error, we had to rely on a global variable in the user action function. The returned sequences must converge to 2 since the error analysis in Section 2.10 predicts that various error measures will behave like O.t2/ C O.x2/. We can easily manage the case with standing waves and the analytical solution u.x; t / D cos.2Lt /sin.2Lx/.
The call will be very similar to the one in test_convrate_sincosfunction in Section 2.3.4, see the wave1D_dn_vc.py file for details.
Programming the Solver with Classes
- Class Parameters
- Class Problem
- Class Mesh
- Class Function
- Class Solver
Subclasses must initialize self.prm with parameters and default values, self.type with the corresponding types, and self.help with the corresponding descriptions of parameters.
Migrating Loops to Cython
- Declaring Variables and Annotating the Code
- Visual Inspection of the C Translation
- Building the Extension Module
- Calling the Cython Function from Python
Note that the solutions from all time steps are stored in a grid function that allows error evaluation (inassert_no_error) after all solutions have been found. Our starting point is the plainaadvance_scalarfunction for a scalar implementation of the update algorithm for new valuesunC1i;j. Variables are declared with types: for example double vin in the argument list instead of justv and cdef double v for the variable in the function body.
You can also directly inspect the generated C code as it appears in the wave2D_u0_loop_cy.c file. Deep within the file we can see in detail how the compute-intensive instructions have been translated into a complex C code that is very different from what a human would write (at least if a direct match to the mathematical notation was intended). Cython code must be translated into C, compiled, and linked to form what is known in the Python world as a C extension module.
The –inplace option makes the extension module available in the current directory as filewave2D_u0_loop_cy.so.
Migrating Loops to Fortran
- The Fortran Subroutine
- Building the Fortran Module with f2py
- How to Avoid Array Copying
The first command asks f2py to interpret the Fortran code and create a Fortran 90 specification of the extension module in filewave2D_u0_loop_f77.pyf. The build process takes place in the specified subfolder build_f77, so files can be inspected if something goes wrong. The reason for this behavior is that f2py creates Python interfaces so that Fortran routines can be called in the same way as Python functions.
Also, arrays in Python are passed to Python functions without their dimensions because the information is packed with the array data in the array objects. We strongly recommend printing out the documentation for each Fortran function to be called from Python and making sure that the calling syntax is exactly as specified in the documentation. There are two main reasons for copying array data: either the array does not have Fortran storage, or the element types do not match those declared in the Fortran code.
The latter cause is usually effectively remedied by using real*8data in Fortran code and float64 (default floattype innumpy) in arrays on the Python side.
Migrating Loops to C via Cython
- Translating Index Pairs to Single Indices
- The Complete C Code
- The Cython Interface File
- Building the Extension Module
The first drug is the most effective if the asarray operation needs to be performed many times. These can be ported to Cython or Fortran as explained, while the rest of the programming can be more conveniently done in Python. We need to compile this file along with the C wrapper code so that advance can be called from Python.
nameadvance is already used for the C function, so the function to call from Python is namedadvance_cwrap. Files are then compiled and linked to an extension module located in filewave2D_u0_loop_c_cy.so. Efficiency In this example, the C and Fortran code run at the same speed, and there are no significant differences in the efficiency of the wrapper code.
The overhead implied by the wrapper code is negligible as long as there is little numerical work in the advanced function, or in other words, that we are working with small meshes.
Migrating Loops to C via f2py
- Migrating Loops to C++ via f2py
Note that we need a specialf2py instruction, through a Cf2pycomment line, to specify that all the function arguments are C variables. Like when we interface Fortran code with f2py, we need to print out the doc string to see the exact call syntax from the Python side. A tool like SWIG3 can interpret the C++ code and generate interfaces for a wide variety of languages, including Python, Perl, Ruby, and Java.
A technically much easier way to interface C++ code is to drop the ability to use C++ classes directly from Python, but instead make a C interface to C++. Such a solution means that classes in Python and C++ cannot be mixed, and that only primitive data types such as numbers, strings and arrays can be transferred between Python and C++. The arrays that come from Python and look like regular C/C++ arrays can be efficiently wrapped into more user-friendly C++ array classes in the C++ code if desired.
Exercises
The goal is to visualize the effect of the Courant number C on the quality of the solution. Simulate forC D and make an animation comparing the three curves (use theanimate_archives.pyprogram to combine the curves and make animations on the screen and video files). Perform the studies for different types of initial profiles: a Gaussian pulse, a "cosine-hat" pulse, a half-"cosine-hat" pulse, and a plug pulse.
We solve the same set of problems as in Exercise C.3, except that we now fix C D1 and instead study the impact of land by varying the parameter.
For evaluation purposes, manuscripts can be submitted in printed or electronic form, in the latter case preferably as pdf or compressed ps files. Authors are asked to use the LaTeX style files available from Springer at: https://www.springer.com/gp/authors-editors/book-authors-editors/manuscript-preparation/5636 (Click on!Templates! LaTeX. ! monographs). Those considering a book that might be suitable for a series are strongly encouraged to contact the publisher or series editors as soon as possible.
Authors are eligible to purchase additional copies of their book and other Springer books for personal use at a 40% discount directly from Springer-Verlag.
Texts in Computational Science and Engineering
Monographs in Computational Science and Engineering