computationalLib
index
/mn/felt/u2/magnarkb/sommerjobb/FYS3150/FYS3150/doc/computationalLib.py

# -*- coding: utf-8 -*-

 
Modules
       
math
numpy
os
sys

 
Classes
       
pylib
exceptions.Exception
MatrixError
MatrixNotSquareError
MatrixNotSymetricError
SingularError
SizeError

 
class MatrixError(exceptions.Exception)
    General class for (mathematical) errors in matrices passed.
 
  Methods defined here:
__init__(self, A)
Input:
- A: The matrix which has an error
__str__(self)

Methods inherited from exceptions.Exception:
__getitem__(...)

 
class MatrixNotSquareError(MatrixError)
    Raised by a method requiring a square matrix if it is not square.
 
 
Method resolution order:
MatrixNotSquareError
MatrixError
exceptions.Exception

Methods defined here:
__str__(self)

Methods inherited from MatrixError:
__init__(self, A)
Input:
- A: The matrix which has an error

Methods inherited from exceptions.Exception:
__getitem__(...)

 
class MatrixNotSymetricError(MatrixError)
    Raised by a method requiring a symetric matrix if it is not symetric.
Always raise MatrixNotSquareError before this one (a non-square matrix can't be symetric anyway).
 
 
Method resolution order:
MatrixNotSymetricError
MatrixError
exceptions.Exception

Methods defined here:
__init__(self, A, delta)
Input:
 - A: The matrix which has an error
 - delta: sum of abs(Aij-Aji)
__str__(self)

Methods inherited from exceptions.Exception:
__getitem__(...)

 
class SingularError(MatrixError)
    Raised by numerical functions if a matrix is singular
 
 
Method resolution order:
SingularError
MatrixError
exceptions.Exception

Methods defined here:
__str__(self)

Methods inherited from MatrixError:
__init__(self, A)
Input:
- A: The matrix which has an error

Methods inherited from exceptions.Exception:
__getitem__(...)

 
class SizeError(MatrixError)
    Raised if a set of matrices/vectors that should have the same size
have different sizes
 
 
Method resolution order:
SizeError
MatrixError
exceptions.Exception

Methods defined here:
__init__(self, message)
Input:
 - message: String containing relevant info about the sizes and names
__str__(self)

Methods inherited from exceptions.Exception:
__getitem__(...)

 
class pylib
    Implements many of the functions found in M.H.Jensens
c++-library, used in Computational Physics. This is again heavily based
on what is found in Numerical recipes.
 
Ported to Python by
Kyrre Ness Sjøbæk      (k DÅTT n DÅTT sjobak ÆTT fys DÅTT uio DÅTT no),
Magnar Kopangen Bugge  (magnarkb ÆTT student DÅTT matnat DÅTT uio DÅTT no),
Marit Sandstad         (marit DÅTT sandstad ÆTT fys DÅTT uio DÅTT no)
 
  Methods defined here:
__init__(self, inputcheck=False, cpp=False)
Constructor,
Set inputcheck = True in order to do input checking (debug, slower)
Set cpp = True to use compiled versions of the functions where aviable
checkSquare(self, A)
Checks if A is square, if not it raises exeption MatrixNotSquareError.
Called by relevant methods if self.inputcheck=True
checkSymetric(self, A)
Checks if A is symetric, if not it raises exception MatrixNotSymetricError.
Called by relevant methods if self.inputcheck=True. Always call checkSquare first!
euler(self, y0, t0, te, N, deriv, filename=None)
General eulers method driver and stepper for
N coupled differential eq's,
fixed stepsize
 
Input:
 - y0:       Vector containing initial values for y
 - t0:       Initial time
 - te:       Ending time
 - N:        Number of steps
 - deriv:    See rk4_step
 - filename: Optional, use if you want to write
             data to file at each step.
             Format used:
             t y[0] y[1] ... (%10.15E)
 
Output:
If filename=None, return tuple containing:
 - time:  Array of times at which it has iterated over
 - yout:  N*len(y0) numpy array containing y for each timestep
If filename specified, None is returned.
gausLegendre(self, a, b, N)
Used to calculate weights and meshpoints for
gaus-legendre quadrature.
 
Input:
- a, b: Limits of integration
- N:    Integration points
 
Returns:
- Numpy array of meshpoints
- Numpy array of weights
 
Method heavily inspired of gauleg() from Numerical recipes
Note: This is not the same method as described in compendium;
see NR for more info!
gausLegendre_cpp(self, a, b, x, w, N)
C++ backend for gausLegendre, using routine
in the library
gausLegendre_python(self, a, b, x, w, N)
Python backend for gausLegendre
jacobi(self, A, inaccurate=False)
Computes all eigenvalues and eigenvectors of a real symetric matrix A,
using Jacobi transformations. Note: This is the cyclic Jacobi method,
not the original one. See Numerical recipes!
 
Input:
 - A: Square symetric matrix which is to be diagonalized.
      Lower part (below diag) left untouched, upper part destroyed
- inaccurate: optional bool value to decide the degree of accuracy
      of the method. default value is False. 
 
Output:
 - d:    Vector containing the eigenvalues of A
 - v:    Matrix with columns representing the eigenvectors of A (normalized)
 - nrot: Number of Jacobi rotations required
jacobi_cpp(self, A, d, v, n, nrot)
C++ backend for jacobi, using routine
in the library
jacobi_python(self, A, d, v, n, nrot, inaccurate)
Python backend for jacobi
jacobi_rot(self, A, s, tau, i, j, k, l)
Sub-routine used by jacobi() to do one part of a rotation
 
Input:
 - A:   Matrix to be sub-rotated
 - s:   sine of rotation angle phi
 - tau: Tau (helper quantity)
 - i,j,k,l: "coordninates" in matrix to rotate
luBackSubst(self, A, index, b)
Back-substitution of LU-decomposed matrix
Solves the set of linear equations A x = b of dimension n
The input A is the LU-decomposed version of A obtained from
pylib.luDecomp(),
index is the pivoting permutation vector obtained
from the same function, and
b is the right-hand-side vector b as a numpy array.
 
Returns the solution x as an numpy array.
 
BIG FAT WARNING: Destroys input b in calling program!
(b is set equal to x after calculation has finished)
Send it a copy if this is bad.
luBackSubst_cpp(self, A, N, index, b)
C++ backend for luDecomp, using routine
in the library
luBackSubst_python(self, A, N, index, b)
Python backend for luBackSubst
luDecomp(self, A)
LU-decomposes a matrix A, and returns the LU-decomposition of a
rowwise permutation of A. Used in combination with luBackSubst function
to solve an equation-set Ax=B.
 
Returns: A tuple containing
- LU-decomposed matrix (upper part and diagonal = matrix U, lower part = matrix L)
- Array which records the row permutation from partial pivoting
- Number which depends on the number of row interchanges was even (+1) or odd (-1)
 
BIG FAT WARNING: Destroys input A in calling program!
(A is set equal to the returned LU-decomposed matrix)
Send it a copy if this is bad.
 
This function has the ability to switch between Python and C++ backends, see __init__()
luDecomp_cpp(self, A, N, index, d)
C++ backend for luDecomp, using routine
in the library
luDecomp_python(self, A, N, index, d)
Python backend for luDecomp
pythag(self, a, b)
Function which computes sqrt(a^2+b^2) without loss of precision. Used by tqli().
rk2(self, y0, t0, te, N, deriv, filename=None)
General RK2 driver for
N coupled differential eq's,
fixed stepsize
 
Input:
 - y0:       Vector containing initial values for y
 - t0:       Initial time
 - te:       Ending time
 - N:        Number of steps
 - deriv:    See rk4_step
 - filename: Optional, use if you want to write
             data to file at each step.
             Format used:
             t y[0] y[1] ... (%10.15E)
 
Output:
If filename=None, return tuple containing:
 - time:  Array of times at which it has iterated over
 - yout:  N*len(y0) numpy array containing y for each timestep
If filename specified, None is returned.
rk2_step(self, y, t, h, deriv)
General RK2 stepper for
N coupled differential eq's
 
Input:
    - y:      Array containing the y(t)
    - t:      Which time are we talking about?
    - h:      Stepsize
    - deriv:  Function that returns an array
              containing dy/dt for each y at time t,
              and takes as arguments an y-array, and time t.
rk4(self, y0, t0, te, N, deriv, filename=None)
General RK4 driver for
N coupled differential eq's,
fixed stepsize
 
Input:
 - y0:       Vector containing initial values for y
 - t0:       Initial time
 - te:       Ending time
 - N:        Number of steps
 - deriv:    See rk4_step
 - filename: Optional, use if you want to write
             data to file at each step.
             Format used:
             t y[0] y[1] ... (%10.15E)
 
Output:
If filename=None, return tuple containing:
 - time:  Array of times at which it has iterated over
 - yout:  N*len(y0) numpy array containing y for each timestep
If filename specified, None is returned.
rk4Adaptive(self, y0, t0, te, h0, deriv, errorfunc, filename=None)
General RK4 driver for
N coupled differential eq's,
adaptive stepsize.
 
Inspired by Numerical Recipes, and
http://www.cofc.edu/lemesurierb/math545-2007/handouts/adaptive-runge-kutta.pdf
plus some of my own extras.
 
Input:
 - y0:        Vector containing initial values for y
 - t0:        Initial time
 - te:        Ending time
 - h0:        Initial guess for stepsize h
 - deriv:     See rk4_step()
 - errorfunc: Fuction that returns 0.0 if the step is accepted,
              or else a returns the new stepsize
              Expects input yOld, yNew, yErr, h, and t
 - filename:  Optional, use if you want to write
              data to file at each step.
              Format used:
              t y[0] y[1] ... (%10.15E)
 
Output:
If filename=None, return tuple containing:
 - time:  Array of times at which it has iterated over
 - yout:  N*len(y0) numpy array containing y for each timestep
If filename specified, None is returned.
rk4Adaptive_stepsizeControl1(self, yOld, yNew, yErr, h, t)
Standard stepsize control algo for adaptive RK4.
This variety uses a fractional tolerance,
usefull for most problems that don't cross zero.
yTol should in this case be a number, and is interpreted
as an accuracy requirement epsilon.
 
Also see rk4Adaptive() and rk4Adaptive_stepsizeControl1()
 
Please set the class variable pylib.yTol before use!
rk4Adaptive_stepsizeControl2(self, yOld, yNew, yErr, h, t)
Standard stepsize control algo for adaptive RK4.
This variety uses a fixed tolerance, usefull for oscilatory
problems. You should set yTol to something like
epsilon*yMax, where yMax isthe largest values you get,
and epsilon is the desired accuracy (say, 10^-6).
 
Also see rk4Adaptive() and rk4Adaptive_stepsizeControl2()
 
Please set the class variable pylib.yTol before use!
rk4_step(self, y, t, h, deriv)
General RK4 stepper for
N coupled differential eq's
 
Input:
    - y:      Array containing the y(t)
    - t:      Which time are we talking about?
    - h:      Stepsize
    - deriv:  Function that returns an array
        containing dy/dt for each y at time t,
        and takes as arguments an y-array, and time t.
sign(self, a, b)
Function which returns |a| * sgn(b).
simpson(self, a, b, n, func)
Same as trapezoidal, but use simpsons rule
tqli(self, d, e, z)
Function which finds the eigenvalues and eigenvectors of a tridiagonal symmetric
matrix. This is a translation of the function tqli in lib.cpp. 
 
Input:
- d: diagonal elements of the matrix
- e: off-diagonal elements of the matrix (first element is dummy)
- z: unit matrix (if eigenvectors of an "already tridiag" matrix wanted),
     or matrix from tred2() if eigenvectors from a symetric matrix tridiagonalized by
     tred2() wanted.
 
The elements of d after tqli() has finished are the eigenvalues of
the tridiagonal matrix. The eigenvectors are stored in z.
tqli_cpp(self, d, e, n, z)
C++ backend for tqli(), using routine
in the library
tqli_python(self, d, e, n, z)
Python backend for tqli()
trapezoidal(self, a, b, n, func)
Integrate the function func
using the trapezoidal rule from a to b,
with n points. Returns value from numerical integration
tred2(self, A)
Perform a Householder reduction of a real symetric matrix
to tridiagonal form. See Numerical recipes for more info!
 
Input:
- A: NxN Numpy array containing the matrix to be tridiagonalized. Destroyed by tred2()!
 
Output:
- d: Numpy array length N containing the diagonal elements of the tridiagonalized matrix
- e: Numpy array length N containing the off-diagonal elements of the tridiagonalized matrix
 
- Input A is replaced by the orthogonal matrix effecting the transformation (NOT eigenvectors)
=> BIG FAT WARNING! A destroyed.
tred2_cpp(self, A, N, d, e)
C++ backend for tred2, using routine
in the library
tred2_python(self, A, N, d, e)
Python backend for tred2

Data and other attributes defined here:
ZERO = 1e-10
guard = 0.94999999999999996
yTol = None