├── MANIFEST.in
├── __init__.py
├── core
├── __init__.py
├── example_residuals.py
├── utils.py
└── ode.py
├── llg
├── __init__.py
├── llg.py
├── mallinson.py
├── energy.py
└── test.py
├── algebra
├── __init__.py
├── sym-bdf3.py
└── two_predictor.py
├── .gitignore
├── setup.py
├── pre-commit
├── README.md
└── LICENSE.txt
/MANIFEST.in:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/core/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/llg/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/algebra/__init__.py:
--------------------------------------------------------------------------------
1 |
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | .ropeproject
2 | .pep8diff
3 | experiments/
4 | core/build
5 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from distutils.core import setup
2 |
3 | setup(
4 | name='SimpleLLG',
5 | version='0.1.0',
6 | author='D.Shepherd'
7 | author_email='davidshepherd7@gmail.com'
8 | packages=['simplellg']
9 | scripts=[]
10 | url=''
11 | license='LICENSE.txt',
12 | description='A simple LLG solver ... '
13 | long_description=open('README.txt').read(),
14 | install_requires=[
15 | "SciPy >= 0.10.1"
16 | ],
17 | )
18 |
--------------------------------------------------------------------------------
/pre-commit:
--------------------------------------------------------------------------------
1 | #!/bin/bash
2 |
3 | set -o errexit
4 | set -o nounset
5 |
6 | # # To install just do:
7 | # cd .git/hooks/
8 | # ln -s ../../pre-commit
9 |
10 |
11 | # Use autopep8 to clean up whitespace etc. (also store and print a diff of
12 | # what it changed)
13 | autopep8 . -d -r --aggressive --ignore=E702 --ignore=E226 \
14 | --exclude=example_residuals.py > .pep8diff
15 | cat .pep8diff
16 | patch <.pep8diff -p1
17 |
18 | echo -e "\n\n\n"
19 |
20 | # Run self tests
21 | nosetests --all-modules --processes=8
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | Python LLG ODE solver for experimenting with timesteppers
2 | ========================================================
3 |
4 | **Note**: This code is essentially **unmaintained**, it was written for experiments as part of my PhD and I have since moved on to other things. Here's an explaination I wrote (elsewhere) of when you might want to use this code and what the alternatives are:
5 |
6 | > The LLG equation is usually a PDE but it can be simplified to an ODE when all of the fields making up H_eff are constant in space. Physically this happens when you have a small (relative to the exchange length) ellipsoid of material. There's a bit more explanation about it [my thesis](https://www.escholar.manchester.ac.uk/uk-ac-man-scw:266267) in section 7.4.1. The code in this repository only deals with the ODE case. This is a useful test case if you are interested in experimenting with time integration methods, e.g. [the adaptive implicit midpoint rule that I was experimenting with](https://link.springer.com/article/10.1007/s10915-019-00965-8). It is potentially useful for some *very simple* physical problems.
7 |
8 | > For most physical problems you will need code that also models variations in space. The most widely used software for this is [OOMMF](http://math.nist.gov/oommf/) which uses finite differences for the spatial part. There's also [nmag](http://nmag.soton.ac.uk/nmag/) which uses finite element methods instead. Finite element methods allow you to accurately model more complex shapes (i.e. shapes that aren't cubeoids), but the underlying maths can be more difficult to understand. I used [oomph-lib](http://oomph-lib.maths.man.ac.uk/doc/html/index.html) together with [some extensions for micromagnetics](https://github.com/davidshepherd7/oomph-lib-micromagnetics), however the micromagnetics extensions are experimental and unmaintained so you probably only want to use this if you are directly following up on my research.
9 |
10 |
11 | Setup
12 | --------
13 |
14 | Required python modules: scipy, matplotlib, sympy.
15 |
16 | Clone into a directory named simpleode with the command:
17 |
18 | git clone https://github.com/davidshepherd7/Landau-Lifshitz-Gilbert-ODE-model.git simpleode
19 |
20 | Note that the name of the directory *must* be simpleode for the import statements to work. Next add the directory *containing* the simpleode directory to your python path with:
21 |
22 | export PYTHONPATH="$PYTHONPATH:[path/to/simpleode/../]"
23 |
24 | you probably want to put this in your shell rc file so that it is set permenantly.
25 |
26 | Apologies for the convoluted setup, I wrote this code when I was fairly new to python and I didn't follow proper packaging practices.
27 |
28 | Testing
29 | ---------
30 |
31 | Run self tests with
32 |
33 | nosetests --all-modules
34 |
35 | in the simplellg directory (this requires the nose package:
36 |
37 | sudo apt-get install python-nose
38 |
39 | on Debian based systems).
40 |
--------------------------------------------------------------------------------
/llg/llg.py:
--------------------------------------------------------------------------------
1 | """Various residuals for the LLG equation
2 | """
3 |
4 | from __future__ import division
5 | from __future__ import absolute_import
6 |
7 | from math import sin, cos, tan, log, atan2, acos, pi, sqrt
8 | import scipy as sp
9 |
10 | import simpleode.core.utils as utils
11 | import simpleode.core.ode as ode
12 |
13 |
14 | # def absmod2pi(a):
15 | # return abs(a % (2 * pi))
16 |
17 |
18 | # def llg_spherical_residual(magnetic_parameters, t, m_sph, dmdt_sph):
19 | # """ Calculate the residual for a guess at dmdt.
20 | # """
21 | # Extract the parameters
22 | # alpha = magnetic_parameters.alpha
23 | # gamma = magnetic_parameters.gamma
24 | # Ms = magnetic_parameters.Ms
25 | # H, hazi, hpol = utils.cart2sph(magnetic_parameters.Hvec)
26 |
27 | # Ensure that the angles are in the correct range
28 | # ??ds improve
29 | # _, mazi, mpol = utils.cart2sph(utils.sph2cart([Ms, m_sph[0], m_sph[1]]))
30 |
31 | # dmazidt = dmdt_sph[0]
32 | # dmpoldt = dmdt_sph[1]
33 |
34 | # Calculate fields:
35 | # no exchange, no Hms for now
36 | # anisotropy:
37 | # dEdmazi = 0
38 | # dEdmpol = -k1 * 2 * sin(pol) * cos(pol)
39 |
40 | # if hazi < 0. or hazi > 2*pi or mazi < 0. or mazi > 2*pi:
41 | # raise ValueError
42 |
43 | # Zeeman: ??ds minus sign?
44 | # if (mazi - hazi) == 0:
45 | # dEdmazi = 0.
46 | # else:
47 | # dEdmazi = - Ms * H * sin(absmod2pi(mazi - hazi)) * sp.sign(mazi - hazi)
48 |
49 | # if (mpol - hpol) == 0:
50 | # dEdmpol = 0.
51 | # else:
52 | # dEdmpol = - Ms * H * sin(abs(mpol - hpol)) * sp.sign(mpol - hpol)
53 |
54 | # print abs(mazi - hazi), abs(mpol - hpol)
55 |
56 | # From Nonlinear Magnetization Dynamics in Nanosystems By Isaak
57 | # D. Mayergoyz, Giorgio Bertotti, Claudio Serpico pg. 39 with theta =
58 | # polar angle, phi = azimuthal angle.
59 | # residual = sp.empty((2))
60 | # residual[0] = dmpoldt + (alpha * sin(mpol) * dmazidt) \
61 | # + (gamma/Ms) * (1.0/sin(mpol)) * dEdmazi
62 | # residual[1] = (sin(mpol) * dmazidt) \
63 | # - (gamma/Ms) * dEdmpol - (alpha * dmpoldt)
64 |
65 | # return residual
66 |
67 |
68 | def heff(magnetic_parameters, t, m_cart):
69 | Hk_vec = magnetic_parameters.Hk_vec(m_cart)
70 | # - ((1.0/3)*sp.array(m_cart))
71 | h_eff = magnetic_parameters.Hvec(t) + Hk_vec
72 |
73 | return h_eff
74 |
75 |
76 | def llg_cartesian_residual(magnetic_parameters, t, m_cart, dmdt_cart):
77 |
78 | # Extract the parameters
79 | alpha = magnetic_parameters.alpha
80 | gamma = magnetic_parameters.gamma
81 | Ms = magnetic_parameters.Ms
82 | h_eff = heff(magnetic_parameters, t, m_cart)
83 |
84 | residual = ((alpha/Ms) * sp.cross(m_cart, dmdt_cart)
85 | - gamma * sp.cross(m_cart, h_eff)
86 | - dmdt_cart)
87 | return residual
88 |
89 |
90 | def llg_cartesian_dfdm(magnetic_parameters, t, m_cart, dmdt_cart):
91 |
92 | # Extract the parameters
93 | alpha = magnetic_parameters.alpha
94 | gamma = magnetic_parameters.gamma
95 | Ms = magnetic_parameters.Ms
96 |
97 | h_eff = heff(magnetic_parameters, t, m_cart)
98 |
99 | dfdm = - gamma * utils.skew(h_eff) + (alpha/Ms) * utils.skew(dmdt_cart)
100 |
101 | return dfdm
102 |
103 |
104 | def ll_dmdt(magnetic_parameters, t, m):
105 | alpha = magnetic_parameters.alpha
106 | h_eff = heff(magnetic_parameters, t, m)
107 |
108 | return (
109 | -1/(1 + alpha**2) * (sp.cross(m, h_eff)
110 | + alpha*sp.cross(m, sp.cross(m, h_eff)))
111 | )
112 |
113 |
114 | def ll_residual(magnetic_parameters, t, m, dmdt):
115 | return dmdt - ll_dmdt(magnetic_parameters, t, m)
116 |
117 |
118 | def simple_llg_residual(t, m, dmdt):
119 | mp = utils.MagParameters()
120 | return llg_cartesian_residual(mp, t, m, dmdt)
121 |
122 |
123 | def simple_llg_initial(*_):
124 | return utils.sph2cart([1.0, 0.0, sp.pi/18])
125 |
126 |
127 | def linear_H(t):
128 | return sp.array([0, 0, -0.5*t])
129 |
130 |
131 | def ramping_field_llg_residual(t, m, dmdt):
132 | mp = utils.MagParameters()
133 | mp.Hvec = linear_H
134 | mp.alpha = 0.1
135 | return llg_cartesian_residual(mp, t, m, dmdt)
136 |
137 |
138 | def ramping_field_llg_initial(*_):
139 | return utils.sph2cart([1.0, 0.0, sp.pi/18])
140 |
141 |
142 | # def llg_constrained_cartesian_residual(magnetic_parameters, t, m_cart,
143 | # dmdt_cart):
144 |
145 | # base_residual = llg_cartesian_residual(magnetic_parameters, t, m_cart[:-1],
146 | # dmdt_cart[:-1])
147 |
148 | # pass
149 |
--------------------------------------------------------------------------------
/llg/mallinson.py:
--------------------------------------------------------------------------------
1 | """Calculate exact solutions for the zero dimensional LLG as given by
2 | [Mallinson2000]
3 | """
4 |
5 | from __future__ import division
6 | from __future__ import absolute_import
7 |
8 | from math import sin, cos, tan, log, atan2, acos, pi, sqrt
9 | import scipy as sp
10 | import matplotlib.pyplot as plt
11 | import functools as ft
12 |
13 | import simpleode.core.utils as utils
14 |
15 |
16 | def calculate_switching_time(magnetic_parameters, p_start, p_now):
17 | """Calculate the time taken to switch from polar angle p_start to p_now
18 | with the magnetic parameters given.
19 | """
20 |
21 | # Should never quite get to pi/2
22 | # if p_now >= pi/2:
23 | # return sp.inf
24 |
25 | # Cache some things to simplify the expressions later
26 | H = magnetic_parameters.H(None)
27 | Hk = magnetic_parameters.Hk()
28 | alpha = magnetic_parameters.alpha
29 | gamma = magnetic_parameters.gamma
30 |
31 | # Calculate the various parts of the expression
32 | prefactor = ((alpha**2 + 1)/(gamma * alpha)) \
33 | * (1.0 / (H**2 - Hk**2))
34 |
35 | a = H * log(tan(p_now/2) / tan(p_start/2))
36 | b = Hk * log((H - Hk*cos(p_start)) /
37 | (H - Hk*cos(p_now)))
38 | c = Hk * log(sin(p_now) / sin(p_start))
39 |
40 | # Put everything together
41 | return prefactor * (a + b + c)
42 |
43 |
44 | def calculate_azimuthal(magnetic_parameters, p_start, p_now):
45 | """Calculate the azimuthal angle corresponding to switching from
46 | p_start to p_now with the magnetic parameters given.
47 | """
48 | def azi_into_range(azi):
49 | a = azi % (2*pi)
50 | if a < 0:
51 | a += 2*pi
52 | return a
53 |
54 | alpha = magnetic_parameters.alpha
55 |
56 | no_range_azi = (-1/alpha) * log(tan(p_now/2) / tan(p_start/2))
57 | return azi_into_range(no_range_azi)
58 |
59 |
60 | def generate_dynamics(magnetic_parameters,
61 | start_angle=pi/18,
62 | end_angle=17*pi/18,
63 | steps=1000):
64 | """Generate a list of polar angles then return a list of corresponding
65 | m directions (in spherical polar coordinates) and switching times.
66 | """
67 | mag_params = magnetic_parameters
68 |
69 | # Construct a set of solution positions
70 | pols = sp.linspace(start_angle, end_angle, steps)
71 | azis = [calculate_azimuthal(mag_params, start_angle, p) for p in pols]
72 | sphs = [utils.SphPoint(1.0, azi, pol) for azi, pol in zip(azis, pols)]
73 |
74 | # Calculate switching times for these positions
75 | times = [calculate_switching_time(mag_params, start_angle, p)
76 | for p in pols]
77 |
78 | return (sphs, times)
79 |
80 |
81 | def plot_dynamics(magnetic_parameters,
82 | start_angle=pi/18,
83 | end_angle=17*pi/18,
84 | steps=1000):
85 | """Plot exact positions given start/finish angles and magnetic
86 | parameters.
87 | """
88 |
89 | sphs, times = generate_dynamics(magnetic_parameters, start_angle,
90 | end_angle, steps)
91 |
92 | sphstitle = "Path of m for " + str(magnetic_parameters) \
93 | + "\n (starting point is marked)."
94 | utils.plot_sph_points(sphs, title=sphstitle)
95 |
96 | timestitle = "Polar angle vs time for " + str(magnetic_parameters)
97 | utils.plot_polar_vs_time(sphs, times, title=timestitle)
98 |
99 | plt.show()
100 |
101 |
102 | def calculate_equivalent_dynamics(magnetic_parameters, polars):
103 | """Given a list of polar angles (and some magnetic parameters)
104 | calculate what the corresponding azimuthal angles and switching times
105 | (from the first angle) should be.
106 | """
107 | start_angle = polars[0]
108 |
109 | f_times = ft.partial(calculate_switching_time, magnetic_parameters,
110 | start_angle)
111 | exact_times = [f_times(p) for p in polars]
112 |
113 | f_azi = ft.partial(calculate_azimuthal, magnetic_parameters, start_angle)
114 | exact_azis = [f_azi(p) for p in polars]
115 |
116 | return exact_times, exact_azis
117 |
118 |
119 | def plot_vs_exact(magnetic_parameters, ts, ms):
120 |
121 | # Extract lists of the polar coordinates
122 | m_as_sph_points = map(utils.array2sph, ms)
123 | pols = [m.pol for m in m_as_sph_points]
124 | azis = [m.azi for m in m_as_sph_points]
125 |
126 | # Calculate the corresponding exact dynamics
127 | exact_times, exact_azis = \
128 | calculate_equivalent_dynamics(magnetic_parameters, pols)
129 |
130 | # Plot
131 | plt.figure()
132 | plt.plot(ts, pols, '--',
133 | exact_times, pols)
134 |
135 | plt.figure()
136 | plt.plot(pols, azis, '--',
137 | pols, exact_azis)
138 |
139 | plt.show()
140 |
--------------------------------------------------------------------------------
/core/example_residuals.py:
--------------------------------------------------------------------------------
1 | # Some pairs of residuals and exact solutions for testing with:
2 |
3 | from scipy import exp, tanh, sin, cos
4 | import scipy as sp
5 | import sympy
6 |
7 | from functools import partial as par
8 |
9 | def exp_residual(t, y, dydt): return y - dydt
10 | def exp_dydt(t, y): return y
11 | def exp_exact(t): return exp(t)
12 | def exp_dfdy(t, y): return 1
13 |
14 | def exp3_residual(t, y, dydt): return 3*y - dydt
15 | def exp3_dydt(t, y): return 3 * y
16 | def exp3_exact(t): return exp(3*t)
17 |
18 | # Not sure this works..
19 | def exp_of_minus_t_residual(t, y, dydt): return exp_of_minus_t_dydt(t,y) - dydt
20 | def exp_of_minus_t_exact(t): return exp(-t)
21 | def exp_of_minus_t_dydt(t, y): return -y
22 |
23 |
24 | def poly_residual(t, y, dydt): return 4*t**3 + 2*t - dydt
25 | def poly_exact(t): return t**4 + t**2
26 | def poly_dydt(t, y): return poly_residual(t, y, 0)
27 | def poly_dfdy(t, y): return 0
28 |
29 | # Useful because 2nd order integrators should be exact (and adaptive ones
30 | # should recognise this and rapidly increase dt).
31 | def square_residual(t, y, dydt): return 2*t - dydt
32 | def square_dydt(t, y): return square_residual(t, y, 0)
33 | def square_exact(t): return t**2
34 | def square_dfdy(t, y): return 0
35 |
36 |
37 | def exp_of_poly_residual(t, y, dydt): return exp_of_poly_dydt(t, y) - dydt
38 | def exp_of_poly_dydt(t, y): return y*(1 - 3*t**2)
39 | def exp_of_poly_exact(t): return exp(t - t**3)
40 |
41 |
42 | def tanh_residual(t, y, dydt, alpha=1.0, step_time=1.0):
43 | return (alpha * (1 - (tanh(alpha*(t - step_time)))**2))/2 - dydt
44 | def tanh_exact(t, alpha=1.0, step_time=1.0):
45 | return (tanh(alpha*(t - step_time)) + 1)/2
46 |
47 | def tanh_simple_residual(t, y, dydt, alpha=1.0, step_time=1.0):
48 | return (alpha * (1 - (tanh(alpha*(t - step_time)))**2)) - dydt
49 | def tanh_simple_exact(t, alpha=1.0, step_time=1.0):
50 | return tanh(alpha*(t - step_time))
51 |
52 | # Stiff example
53 | def van_der_pol_residual(t, y, dydt, mu=10):
54 | return dydt - van_der_pol_dydt(t, y, mu)
55 | def van_der_pol_dydt(t, y, mu=10):
56 | return sp.array([y[1], mu * (1 - y[0]**2)*y[1] - y[0]])
57 | # No exact solution for van der pol afaik
58 |
59 | # The classical example of a stiff ODE
60 | def stiff_damped_example_residual(t, y, dydt):
61 | return dydt - stiff_damped_example_dydt(t, y)
62 | def stiff_damped_example_dydt(t, y):
63 | return sp.dot(sp.array([[-1, 1], [1, -1000]]), y)
64 |
65 | # From G&S pg 258
66 | def stiff_example_residual(t, y, dydt):
67 | return dydt - stiff_damped_example_dydt(t, y)
68 | def stiff_example_dydt(t, y):
69 | return sp.dot(sp.array([[-1, 1], [1, -1000]]), y)
70 | def stiff_example_exact(t):
71 | l1 = 1000.0010001
72 | l2 = 0.998999
73 | return sp.array([(-l2/(l1 - l2))*sp.exp(-l1*t) + (l1/(l1 - l2))*sp.exp(-l2*t),
74 | (l2*(l1 - 1))*sp.exp(-l1*t)/(l1 - l2) + l1*(1 - l2)*sp.exp(-l2*t)/(l1 - l2)
75 | ])
76 |
77 |
78 | def midpoint_method_killer_problem(y0, g_string, l):
79 | """Generate a problem which should work badly in midpoint method.
80 | Essentially these problems consist of two parts: a "main" solution
81 | as given by g and (added to it) a damped exponential solution which
82 | decays starting from y0 - g(0) to zero in a time frame determined by
83 | l.
84 |
85 | g_string is any function specified as a string to be fed into sympy.
86 |
87 | y0 is an initial value, not equal to g(0).
88 |
89 | l (lambda ) is the coefficient of "badness".
90 |
91 | Derivation in notes 23/9/13.
92 | """
93 | sym_t, sym_y = sympy.symbols('t y')
94 |
95 | g = sympy.sympify(g_string)
96 |
97 | dgdt = sympy.diff(g, sym_t, 1)
98 | g0 = g.subs(sym_t, 0).evalf()
99 | exact_symb = (y0 - g0)*sympy.exp(-l*sym_t) + g
100 |
101 | # Don't just diff exact, or we don't get the y dependence in there!
102 | dydt_symb = -l*sym_y + l*g + sympy.diff(g, sym_t, 1)
103 | F = sympy.diff(dydt_symb, sym_y, 1)
104 |
105 | exact_f = sympy.lambdify(sym_t, exact_symb)
106 | dydt_f = sympy.lambdify((sym_t, sym_y), dydt_symb)
107 |
108 | def residual(t, y, dydt):
109 | return dydt - dydt_f(t, y)
110 |
111 | return residual, dydt_f, exact_f, (exact_symb, F)
112 |
113 | trig_midpoint_killer_problem = par(midpoint_method_killer_problem, 5,
114 | "sin(t) + cos(t)")
115 |
116 | poly_midpoint_killer_problem = par(midpoint_method_killer_problem, 5, "t**2")
117 |
118 |
119 | # ODE example for paper?
120 | def damped_oscillation_residual(omega, beta, t, y, dydt):
121 | return dydt - damped_oscillation_dydt(omega, beta, t, y)
122 | def damped_oscillation_dydt(omega, beta, t, y):
123 | return beta*sp.exp(-beta*t)*sp.sin(omega*t) - omega*sp.exp(-beta*t)*sp.cos(omega*t)
124 | def damped_oscillation_exact(omega, beta, t):
125 | return sp.exp(-beta*t) * sp.sin(omega*t)
126 |
127 | def damped_oscillation_dddydt(omega, beta, t):
128 | """See notes 16/8/2013."""
129 | a = sp.exp(- beta*t) * sp.sin(omega * t) # y in notes
130 | b = sp.exp(-beta * t) * sp.cos(omega * t) # k in notes
131 | return - beta**3 * a - omega**3 * b + omega*beta**2 * b + 3*beta*omega**2 * a
132 |
133 | def damped_oscillation_ddydt(omega, beta, t):
134 | """See notes 19/8/2013."""
135 | a = sp.exp(- beta*t) * sp.sin(omega * t)
136 | b = sp.exp(-beta * t) * sp.cos(omega * t)
137 | return (beta**2 - omega**2)*a - 2*omega*beta*b
138 |
139 |
140 | def constant_dydt(t, y):
141 | return 0
142 | def constant_residual(t, y, dydt):
143 | return dydt - constant_dydt(t, y)
144 | def constant_exact(t):
145 | return 1
146 | def constant_dfdy(t, y):
147 | return 0
148 |
--------------------------------------------------------------------------------
/llg/energy.py:
--------------------------------------------------------------------------------
1 | """Calculate energies for a single magnetisation vector in a field.
2 | """
3 |
4 | from __future__ import division
5 | from __future__ import absolute_import
6 |
7 | import operator as op
8 | from math import sin, cos, tan, log, atan2, acos, pi, sqrt
9 | import scipy as sp
10 | import itertools as it
11 |
12 | import simpleode.core.utils as utils
13 | import simpleode.llg.llg as llg
14 | from simpleode.llg.llg import heff
15 |
16 |
17 | def llg_state_energy(sph, mag_params, t=None):
18 | """Assuming unit volume, spatially constant, spherical particle.
19 |
20 | Energies taken from [Coey2010].
21 |
22 | Ignore stress and magnetostriction.
23 |
24 | t can be None if applied field is not time dependant.
25 | """
26 | return exchange_energy(sph, mag_params) \
27 | + magnetostatic_energy(sph, mag_params) \
28 | + magnetocrystalline_anisotropy_energy(sph, mag_params) \
29 | + zeeman_energy(sph, mag_params, t)
30 |
31 |
32 | def exchange_energy(sph, mag_params):
33 | """Always zero because 0D/spatially constant."""
34 | return 0.0
35 |
36 |
37 | # ??ds generalise!
38 | def magnetostatic_energy(sph, mag_params):
39 | """ For a small, spherical particle:
40 | Ems = - 0.5 mu0 (M.Hms) = 0.5/3 * Ms**2
41 | """
42 | Ms = mag_params.Ms
43 | mu0 = mag_params.mu0
44 | return (0.5/3) * mu0 * Ms**2
45 |
46 |
47 | def magnetocrystalline_anisotropy_energy(sph, mag_params):
48 | """ Eca = K1 (m.e)^2"""
49 | K1 = mag_params.K1
50 | m_cart = utils.sph2cart(sph)
51 | return K1 * (1 - sp.dot(m_cart, mag_params.easy_axis)**2)
52 |
53 |
54 | def zeeman_energy(sph, mag_params, t=None):
55 | """ Ez = - mu0 * (M.Happ(t)), t can be None if the field is not time
56 | dependant.
57 | """
58 | Ms = mag_params.Ms
59 | Happ = mag_params.Hvec(t)
60 | mu0 = mag_params.mu0
61 |
62 | m = utils.sph2cart(sph)
63 | return -1 * mu0 * Ms * sp.dot(m, Happ)
64 |
65 |
66 | def recompute_alpha(sph_start, sph_end, t_start, t_end, mag_params):
67 | """
68 | From a change in energy we can calculate what the effective damping
69 | was. For more details see [Albuquerque2001,
70 | http://dx.doi.org/10.1063/1.1355322].
71 |
72 | alpha' = - (1/(M**2)) *( dE/dt / spaceintegral( (dm/dt**2 )))
73 |
74 | No space integral is needed because we are working with 0D LLG.
75 | """
76 |
77 | Ms = mag_params.Ms
78 | dt = t_end - t_start
79 |
80 | # Estimate dEnergy / dTime
81 | dEdt = (llg_state_energy(sph_end, mag_params, t_end)
82 | - llg_state_energy(sph_start, mag_params, t_start)
83 | )/dt
84 |
85 | # Estimate dMagnetisation / dTime then take sum of squares
86 | dmdt = [(m2 - m1)/dt for m1, m2 in
87 | zip(utils.sph2cart(sph_start), utils.sph2cart(sph_end))]
88 | dmdt_sq = sp.dot(dmdt, dmdt)
89 |
90 | # dE should be negative so the result should be positive.
91 | return - (1/(Ms**2)) * (dEdt / dmdt_sq)
92 |
93 |
94 | def low_accuracy_recompute_alpha_varying_fields(
95 | sph_start, sph_end, t_start, t_end, mag_params):
96 | """
97 | Compute effective damping from change in magnetisation and change in
98 | applied field.
99 |
100 | From Nonlinear magnetization dynamics in nanosystems eqn (2.15).
101 |
102 | See notes 30/7/13.
103 |
104 | Derivatives are estimated using BDF1 finite differences.
105 | """
106 |
107 | # Only for normalised problems!
108 | assert(mag_params.Ms == 1)
109 |
110 | # Get some values
111 | dt = t_end - t_start
112 | m_cart_end = utils.sph2cart(sph_end)
113 | h_eff_end = heff(mag_params, t_end, m_cart_end)
114 | mxh = sp.cross(m_cart_end, h_eff_end)
115 |
116 | # Finite difference derivatives
117 | dhadt = (mag_params.Hvec(t_start) - mag_params.Hvec(t_end))/dt
118 |
119 | assert(all(dhadt == 0)) # no field for now
120 |
121 | dedt = (llg_state_energy(sph_end, mag_params, t_end)
122 | - llg_state_energy(sph_start, mag_params, t_start)
123 | )/dt
124 |
125 | sigma = sp.dot(mxh, mxh) / (dedt + sp.dot(m_cart_end, dhadt))
126 |
127 | possible_alphas = sp.roots([1, sigma, 1])
128 |
129 | a = (-sigma + sqrt(sigma**2 - 4))/2
130 | b = (-sigma - sqrt(sigma**2 - 4))/2
131 |
132 | possible_alphas2 = [a, b]
133 | utils.assert_list_almost_equal(possible_alphas, possible_alphas2)
134 |
135 | print(sigma, possible_alphas)
136 |
137 | def real_and_positive(x):
138 | return sp.isreal(x) and x > 0
139 |
140 | alphas = filter(real_and_positive, possible_alphas)
141 | assert(len(alphas) == 1)
142 | return sp.real(alphas[0])
143 |
144 |
145 | def recompute_alpha_varying_fields(
146 | sph_start, sph_end, t_start, t_end, mag_params):
147 | """
148 | Compute effective damping from change in magnetisation and change in
149 | applied field.
150 |
151 | See notes 30/7/13 pg 5.
152 |
153 | Derivatives are estimated using BDF1 finite differences.
154 | """
155 |
156 | # Only for normalised problems!
157 | assert(mag_params.Ms == 1)
158 |
159 | # Get some values
160 | dt = t_end - t_start
161 | m_cart_end = utils.sph2cart(sph_end)
162 | h_eff_end = heff(mag_params, t_end, m_cart_end)
163 | mxh = sp.cross(m_cart_end, h_eff_end)
164 |
165 | # Finite difference derivatives
166 | dhadt = (mag_params.Hvec(t_start) - mag_params.Hvec(t_end))/dt
167 | dedt = (llg_state_energy(sph_end, mag_params, t_end)
168 | - llg_state_energy(sph_start, mag_params, t_start)
169 | )/dt
170 | dmdt = (sp.array(utils.sph2cart(sph_start))
171 | - sp.array(m_cart_end))/dt
172 |
173 | utils.assert_almost_equal(dedt, sp.dot(m_cart_end, dhadt)
174 | + sp.dot(dmdt, h_eff_end), 1e-2)
175 |
176 | # print(sp.dot(m_cart_end, dhadt), dedt)
177 |
178 | # Calculate alpha itself using the forumla derived in notes
179 | alpha = ((dedt - sp.dot(m_cart_end, dhadt))
180 | / (sp.dot(h_eff_end, sp.cross(m_cart_end, dmdt))))
181 |
182 | return alpha
183 |
184 |
185 | def recompute_alpha_varying_fields_at_midpoint(sph_start, sph_end,
186 | t_start, t_end, mag_params):
187 | """
188 | Compute effective damping from change in magnetisation and change in
189 | applied field.
190 |
191 | See notes 30/7/13 pg 5.
192 |
193 | Derivatives are estimated using midpoint method finite differences, all
194 | values are computed at the midpoint (m = (m_n + m_n-1)/2, similarly for
195 | t).
196 | """
197 |
198 | # Only for normalised problems!
199 | assert(mag_params.Ms == 1)
200 |
201 | # Get some values
202 | dt = t_end - t_start
203 | t = (t_end + t_start)/2
204 | m = (sp.array(utils.sph2cart(sph_end))
205 | + sp.array(utils.sph2cart(sph_start)))/2
206 |
207 | h_eff = heff(mag_params, t, m)
208 | mxh = sp.cross(m, h_eff)
209 |
210 | # Finite difference derivatives
211 | dhadt = (mag_params.Hvec(t_end) - mag_params.Hvec(t_start))/dt
212 | dedt = (llg_state_energy(sph_end, mag_params, t_end)
213 | - llg_state_energy(sph_start, mag_params, t_start)
214 | )/dt
215 | dmdt = (sp.array(utils.sph2cart(sph_end))
216 | - sp.array(utils.sph2cart(sph_start)))/dt
217 |
218 | # utils.assert_almost_equal(dedt, sp.dot(m_cart_end, dhadt)
219 | # + sp.dot(dmdt, h_eff_end), 1e-2)
220 |
221 | # print(sp.dot(m_cart_end, dhadt), dedt)
222 |
223 | # Calculate alpha itself using the forumla derived in notes
224 | alpha = -((dedt + sp.dot(m, dhadt))
225 | / (sp.dot(h_eff, sp.cross(m, dmdt))))
226 |
227 | return alpha
228 |
229 |
230 | def recompute_alpha_list(m_sph_list, t_list, mag_params,
231 | alpha_func=recompute_alpha):
232 | """Compute a list of effective dampings, one for each step in the input
233 | lists.
234 | """
235 | alpha_list = it.imap(alpha_func, m_sph_list, m_sph_list[1:],
236 | t_list, t_list[1:], it.repeat(mag_params))
237 | return alpha_list
238 |
--------------------------------------------------------------------------------
/llg/test.py:
--------------------------------------------------------------------------------
1 | from __future__ import division
2 | from __future__ import absolute_import
3 |
4 |
5 | import functools as ft
6 | import matplotlib.pyplot as plt
7 | import unittest
8 | import operator as op
9 | import scipy as sp
10 | import itertools as it
11 |
12 | from math import sin, cos, tan, log, atan2, acos, pi, sqrt
13 |
14 | import simpleode.core.utils as utils
15 | import simpleode.core.ode as ode
16 | import simpleode.llg.mallinson as mlsn
17 | import simpleode.llg.energy as energy
18 | import simpleode.llg.llg as llg
19 |
20 |
21 | # We have to split out these tests into their own file because otherwise we
22 | # get circular dependencies.
23 |
24 |
25 | # Mallinson
26 | # ============================================================
27 |
28 | class MallinsonSolverCheckerBase():
29 |
30 | """Base class to define the test functions but not actually run them.
31 | """
32 |
33 | def base_init(self, magParameters=None, steps=1000,
34 | p_start=pi/18):
35 |
36 | if magParameters is None:
37 | self.mag_params = utils.MagParameters()
38 | else:
39 | self.mag_params = magParameters
40 |
41 | (self.sphs, self.times) = mlsn.generate_dynamics(
42 | self.mag_params, steps=steps)
43 |
44 | def f(sph):
45 | energy.llg_state_energy(sph, self.mag_params)
46 | self.energys = map(f, self.sphs)
47 |
48 | # Monotonically increasing time
49 | def test_increasing_time(self):
50 | print(self.mag_params.Hvec)
51 | for a, b in zip(self.times, self.times[1:]):
52 | assert(b > a)
53 |
54 | # Azimuthal is in correct range
55 | def test_azimuthal_in_range(self):
56 | for sph in self.sphs:
57 | utils.assert_azi_in_range(sph)
58 |
59 | # Monotonically decreasing azimuthal angle except for jumps at 2*pi.
60 | def test_increasing_azimuthal(self):
61 | for a, b in zip(self.sphs, self.sphs[1:]):
62 | assert(a.azi > b.azi or
63 | (a.azi - 2*pi <= 0.0 and b.azi >= 0.0))
64 |
65 | def test_damping_self_consistency(self):
66 | a2s = energy.recompute_alpha_list(self.sphs, self.times,
67 | self.mag_params)
68 |
69 | # Check that we get the same values with the varying fields version
70 | a3s = energy.recompute_alpha_list(self.sphs, self.times,
71 | self.mag_params,
72 | energy.recompute_alpha_varying_fields)
73 | utils.assert_list_almost_equal(a2s, a3s, (1.1/len(self.times)))
74 | # one of the examples doesn't quite pass with tol=1.0/len, so use
75 | # 1.1
76 |
77 | # Use 1/length as error estimate because it's proportional to dt
78 | # and so proportional to the expected error
79 | def check_alpha_ok(a2):
80 | return abs(a2 - self.mag_params.alpha) < (1.0/len(self.times))
81 | assert(all(map(check_alpha_ok, a2s)))
82 |
83 | # This is an important test. If this works then it is very likely that
84 | # the Mallinson calculator, the energy calculations and most of the
85 | # utils (so far) are all working. So tag it as "core".
86 | test_damping_self_consistency.core = True
87 |
88 |
89 | # Now run the tests with various intial settings (tests are inherited from
90 | # the base class.
91 | class TestMallinsonDefaults(MallinsonSolverCheckerBase, unittest.TestCase):
92 |
93 | def setUp(self):
94 | self.base_init() # steps=10000) ??ds
95 |
96 |
97 | class TestMallinsonHk(MallinsonSolverCheckerBase, unittest.TestCase):
98 |
99 | def setUp(self):
100 | mag_params = utils.MagParameters()
101 | mag_params.K1 = 0.6
102 | self.base_init(mag_params)
103 |
104 |
105 | class TestMallinsonLowDamping(MallinsonSolverCheckerBase, unittest.TestCase):
106 |
107 | def setUp(self):
108 | mag_params = utils.MagParameters()
109 | mag_params.alpha = 0.1
110 | self.base_init(mag_params) # , steps=10000) ??ds
111 |
112 |
113 | class TestMallinsonStartAngle(MallinsonSolverCheckerBase,
114 | unittest.TestCase):
115 |
116 | def setUp(self):
117 | self.base_init(p_start=pi/2)
118 |
119 |
120 | # llg.py
121 | # ============================================================
122 | # ??ds replace with substituting the exact solution into the residual and
123 | # checking it is zero?
124 | def test_llg_residuals():
125 | m0_sph = [0.0, pi/18]
126 | m0_cart = utils.sph2cart(tuple([1.0] + m0_sph))
127 | # m0_constrained = list(m0_cart) + [None] # ??ds
128 |
129 | residuals = [(llg.llg_cartesian_residual, m0_cart),
130 | (llg.ll_residual, m0_cart),
131 | # (llg_constrained_cartesian_residual, m0_constrained),
132 | ]
133 |
134 | for r, i in residuals:
135 | yield check_residual, r, i
136 |
137 |
138 | def check_residual(residual, initial_m):
139 | mag_params = utils.MagParameters()
140 | tmax = 3.0
141 | f_residual = ft.partial(residual, mag_params)
142 |
143 | # Timestep to a solution + convert to spherical
144 | result_times, m_list = ode.odeint(f_residual, sp.array(initial_m),
145 | tmax, dt=0.01)
146 | m_sph = [utils.array2sph(m) for m in m_list]
147 | result_pols = [m.pol for m in m_sph]
148 | result_azis = [m.azi for m in m_sph]
149 |
150 | # Calculate exact solutions
151 | exact_times, exact_azis = \
152 | mlsn.calculate_equivalent_dynamics(mag_params, result_pols)
153 |
154 | # Check
155 | utils.assert_list_almost_equal(exact_azis, result_azis, 1e-3)
156 | utils.assert_list_almost_equal(exact_times, result_times, 1e-3)
157 |
158 |
159 | def test_dfdm():
160 |
161 | ms = [utils.sph2cart([1.0, 0.0, pi/18]),
162 | utils.sph2cart([1.0, 0.0, 0.0001*pi]),
163 | utils.sph2cart([1.0, 0.0, 0.999*pi]),
164 | utils.sph2cart([1.0, 0.3*2*pi, 0.5*pi]),
165 | utils.sph2cart([1.0, 2*pi, pi/18]),
166 | ]
167 |
168 | for m in ms:
169 | yield check_dfdm, m
170 |
171 |
172 | def check_dfdm(m_cart):
173 | """Compare dfdm function with finite differenced dfdm."""
174 |
175 | # Some parameters
176 | magnetic_parameters = utils.MagParameters()
177 | t = 0.3
178 |
179 | # Use LL to get dmdt:
180 | alpha = magnetic_parameters.alpha
181 | gamma = magnetic_parameters.gamma
182 | Hvec = magnetic_parameters.Hvec(None)
183 | Ms = magnetic_parameters.Ms
184 |
185 | h_eff = Hvec
186 | dmdt_cart = (gamma/(1+alpha**2)) * sp.cross(m_cart, h_eff) \
187 | - (alpha*gamma/((1+alpha**2)*Ms)) * sp.cross(m_cart, sp.cross(
188 | m_cart, h_eff))
189 |
190 | # Calculate with function
191 | dfdm_func = llg.llg_cartesian_dfdm(
192 | magnetic_parameters,
193 | t,
194 | m_cart,
195 | dmdt_cart)
196 |
197 | def f(t, m_cart, dmdt_cart):
198 | # f is the residual + dm/dt (see notes 27/2/13)
199 | return llg.llg_cartesian_residual(magnetic_parameters,
200 | t, m_cart, dmdt_cart) + dmdt_cart
201 | # FD it
202 | dfdm_fd = sp.zeros((3, 3))
203 | r = f(t, m_cart, dmdt_cart)
204 | delta = 1e-8
205 | for i, m in enumerate(m_cart):
206 | m_temp = sp.array(m_cart).copy() # Must force a copy here
207 | m_temp[i] += delta
208 | r_temp = f(t, m_temp, dmdt_cart)
209 | r_diff = (r_temp - r)/delta
210 |
211 | for j, r_diff_j in enumerate(r_diff):
212 | dfdm_fd[i][j] = r_diff_j
213 |
214 | print dfdm_fd
215 |
216 | # Check the max of the difference
217 | utils.assert_almost_zero(sp.amax(dfdm_func - dfdm_fd), 1e-6)
218 |
219 |
220 | # energy.py
221 | # ============================================================
222 | def test_zeeman():
223 | """Test zeeman energy for some simple cases.
224 | """
225 | H_tests = [lambda t: sp.array([0, 0, 10]),
226 | lambda t: sp.array([-sqrt(2)/2, -sqrt(2)/2, 0.0]),
227 | lambda t: sp.array([0, 1, 0]),
228 | lambda t: sp.array([0.01, 0.0, 0.01]),
229 | ]
230 |
231 | m_tests = [(1.0, 0.0, 0.0),
232 | utils.cart2sph((sqrt(2)/2, sqrt(2)/2, 0.0)),
233 | (1, 0, 1),
234 | (0.0, 100.0, 0.0),
235 | ]
236 |
237 | answers = [lambda mP: -1 * mP.mu0 * mP.Ms * mP.H(None),
238 | lambda mP: mP.mu0 * mP.Ms * mP.H(None),
239 | lambda _:0.0,
240 | lambda _:0.0,
241 | ]
242 |
243 | for m, H, ans in zip(m_tests, H_tests, answers):
244 | yield check_zeeman, m, H, ans
245 |
246 |
247 | def check_zeeman(m, H, ans):
248 | """Helper function for test_zeeman."""
249 | mag_params = utils.MagParameters()
250 | mag_params.Hvec = H
251 | utils.assert_almost_equal(energy.zeeman_energy(m, mag_params),
252 | ans(mag_params))
253 |
254 |
255 | # See also mallinson.py: test_self_consistency for checks on alpha
256 | # recomputation using Mallinson's exact solution.
257 |
258 | # To test for applied fields we would need to do real time integration,
259 | # which is a bit too large of a dependancy to have in a unit test, so do it
260 | # somewhere else.
261 |
--------------------------------------------------------------------------------
/algebra/sym-bdf3.py:
--------------------------------------------------------------------------------
1 |
2 | from __future__ import division
3 | from __future__ import absolute_import
4 |
5 | import sympy
6 | import scipy.misc
7 | import sys
8 | import itertools as it
9 |
10 | from sympy import Rational as sRat
11 | from operator import mul
12 | from functools import partial as par
13 |
14 | import simpleode.core.utils as utils
15 | from functools import reduce
16 |
17 |
18 | # A set of functions for symbolically calculating bdf forumlas.
19 |
20 |
21 | # Define some (global) symbols to use
22 | dts = list(sympy.var('Delta:9', real=True))
23 | dys = list(sympy.var('Dy:9', real=True))
24 | ys = list(sympy.var('y:9', real=True))
25 |
26 | # subs i => step n+1-i (with Delta_{n+1} = t_{n+1} - t_n)
27 |
28 |
29 | def divided_diff(order, ys, dts):
30 | """Caluclate divided differences of the list of values given
31 | in ys at points separated by the values in dts.
32 |
33 | Should work with symbols or numbers, only tested with symbols.
34 | """
35 | assert(len(ys) == order+1)
36 | assert(len(dts) == order)
37 |
38 | if order > 1:
39 | return ((divided_diff(order-1, ys[:-1], dts[:-1])
40 | - divided_diff(order-1, ys[1:], dts[1:]))
41 | /
42 | sum(dts))
43 | else:
44 | return (ys[0] - ys[-1])/(dts[0])
45 |
46 |
47 | def old_bdf_prefactor(order, implicit):
48 | """Calculate the non-divided difference part of the bdf approximation.
49 | For implicit this is the product term in (5.12) on page 400 of
50 | Hairer1991. For explicit it's more tricky and not given in any book
51 | that I've found, I derived it from expressions on pgs 400, 366 of
52 | Hairer1991.
53 | """
54 |
55 | def accumulate(iterable):
56 | """Return running totals (from python 3.2), i.e.
57 |
58 | accumulate([1,2,3,4,5]) --> 1 3 6 10 15
59 | """
60 | it = iter(iterable)
61 | total = next(it)
62 | yield total
63 | for element in it:
64 | total = total + element
65 | yield total
66 |
67 | assert(order >= 0)
68 |
69 | if order == 0:
70 | return 0
71 | elif order == 1:
72 | return 1
73 | else:
74 | if implicit:
75 | # dt0 * (dt0 + dt1) * (dt0 + dt1 + dt2) * ... (dt0 + dt1 + ... +
76 | # dt_{order-1})
77 | return _product(accumulate(dts[0:order-1]))
78 | else:
79 | # the maths is messy here... Basically the same as above but
80 | # with some different terms
81 | terms = it.chain([dts[0]], accumulate(dts[1:order-1]))
82 | return -1 * _product(terms)
83 |
84 |
85 | def _steps_diff_to_list_of_dts(a, b, missing=None):
86 | """Get t_a - t_b in terms of dts.
87 |
88 | e.g.
89 | a = 0, b = 2:
90 | t_0 - t_2 = t_{n+1} - t_{n-1} = dt_{n+1} + dt_n = dts[0] + dts[1]
91 |
92 | a = 2, b = 0:
93 | t_2 - t_0 = - dts[0] - dts[1]
94 | """
95 | # if a and b are in the "wrong" order then it's just the negative of
96 | # the sum with them in the "right" order.
97 | if a > b:
98 | return map(lambda x: -1*x, _steps_diff_to_list_of_dts(b, a, missing))
99 |
100 | return dts[a:b]
101 |
102 |
103 | def _product(l):
104 | """Return the product (i.e. all entrys multiplied together) of a list or iterator.
105 | """
106 | return reduce(mul, l, 1)
107 |
108 |
109 | def bdf_prefactor(order, derivative_point):
110 | """Calculate the non-divided difference part of the bdf approximation
111 | with the derivative known at any integer point. For implicit BDF the
112 | known derivative is at n+1 (so derivative point = 0), others it is
113 | further back in time (>0).
114 | """
115 | assert(order >= 0)
116 | assert(derivative_point >= 0)
117 |
118 | if order == 0:
119 | return 0
120 |
121 | terms = 0
122 |
123 | # For each i in the summation (Note that for most i, for low derivative
124 | # point the contribution is zero. It's possible to do fancy algebra to
125 | # speed this up, but it's just not worth it!)
126 | for i in range(0, order):
127 | # Get a list of l values for which to calculate the product terms.
128 | l_list = [l for l in range(0, order) if l != i]
129 |
130 | # Calculate a list of product terms (in terms of dts).
131 | c = map(lambda b: sum(_steps_diff_to_list_of_dts(derivative_point, b)),
132 | l_list)
133 |
134 | # Multiply together and add to total
135 | terms = terms + _product(c)
136 |
137 | return terms
138 |
139 |
140 | def bdf_method(order, derivative_point=0):
141 | """Calculate the bdf approximation for dydt. If implicit approximation
142 | is at t_{n+1}, otherwise it is at t_n.
143 | """
144 |
145 | # Each term is just the appropriate order prefactor multiplied by a
146 | # divided difference. Basically just a python implementation of
147 | # equation (5.12) on page 400 of Hairer1991.
148 | def single_term(n):
149 | return (
150 | bdf_prefactor(
151 | n,
152 | derivative_point) * divided_diff(n,
153 | ys[:n+1],
154 | dts[:n])
155 | )
156 |
157 | return sum(map(single_term, range(1, order+1)))
158 |
159 |
160 | def main():
161 |
162 | print sympy.pretty(sympy.collect(bdf_method(2, 0).expand(), ys).simplify())
163 |
164 | print "code for ibdf2 step:"
165 | print my_bdf_code_gen(2, 0, True)
166 |
167 | # print "\n\n code for eBDF3 step:"
168 | # print my_bdf_code_gen(3, 1, False)
169 |
170 | # print "\n\n code for iBDF3 dydt approximation:"
171 | # print my_bdf_code_gen(3, 0, True)
172 |
173 | print "\n\n code for iBDF3 step:"
174 | print my_bdf_code_gen(3, 0, True)
175 |
176 | # print "\n\n code for iBDF4 dydt approximation:"
177 | # print my_bdf_code_gen(4, 0, True)
178 |
179 | print "\n\n code for eBDF3 step w/ derivative at n-1:"
180 | print my_bdf_code_gen(3, 2, True)
181 |
182 | # print sympy.pretty(sympy.Eq(dys[2], bdf_method(1, 2)))
183 | # print sympy.pretty(sympy.Eq(dys[2], bdf_method(2, 2)))
184 | # print sympy.pretty(sympy.Eq(dys[2], bdf_method(3, 2)))
185 |
186 |
187 | def my_bdf_code_gen(order, derivative_point, solve_for_ynp1):
188 |
189 | dydt_expr = bdf_method(order, derivative_point)
190 |
191 | if solve_for_ynp1:
192 | # Set equal to dydt at derivative-point-th step, then solve for y_{n+1}
193 | bdf_method_solutions = sympy.solve(sympy.Eq(dydt_expr,
194 | dys[derivative_point]), y0)
195 |
196 | # Check there's one solution only
197 | assert(len(bdf_method_solutions) == 1)
198 |
199 | # Convert it to a string
200 | bdf_method_code = str(
201 | bdf_method_solutions[0].expand().collect(ys+dys).simplify())
202 |
203 | else:
204 | bdf_method_code = str(dydt_expr.expand().collect(ys+dys).simplify())
205 |
206 | # Replace the sympy variables with variable names consistent with my
207 | # code in ode.py
208 | sympy_to_odepy_code_string_replacements = \
209 | {'Delta0': 'dtn', 'Delta1': 'dtnm1', 'Delta2': 'dtnm2', 'Delta3': 'dtnm3',
210 | 'Dy0': 'dynp1', 'Dy1': 'dyn', 'Dy2': 'dynm1',
211 | 'y0': 'ynp1', 'y1': 'yn', 'y2': 'ynm1', 'y3': 'ynm2', 'y4': 'ynm3'}
212 |
213 | # This is a rubbish way to do mass replace (many passes through the
214 | # text, any overlapping replaces will cause crazy behaviour) but it's
215 | # good enough for our purposes.
216 | for key, val in sympy_to_odepy_code_string_replacements.iteritems():
217 | bdf_method_code = bdf_method_code.replace(key, val)
218 |
219 | # Check that none of the replacements contain things that will be
220 | # replaced by other replacement operations. Maybe slow but good to test
221 | # just in case...
222 | for _, replacement in sympy_to_odepy_code_string_replacements.iteritems():
223 | for key, _ in sympy_to_odepy_code_string_replacements.iteritems():
224 | assert(replacement not in key)
225 |
226 | return bdf_method_code
227 |
228 |
229 | if __name__ == '__main__':
230 | sys.exit(main())
231 |
232 |
233 | # Tests
234 | # ============================================================
235 |
236 | def assert_sym_eq(a, b):
237 | """Compare symbolic expressions. Note that the simplification algorithm
238 | is not completely robust: might give false negatives (but never false
239 | positives).
240 |
241 | Try adding extra simplifications if needed, e.g. add .trigsimplify() to
242 | the end of my_simp.
243 | """
244 |
245 | def my_simp(expr):
246 | # Can't .expand() ints, so catch the zero case separately.
247 | try:
248 | return expr.expand().simplify()
249 | except AttributeError:
250 | return expr
251 |
252 | print
253 | print sympy.pretty(my_simp(a))
254 | print "equals"
255 | print sympy.pretty(my_simp(b))
256 | print
257 |
258 | # Try to simplify the difference to zero
259 | assert (my_simp(a - b) == 0)
260 |
261 |
262 | def check_const_step(order, exact, derivative_point):
263 |
264 | # Derive bdf method
265 | b = bdf_method(order, derivative_point)
266 |
267 | # Set all step sizes to be Delta0
268 | b_const_step = b.subs({k: Delta0 for k in dts})
269 |
270 | # Compare with exact
271 | assert_sym_eq(exact, b_const_step)
272 |
273 |
274 | def test_const_step_implicit():
275 | """Check that the implicit methods are correct for fixed step size by
276 | comparison with Hairer et. al. 1991 pg 366.
277 | """
278 |
279 | exacts = [(y0 - y1)/Delta0,
280 | (sRat(3, 2)*y0 - 2*y1 + sRat(1, 2)*y2)/Delta0,
281 | (sRat(11, 6)*y0 - 3*y1 + sRat(3, 2)*y2 - sRat(1, 3)*y3)/Delta0,
282 | (sRat(25, 12)*y0 - 4*y1 + 3*y2 - sRat(4, 3)*y3 + sRat(1, 4)*y4)/Delta0]
283 |
284 | orders = [1, 2, 3, 4]
285 |
286 | for order, exact in zip(orders, exacts):
287 | yield check_const_step, order, exact, 0
288 |
289 |
290 | def test_const_step_explicit():
291 |
292 | # Get explicit BDF2 (implicit midpoint)'s dydt approximation G&S pg 715
293 | a = sympy.solve(-y0 + y1 + (1 + Delta0/Delta1)*Delta0*Dy1
294 | - (Delta0/Delta1)**2*(y1 - y2), Dy1)
295 | assert(len(a) == 1)
296 | IMR_bdf_form = a[0].subs({k: Delta0 for k in dts})
297 |
298 | orders = [1, 2, 3]
299 | exacts = [(y0 - y1)/Delta0,
300 | IMR_bdf_form,
301 | #Hairer pg 364
302 | (sRat(1, 3)*y0 + sRat(1, 2)*y1 - y2 + sRat(1, 6)*y3)/Delta0
303 | ]
304 |
305 | for order, exact in zip(orders, exacts):
306 | yield check_const_step, order, exact, 1
307 |
308 |
309 | def test_variable_step_implicit_bdf2():
310 |
311 | # From Gresho and Sani pg 715
312 | exact = sympy.solve(-(y0 - y1)/Delta0 +
313 | (Delta0 / (2*Delta0 + Delta1)) * (y1 - y2)/Delta1 +
314 | ((Delta0 + Delta1)/(2*Delta0 + Delta1)) * Dy0, Dy0)
315 |
316 | # Should only be one solution, get it
317 | assert(len(exact) == 1)
318 | exact = exact[0]
319 |
320 | # Get the method using my code
321 | mine = bdf_method(2, 0)
322 |
323 | assert_sym_eq(exact, mine)
324 |
325 |
326 | def test_variable_step_explicit_bdf2():
327 |
328 | # Also from Gresho and Sani pg 715
329 | exact = sympy.solve(-y0 + y1 + (1 + Delta0/Delta1)*Delta0*Dy1
330 | - (Delta0/Delta1)**2*(y1 - y2), Dy1)
331 |
332 | # Should only be one solution, get it
333 | assert(len(exact) == 1)
334 | exact = exact[0]
335 |
336 | # Get the method using my code
337 | mine = bdf_method(2, 1)
338 |
339 | assert_sym_eq(exact, mine)
340 |
341 |
342 | def test_list_dts():
343 |
344 | # Check we have a list (not a tuple like before...)
345 | assert list(
346 | _steps_diff_to_list_of_dts(2,
347 | 0)) == _steps_diff_to_list_of_dts(2,
348 | 0)
349 | assert list(
350 | _steps_diff_to_list_of_dts(0,
351 | 2)) == _steps_diff_to_list_of_dts(0,
352 | 2)
353 |
354 | map(assert_sym_eq, _steps_diff_to_list_of_dts(0, 2), [dts[0], dts[1]])
355 | map(assert_sym_eq, _steps_diff_to_list_of_dts(2, 0), [-dts[0], -dts[1]])
356 |
357 | assert _steps_diff_to_list_of_dts(2, 2) == []
358 |
359 |
360 | def test_product():
361 | assert _product([]) == 1
362 | assert _product(xrange(1, 11)) == scipy.misc.factorial(10, True)
363 | assert _product(xrange(0, 101)) == 0
364 |
365 |
366 | def test_generalised_bdf_prefactor():
367 | def check(order, implicit):
368 | old = old_bdf_prefactor(order, implicit)
369 | if implicit:
370 | new = bdf_prefactor(order, 0)
371 | else:
372 | new = bdf_prefactor(order, 1)
373 | assert_sym_eq(old, new)
374 |
375 | orders = [0, 1, 2, 3, 4]
376 | for order in orders:
377 | for implicit in [True, False]:
378 | yield check, order, implicit
379 |
380 | def check_new_ones(order, real_value):
381 | calculated = bdf_prefactor(order, 2)
382 | assert_sym_eq(real_value, calculated)
383 |
384 | real_values = [(0, 0),
385 | (1, 1),
386 | (2, (-dts[0] - dts[1]) - dts[1]),
387 | (3, (-dts[0] - dts[1])*-dts[1]),
388 | (4, (-dts[0] - dts[1])*-dts[1]*dts[2]),
389 | ]
390 | for order, real_value in real_values:
391 | yield check_new_ones, order, real_value
392 |
--------------------------------------------------------------------------------
/core/utils.py:
--------------------------------------------------------------------------------
1 |
2 | from __future__ import division
3 | from __future__ import absolute_import
4 |
5 | import collections
6 | import scipy as sp
7 | import scipy.linalg
8 | import itertools as it
9 | import operator as op
10 | import functools as ft
11 | import sympy
12 | import math
13 |
14 | from functools import partial as par
15 | from os.path import join as pjoin
16 | from math import sin, cos, tan, log, atan2, acos, pi, sqrt
17 |
18 |
19 | # General
20 | # ============================================================
21 |
22 |
23 | def unzip(iterable_of_iterables):
24 | """Inverse of zip. E.g. given a list of tuples returns a tuple of
25 | lists.
26 |
27 | To understand why: think about what * does to a list and what zip then
28 | does with this list.
29 |
30 | See http://www.shocksolution.com/2011/07/python-lists-to-tuples-and-tuples-to-lists/"""
31 | return zip(*iterable_of_iterables)
32 |
33 |
34 | def _apply_to_list_and_print_args(function, list_of_args):
35 | """Does what it says. Should really be a lambda function but
36 | multiprocessing requires named functions
37 | """
38 | print list_of_args
39 | return function(*list_of_args)
40 |
41 |
42 | def parallel_parameter_sweep(function, parameter_lists, serial_mode=False):
43 | """Run function with all combinations of parameters in parallel using
44 | all available cores.
45 |
46 | parameter_lists should be a list of lists of parameters,
47 | """
48 |
49 | import multiprocessing
50 |
51 | # Generate a complete set of combinations of parameters
52 | parameter_sets = it.product(*parameter_lists)
53 |
54 | # multiprocessing doesn't include a "starmap", requires all functions
55 | # to take a single argument. Use a function wrapper to fix this. Also
56 | # print the list of args while we're in there.
57 | wrapped_function = par(_apply_to_list_and_print_args, function)
58 |
59 | # For debugging we often need to run in serial (to get useful stack
60 | # traces).
61 | if serial_mode:
62 | results_iterator = it.imap(wrapped_function, parameter_sets)
63 | # Force evaluation (to be exactly the same as in parallel)
64 | results_iterator = list(results_iterator)
65 |
66 | else:
67 | # Run in all parameter sets in parallel
68 | pool = multiprocessing.Pool()
69 | results_iterator = pool.imap_unordered(
70 | wrapped_function, parameter_sets)
71 | pool.close()
72 |
73 | # wait for everything to finish
74 | pool.join()
75 |
76 | return results_iterator
77 |
78 |
79 | def partial_lists(l, min_list_length=1):
80 | """Given a list l return a list of "partial lists" (probably not the
81 | right term...).
82 |
83 | Optionally specify a minimum list length.
84 |
85 | ie.
86 |
87 | l = [0, 1, 2, 3]
88 |
89 | partial_lists(l) = [[0], [0, 1], [0, 1, 2], [0, 1, 2, 3]]
90 | """
91 | all_lists = [l[:i] for i in range(0, len(l)+1)]
92 | return filter(lambda x: len(x) >= min_list_length, all_lists)
93 |
94 |
95 | def myfigsave(
96 | figure, name, texpath="/home/david/Dropbox/phd/reports/ongoing-writeup/images"):
97 | """Fix up layout and save a pdf of an image into my latex folder.
98 | """
99 |
100 | # Fix layout
101 | figure.tight_layout(pad=0.3)
102 |
103 | # Save a pdf into my tex image dir
104 | figpath = pjoin(texpath, name)
105 | figure.savefig(figpath, dpi=300, orientation='portrait',
106 | transparent=False)
107 |
108 | print "Saved to", figpath
109 | return
110 |
111 |
112 | def memoize(f):
113 | """ Memoization decorator for a function taking multiple arguments.
114 |
115 | From http://code.activestate.com/recipes/578231-probably-the-fastest-memoization-decorator-in-the-/
116 | (in the comments)
117 | """
118 | class memodict(dict):
119 |
120 | def __init__(self, f):
121 | self.f = f
122 |
123 | def __call__(self, *args):
124 | return self[args]
125 |
126 | def __missing__(self, key):
127 | ret = self[key] = self.f(*key)
128 | return ret
129 | return memodict(f)
130 |
131 |
132 | def latex_escape(s):
133 | """Escape all characters that latex will cry about.
134 | """
135 | s = s.replace(r'{', r'\{')
136 | s = s.replace(r'}', r'\}')
137 | s = s.replace(r'&', r'\&')
138 | s = s.replace(r'%', r'\%')
139 | s = s.replace(r'$', r'\$')
140 | s = s.replace(r'#', r'\#')
141 | s = s.replace(r'_', r'\_')
142 | s = s.replace(r'^', r'\^{}')
143 |
144 | # Can't handle backslashes... ?
145 |
146 | return s
147 |
148 |
149 | # Testing helpers
150 | # ============================================================
151 |
152 |
153 | def almost_equal(a, b, tol=1e-9):
154 | return abs(a - b) < tol
155 |
156 |
157 | def abs_list_diff(list_a, list_b):
158 | return [abs(a - b) for a, b in zip(list_a, list_b)]
159 |
160 |
161 | def list_almost_zero(list_x, tol=1e-9):
162 | return max(list_x) < tol
163 |
164 |
165 | def list_almost_equal(list_a, list_b, tol=1e-9):
166 | return list_almost_zero(abs_list_diff(list_a, list_b), tol)
167 |
168 |
169 | def same_order_of_magnitude(a, b, fp_zero):
170 | if abs(a) < fp_zero or abs(b) < fp_zero:
171 | return abs(a) < fp_zero and abs(b) < fp_zero
172 | else:
173 | return (abs(sp.log10(abs(a)) - sp.log10(abs(b))) < 1)
174 |
175 |
176 | def same_sign(a, b, fp_zero):
177 | """Check if two floats (or probably fine for other numbers) have the
178 | same sign. Throw an error on NaN values. Treat small floats as zero and
179 | treat zero as not having a sign.
180 | """
181 | if (a == sp.NaN) or (b == sp.NaN):
182 | raise ValueError("NaN(s) passed to sign comparison functions")
183 | elif (abs(a) < fp_zero) and (abs(b) < fp_zero):
184 | return True
185 | else:
186 | return math.copysign(1, a) == math.copysign(1, b)
187 |
188 |
189 | # Some useful asserts. We explicitly use the assert command in each
190 | # (instead of defining the asserts in terms of the bool-returning functions
191 | # above) to get useful output from nose -d.
192 | def assert_almost_equal(a, b, tol=1e-9):
193 | assert(abs(a - b) < tol)
194 |
195 |
196 | def assert_almost_zero(a, tol=1e-9):
197 | assert(abs(a) < tol)
198 |
199 |
200 | def assert_list_almost_equal(list_a, list_b, tol=1e-9):
201 | assert(len(list(list_a)) == len(list(list_b)))
202 | for a, b in zip(list_a, list_b):
203 | assert(abs(a - b) < tol)
204 |
205 |
206 | def assert_list_almost_zero(values, tol=1e-9):
207 | for x in values:
208 | assert abs(x) < tol
209 |
210 |
211 | def assert_sym_eq(a, b):
212 | """Compare symbolic expressions. Note that the simplification algorithm
213 | is not completely robust: might give false negatives (but never false
214 | positives).
215 |
216 | Try adding extra simplifications if needed, e.g. add .trigsimplify() to
217 | the end of my_simp.
218 | """
219 |
220 | def my_simp(expr):
221 | # Can't .expand() ints, so catch the zero case separately.
222 | try:
223 | return expr.expand().simplify()
224 | except AttributeError:
225 | return expr
226 |
227 | print
228 | print sympy.pretty(my_simp(a))
229 | print "equals"
230 | print sympy.pretty(my_simp(b))
231 | print
232 |
233 | # Try to simplify the difference to zero
234 | assert (my_simp(a - b) == 0)
235 |
236 |
237 | def assert_same_sign(a, b, fp_zero=1e-9):
238 | if (a == sp.NaN) or (b == sp.NaN):
239 | raise ValueError("NaN(s) passed to sign comparison functions")
240 | elif (abs(a) < fp_zero) and (abs(b) < fp_zero):
241 | assert True
242 | else:
243 | assert math.copysign(1, a) == math.copysign(1, b)
244 |
245 |
246 | def assert_same_order_of_magnitude(a, b, fp_zero=1e-14):
247 | """Check that log10(abs(.)) are nearby for a and b. If a or b is below
248 | fp_zero then the other is checked in the same way for closeness to
249 | fp_zero (after checking that it is not also below fp_zero, for safety
250 | with log10).
251 | """
252 | if abs(a) < fp_zero:
253 | assert abs(b) < fp_zero or (
254 | sp.log10(abs(b)) - sp.log10(abs(fp_zero)) < 1)
255 | if abs(b) < fp_zero:
256 | assert abs(a) < fp_zero or (
257 | sp.log10(abs(a)) - sp.log10(abs(fp_zero)) < 1)
258 | else:
259 | assert (abs(sp.log10(abs(a)) - sp.log10(abs(b))) < 1)
260 |
261 |
262 | # Spherical polar coordinates asserts
263 | def assert_azi_in_range(sph):
264 | assert(sph.azi > 0 or almost_equal(sph.azi, 0.0))
265 | assert(sph.azi < 2*pi or almost_equal(sph.azi, 2*pi))
266 |
267 |
268 | def assert_polar_in_range(sph):
269 | assert(sph.pol >= 0 and sph.pol <= pi)
270 |
271 |
272 | # Convert symbolic expressions to useful python functions
273 | # ============================================================
274 |
275 | def symb2deriv(exact_symb, order):
276 | t, y, Dy = sympy.symbols('t y Dy')
277 | deriv_symb = sympy.diff(exact_symb, t, order).subs(exact_symb, y)
278 | deriv = sympy.lambdify((t, y), deriv_symb)
279 | return deriv
280 |
281 |
282 | def symb2residual(exact_symb):
283 | t, y, Dy = sympy.symbols('t y Dy')
284 | dydt_symb = sympy.diff(exact_symb, t, 1).subs(exact_symb, y)
285 | residual_symb = Dy - dydt_symb
286 | residual = sympy.lambdify((t, y, Dy), residual_symb)
287 | return residual
288 |
289 |
290 | def symb2jacobian(exact_symb):
291 | t, y, Dy = sympy.symbols('t y Dy')
292 | dydt_symb = sympy.diff(exact_symb, t, 1).subs(exact_symb, y)
293 | jacobian_symb = sympy.diff(dydt_symb, y, 1).subs(exact_symb, y)
294 | jacobian = sympy.lambdify((t, y), jacobian_symb)
295 | return jacobian
296 |
297 |
298 | def symb2functions(exact_symb):
299 | t, y, Dy = sympy.symbols('t y Dy')
300 | exact = sympy.lambdify(t, exact_symb)
301 | residual = symb2residual(exact_symb)
302 | dys = [None]+map(par(symb2deriv, exact_symb), range(1, 10))
303 | jacobian = symb2jacobian(exact_symb)
304 | return exact, residual, dys, jacobian
305 |
306 |
307 | # Coordinate systems
308 | # ============================================================
309 |
310 | # Some data structures
311 | SphPoint = collections.namedtuple('SphPoint', ['r', 'azi', 'pol'])
312 | CartPoint = collections.namedtuple('CartPoint', ['x', 'y', 'z'])
313 |
314 |
315 | def cart2sph(cartesian_point):
316 | """
317 | Convert a 3D cartesian tuple into spherical polars.
318 |
319 | In the form (r,azi, pol) = (r, theta, phi) (following convention from
320 | mathworld).
321 |
322 | In Mallinson's notation this is (r, phi, theta).
323 | """
324 | x, y, z = cartesian_point
325 |
326 | r = sp.linalg.norm(cartesian_point, 2)
327 |
328 | # Get azimuthal then shift from [-pi,pi] to [0,2pi]
329 | azi = atan2(y, x)
330 | if azi < 0:
331 | azi += 2*pi
332 |
333 | # Dodge the problem at central singular point...
334 | if r < 1e-9:
335 | polar = 0
336 | else:
337 | polar = acos(z/r)
338 |
339 | return SphPoint(r, azi, polar)
340 |
341 |
342 | def sph2cart(spherical_point):
343 | """
344 | Convert a 3D spherical polar coordinate tuple into cartesian
345 | coordinates. See cart2sph(...) for spherical coordinate scheme."""
346 |
347 | r, azi, pol = spherical_point
348 |
349 | x = r * cos(azi) * sin(pol)
350 | y = r * sin(azi) * sin(pol)
351 | z = r * cos(pol)
352 |
353 | return CartPoint(x, y, z)
354 |
355 |
356 | def array2sph(point_as_array):
357 | """ Convert from an array representation to a SphPoint.
358 | """
359 |
360 | assert point_as_array.ndim == 1
361 |
362 | # Hopefully 2 dims => spherical coords
363 | if point_as_array.shape[0] == 2:
364 | azi = point_as_array[0]
365 | pol = point_as_array[1]
366 | return SphPoint(1.0, azi, pol)
367 |
368 | # Presumably in cartesian...
369 | elif point_as_array.shape[0] == 3:
370 | return cart2sph(SphPoint(point_as_array[0],
371 | point_as_array[1],
372 | point_as_array[2]))
373 |
374 | else:
375 | raise IndexError
376 |
377 |
378 | def plot_sph_points(sphs, title='Path of m'):
379 | carts = map(sph2cart, sphs)
380 |
381 | fig = plt.figure()
382 | ax = fig.add_subplot(111, projection='3d')
383 |
384 | # Plot the path
385 | xs, ys, zs = unzip(carts)
386 | ax.plot(xs, ys, zs)
387 |
388 | # Draw on the starting point
389 | start_point = carts[0]
390 | ax.scatter(start_point.x, start_point.y, start_point.z)
391 |
392 | # Draw on z-axis
393 | ax.plot([0, 0], [0, 0], [-1, 1], '--')
394 |
395 | plt.title(title)
396 |
397 | # Axes
398 | ax.set_zlim(-1, 1)
399 | ax.set_xlim(-1, 1)
400 | ax.set_ylim(-1, 1)
401 |
402 | return fig
403 |
404 |
405 | def plot_polar_vs_time(sphs, times, title='Polar angle vs time'):
406 |
407 | fig = plt.figure()
408 | ax = fig.add_subplot(111)
409 |
410 | rs, azis, pols = unzip(sphs)
411 | ax.plot(times, pols)
412 |
413 | plt.xlabel('time/ arb. units')
414 | plt.ylabel('polar angle/ radians')
415 | plt.title(title)
416 |
417 | return fig
418 |
419 |
420 | class MagParameters():
421 |
422 | def Hvec(self, t):
423 | return sp.array([0, 0, -2])
424 |
425 | gamma = 1.0
426 | K1 = 0.0
427 | Ms = 1.0
428 | mu0 = 1.0
429 | easy_axis = sp.array([0, 0, 1])
430 |
431 | def __init__(self, alpha=1.0):
432 | self.alpha = alpha
433 |
434 | def dimensional_H(self, t):
435 | return sp.linalg.norm(self.Hvec(t), ord=2)
436 |
437 | def H(self, t):
438 | return sp.linalg.norm(self.Hvec(t)/self.Ms, ord=2)
439 |
440 | def dimensional_Hk(self):
441 | """Ansiotropy field strength."""
442 | # ??ds if m is always unit vector then this is right, if not we
443 | # need extra factor of Ms on bottom...
444 | return (2 * self.K1) / (self.mu0 * self.Ms)
445 |
446 | def Hk(self):
447 | """Ansiotropy field strength."""
448 | # ??ds if m is always unit vector then this is right, if not we
449 | # need extra factor of Ms on bottom...
450 | return self.dimensional_Hk() / self.Ms
451 |
452 | def dimensional_Hk_vec(self, m_cart):
453 | """Uniaxial anisotropy field. Magnetisation should be in normalised
454 | cartesian form."""
455 | return (
456 | self.dimensional_Hk() * sp.dot(
457 | m_cart, self.easy_axis) * self.easy_axis
458 | )
459 |
460 | def Hk_vec(self, m_cart):
461 | """Normalised uniaxial anisotropy field. Magnetisation should be in
462 | normalised cartesian form."""
463 | return self.dimensional_Hk_vec(m_cart) / self.Ms
464 |
465 | def __repr__(self):
466 | """Return a string representation of the parameters.
467 | """
468 | return "alpha = " + str(self.alpha) \
469 | + ", gamma = " + str(self.gamma) + ",\n" \
470 | + "H(0) = " + str(self.Hvec(0)) \
471 | + ", K1 = " + str(self.K1) \
472 | + ", Ms = " + str(self.Ms)
473 |
474 |
475 | # Smaller helper functions
476 | # ============================================================
477 |
478 |
479 | def relative_error(exact, estimate):
480 | return abs(exact - estimate) / exact
481 |
482 |
483 | def dts_from_ts(ts):
484 | return list(map(op.sub, ts[1:], ts[:-1]))
485 |
486 | ts2dts = dts_from_ts
487 |
488 |
489 | def dts2ts(base, dts):
490 | ts = [base]
491 | for dt in dts:
492 | ts.append(ts[-1] + dt)
493 |
494 | return ts
495 |
496 |
497 | def ts2dtn(ts):
498 | return ts[-1] - ts[-2]
499 |
500 |
501 | def ts2dtnm1(ts):
502 | return ts[-2] - ts[-3]
503 |
504 |
505 | # Matrices
506 | # ============================================================
507 |
508 | def skew(vector_with_length_3):
509 | v = vector_with_length_3
510 |
511 | if len(v) != 3:
512 | raise TypeError("skew is only defined for vectors of length 3")
513 |
514 | return sp.array([[0, -v[2], v[1]],
515 | [v[2], 0, -v[0]],
516 | [-v[1], v[0], 0]])
517 |
518 | # Test this file's code
519 | # ============================================================
520 |
521 | import unittest
522 | from random import random
523 | import nose.tools as nt
524 |
525 |
526 | class TestCoordinateConversion(unittest.TestCase):
527 |
528 | # Pick some coordinate lists to try out
529 | def setUp(self):
530 | def carttuple(x):
531 | return (x*random(), x*random(), x*random())
532 | self.carts = map(carttuple, sp.linspace(0, 2, 20))
533 | self.sphs = map(cart2sph, self.carts)
534 |
535 | # Check that applying both operations gives back the same thing
536 | def check_cart_sph_composition(self, cart, sph):
537 | assert_list_almost_equal(cart, sph2cart(sph))
538 |
539 | def test_composition_is_identity(self):
540 | for (cart, sph) in zip(self.carts, self.sphs):
541 | self.check_cart_sph_composition(cart, sph)
542 |
543 | # Check that the azimuthal angle is in the correct range
544 | def test_azi_range(self):
545 | for sph in self.sphs:
546 | assert_azi_in_range(sph)
547 |
548 | def test_azimuthal_edge_cases(self):
549 | assert_almost_equal(cart2sph((-1, -1, 0)).azi, 5*pi/4)
550 |
551 | # Check that the polar angle is in the correct range
552 | def test_polar_range(self):
553 | for sph in self.sphs:
554 | assert_polar_in_range(sph)
555 |
556 |
557 | def example_f(x, y):
558 | return cos(x) + sin(y)
559 |
560 |
561 | def test_parallel_sweep():
562 | """Check that a parallel run gives the same results as a non-parallel
563 | run for a simple function.
564 | """
565 | xs = sp.linspace(-pi, +pi, 30)
566 | ys = sp.linspace(-pi, +pi, 30)
567 |
568 | parallel_result = list(parallel_parameter_sweep(example_f, [xs, ys]))
569 | serial_result = list(parallel_parameter_sweep(example_f, [xs, ys], True))
570 | exact_result = list(it.starmap(example_f, it.product(xs, ys)))
571 |
572 | # Use sets for the comparison because the parallel computation destroys
573 | # any ordering we had before (and sets order their elements).
574 | assert_list_almost_equal(set(parallel_result), set(exact_result))
575 | assert_list_almost_equal(set(serial_result), set(exact_result))
576 |
577 |
578 | def test_skew_size_check():
579 | xs = [sp.linspace(0.0, 1.0, 4), 1.0, sp.identity(3)]
580 | for x in xs:
581 | nt.assert_raises(TypeError, skew, [x])
582 |
583 |
584 | def test_skew():
585 | xs = [sp.linspace(0.0, 1.0, 3), sp.zeros((3, 1)), [1, 2, 3], ]
586 | a = sp.rand(3)
587 |
588 | for x in xs:
589 | # Anything crossed with itself is zero:
590 | skew_mat = skew(x)
591 | assert_list_almost_zero(sp.dot(skew_mat, sp.array(x)))
592 |
593 | # a x b = - b x a
594 | assert_list_almost_zero(sp.dot(skew_mat, a) + sp.dot(a, skew_mat))
595 |
596 |
597 | def test_dts2ts():
598 | """Check that ts2dts and dts2ts are the inverse of each other (except for
599 | the requirement for a "base" value in dts2ts).
600 | """
601 | t = sympy.symbols('t')
602 | dts = sympy.symbols('Delta9:0', Real=True)
603 |
604 | results = ts2dts(dts2ts(t, dts))
605 |
606 | for a, b in zip(results, dts):
607 | assert_sym_eq(a, b)
608 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/core/ode.py:
--------------------------------------------------------------------------------
1 | from __future__ import division
2 | from __future__ import absolute_import
3 |
4 | import scipy as sp
5 | import scipy.integrate
6 | import scipy.linalg
7 | import scipy.optimize
8 | import functools as ft
9 | import itertools as it
10 | import copy
11 | import sys
12 | import random
13 | import sympy
14 |
15 | from math import sin, cos, tan, log, atan2, acos, pi, sqrt, exp
16 | from scipy.interpolate import krogh_interpolate
17 | from scipy.linalg import norm
18 | from functools import partial as par
19 |
20 |
21 | import simpleode.core.utils as utils
22 |
23 |
24 | # PARAMETERS
25 | MAX_ALLOWED_DT_SCALING_FACTOR = 3.0
26 | MIN_ALLOWED_DT_SCALING_FACTOR = 0.75
27 | TIMESTEP_FAILURE_DT_SCALING_FACTOR = 0.5
28 |
29 | MIN_ALLOWED_TIMESTEP = 1e-8
30 | MAX_ALLOWED_TIMESTEP = 1e8
31 |
32 |
33 | # Data storage notes
34 | # ============================================================
35 | # Y values and time values are stored in lists throughout (for easy
36 | # appending).
37 | # The final value in each of these lists (accessed with [-1]) is the most
38 | # recent.
39 | # Almost always the most recent value in the list is the current
40 | # guess/result for y_np1/t_np1 (i.e. y_{n+1}, t_{n+1}, i.e. the value being
41 | # calculated), the previous is y_n, etc.
42 | # Denote values of y/t at timestep using eg. y_np1 for y at step n+1. Use
43 | # 'h' for 0.5, 'm' for minus, 'p' for plus (since we can't include .,-,+ in
44 | # variable names).
45 | #
46 | #
47 | # Random notes:
48 | # ============================================================
49 | # Try to always use fractions rather than floating point values because
50 | # this allows us to use the same functions in sympy for algebraic
51 | # computations without loss of accuracy.
52 |
53 |
54 | class FailedTimestepError(Exception):
55 |
56 | def __init__(self, new_dt):
57 | self.new_dt = new_dt
58 |
59 | def __str__(self):
60 | return "Exception: timestep failed, next timestep should be "\
61 | + repr(self.new_dt)
62 |
63 |
64 | class ConvergenceFailure(Exception):
65 | pass
66 |
67 |
68 | def _timestep_scheme_factory(method):
69 | """Construct the functions for the named method. Input is either a
70 | string with the name of the method or a dict with the name and a list
71 | of parameters.
72 |
73 | Returns a triple of functions for:
74 | * a time residual
75 | * a timestep adaptor
76 | * intialisation actions
77 | """
78 |
79 | _method_dict = {}
80 |
81 | # If it's a dict then get the label attribute, otherwise assume it's a
82 | # string...
83 | if isinstance(method, dict):
84 | _method_dict = method
85 | else:
86 | _method_dict = {'label': method}
87 |
88 | label = _method_dict.get('label').lower()
89 |
90 | if label == 'bdf2':
91 | return bdf2_residual, None, par(higher_order_start, 2)
92 |
93 | elif label == 'bdf3':
94 | return bdf3_residual, None, par(higher_order_start, 3)
95 |
96 | elif label == 'bdf2 mp':
97 | adaptor = par(general_time_adaptor,
98 | lte_calculator=bdf2_mp_lte_estimate,
99 | method_order=2)
100 | return (bdf2_residual, adaptor, par(higher_order_start, 3))
101 |
102 | elif label == 'bdf2 ebdf3':
103 | dydt_func = _method_dict.get('dydt_func', None)
104 | lte_est = par(ebdf3_lte_estimate, dydt_func=dydt_func)
105 | adaptor = par(general_time_adaptor,
106 | lte_calculator=lte_est,
107 | method_order=2)
108 | return (bdf2_residual, adaptor, par(higher_order_start, 4))
109 |
110 | elif label == 'bdf1':
111 | return bdf1_residual, None, None
112 |
113 | elif label == 'imr':
114 | return imr_residual, None, None
115 |
116 | elif label == 'imr ebdf3':
117 | dydt_func = _method_dict.get('dydt_func', None)
118 | lte_est = par(ebdf3_lte_estimate, dydt_func=dydt_func)
119 | adaptor = par(general_time_adaptor,
120 | lte_calculator=lte_est,
121 | method_order=2)
122 | return imr_residual, adaptor, par(higher_order_start, 5)
123 |
124 | elif label == 'imr w18':
125 | import simpleode.algebra.two_predictor as tp
126 | p1_points = _method_dict['p1_points']
127 | p1_pred = _method_dict['p1_pred']
128 |
129 | p2_points = _method_dict['p2_points']
130 | p2_pred = _method_dict['p2_pred']
131 |
132 | symbolic = _method_dict['symbolic']
133 |
134 | lte_est = tp.generate_predictor_pair_lte_est(
135 | *tp.generate_predictor_pair_scheme(p1_points, p1_pred,
136 | p2_points, p2_pred,
137 | symbolic=symbolic))
138 |
139 | adaptor = par(general_time_adaptor,
140 | lte_calculator=lte_est,
141 | method_order=2)
142 |
143 | # ??ds don't actually need this many history values to start but it
144 | # makes things easier so use this many for now.
145 | return imr_residual, adaptor, par(higher_order_start, 12)
146 |
147 | elif label == 'trapezoid' or label == 'tr':
148 | # TR is actually self starting but due to technicalities with
149 | # getting derivatives of y from implicit formulas we need an extra
150 | # starting point.
151 | return TrapezoidRuleResidual(), None, par(higher_order_start, 2)
152 |
153 | elif label == 'tr ab':
154 |
155 | dydt_func = _method_dict.get('dydt_func')
156 |
157 | adaptor = par(general_time_adaptor,
158 | lte_calculator=tr_ab_lte_estimate,
159 | dydt_func=dydt_func,
160 | method_order=2)
161 |
162 | return TrapezoidRuleResidual(), adaptor, par(higher_order_start, 2)
163 |
164 | else:
165 | message = "Method '"+label+"' not recognised."
166 | raise ValueError(message)
167 |
168 |
169 | def higher_order_start(n_start, func, ts, ys, dt=1e-6):
170 | """ Run a few steps of imr with a very small timestep.
171 | Useful for generating extra initial data for multi-step methods.
172 | """
173 | while len(ys) < n_start:
174 | ts, ys = _odeint(func, ts, ys, dt, ts[-1] + dt,
175 | imr_residual)
176 | return ts, ys
177 |
178 |
179 | def odeint(func, y0, tmax, dt, method='bdf2', target_error=None, **kwargs):
180 | """
181 | Integrate the residual "func" with initial value "y0" to time
182 | "tmax". If non-adaptive (target_error=None) then all steps have size
183 | "dt", otherwise "dt" is used for the first step and later steps are
184 | automatically decided using the adaptive scheme.
185 |
186 | newton_tol : specify Newton tolerance (used for minimisation of residual).
187 |
188 | actions_after_timestep : function to modify t_np1 and y_np1 after
189 | calculation (takes ts, ys as input args, returns modified t_np1, y_np1).
190 |
191 | Actually just a user friendly wrapper for _odeint. Given a method name
192 | (or dict of time integration method parameters) construct the required
193 | functions using _timestep_scheme_factory(..), set up data storage and
194 | integrate the ODE using _odeint.
195 |
196 | Any other arguments are just passed down to _odeint, which passes extra
197 | args down to the newton solver.
198 | """
199 |
200 | # Select the method and adaptor
201 | time_residual, time_adaptor, initialisation_actions = \
202 | _timestep_scheme_factory(method)
203 |
204 | # Check adaptivity arguments for consistency.
205 | # if target_error is None and time_adaptor is not None:
206 | # raise ValueError("Adaptive time stepping requires a target_error")
207 | # if target_error is not None and time_adaptor is None:
208 | # raise ValueError("Adaptive time stepping requires an adaptive method")
209 |
210 | ts = [0.0] # List of times (floats)
211 | ys = [sp.array(y0, ndmin=1)] # List of y vectors (ndarrays)
212 |
213 | # Now call the actual function to do the work
214 | return _odeint(func, ts, ys, dt, tmax, time_residual,
215 | target_error, time_adaptor, initialisation_actions,
216 | **kwargs)
217 |
218 |
219 | def _odeint(func, tsin, ysin, dt, tmax, time_residual,
220 | target_error=None, time_adaptor=None,
221 | initialisation_actions=None, actions_after_timestep=None,
222 | newton_failure_reduce_step=False, jacobian_func=None,
223 | vary_step=False,
224 | **kwargs):
225 | """Underlying function for odeint.
226 | """
227 |
228 | # Make sure we only operator on a copy of (tsin, ysin) not the lists
229 | # themselves! (possibility for subtle bugs otherwise)
230 | ts = copy.copy(tsin)
231 | ys = copy.copy(ysin)
232 |
233 | if initialisation_actions is not None:
234 | ts, ys = initialisation_actions(func, ts, ys)
235 |
236 | if vary_step:
237 | assert time_adaptor is None
238 | step_randomiser = create_random_time_adaptor(dt, 0.9, 1.1)
239 |
240 | # Main timestepping loop
241 | # ============================================================
242 | while ts[-1] < tmax:
243 |
244 | t_np1 = ts[-1] + dt
245 |
246 | # Fill in the residual for calculating dydt and the previous time
247 | # and y values ready for the Newton solver. Don't use a lambda
248 | # function because it confuses the profiler.
249 | def residual(y_np1):
250 | return time_residual(func, ts+[t_np1], ys+[y_np1])
251 |
252 | if jacobian_func is not None:
253 | J_f_of_y = lambda y: jacobian_func(t_np1, y)
254 | else:
255 | J_f_of_y = None
256 |
257 | # Try to solve the system, using the previous y as an initial
258 | # guess. If it fails reduce dt and try again.
259 | try:
260 | y_np1 = newton(residual, ys[-1], jacobian_func=J_f_of_y, **kwargs)
261 |
262 | except sp.optimize.nonlin.NoConvergence:
263 |
264 | # If we are doing adaptive stepping (or overide allowing the
265 | # step to be reduced) then reduce the step and try again.
266 | if (time_adaptor is not None) or newton_failure_reduce_step:
267 | dt = scale_timestep(dt, None, None, None,
268 | scaling_function=failed_timestep_scaling)
269 | sys.stderr.write("Failed to converge, reducing time step.\n")
270 | continue
271 |
272 | # Otherwise don't do anything (re-raise the exception).
273 | else:
274 | raise
275 |
276 | # Execute any post-step actions requested (e.g. renormalisation,
277 | # simplified mid-point method update).
278 | if actions_after_timestep is not None:
279 | new_t_np1, new_y_np1 = actions_after_timestep(
280 | ts+[t_np1], ys+[y_np1])
281 | # Note: we store the results in new variables so that we can
282 | # easily discard this step if it fails.
283 | else:
284 | new_t_np1, new_y_np1 = t_np1, y_np1
285 |
286 | # Calculate the next value of dt if needed
287 | if time_adaptor is not None:
288 | try:
289 | dt = time_adaptor(ts+[new_t_np1], ys+[new_y_np1], target_error)
290 |
291 | # If the scaling factor is too small then don't store this
292 | # timestep, instead repeat it with the new step size.
293 | except FailedTimestepError as exception_data:
294 | sys.stderr.write('Rejected time step\n')
295 | dt = exception_data.new_dt
296 | continue
297 |
298 | elif vary_step:
299 | dt = step_randomiser()
300 |
301 | # Update results storage (don't do this earlier in case the time
302 | # step fails).
303 | ys.append(new_y_np1)
304 | ts.append(new_t_np1)
305 |
306 | return ts, ys
307 |
308 |
309 | def higher_order_explicit_start(n_start, func, ts, ys):
310 | starting_dt = 1e-6
311 | while len(ys) < n_start:
312 | ts, ys = _odeint_explicit(func, ts, ys, starting_dt,
313 | ts[-1] + starting_dt,
314 | emr_step)
315 |
316 | return ts, ys
317 |
318 |
319 | def odeint_explicit(func, y0, dt, tmax, method='ab2', time_adaptor=None,
320 | target_error=None, **kwargs):
321 | """Fairly naive implementation of constant step explicit time stepping
322 | for linear odes.
323 | """
324 | # Set up starting values
325 | ts = [0.0]
326 | ys = [sp.array([y0], ndmin=1)]
327 |
328 | if method == 'ab2':
329 | def wrapped_ab2(ts, ys, func):
330 | return ab2_step(ts[-1] - ts[-2], ys[-2], func(ts[-2], ys[-2]),
331 | ts[-2] - ts[-3], func(ts[-3], ys[-3]))
332 |
333 | stepper = wrapped_ab2
334 | n_start = 2
335 |
336 | elif method == "ebdf2":
337 | def wrapped_ebdf2(ts, ys, func):
338 | return ebdf2_step(ts[-1] - ts[-2], ts[-2], func(ts[-2], ys[-2]),
339 | ts[-2] - ts[-3], ys[-3])
340 | stepper = wrapped_ebdf2
341 | n_start = 2
342 |
343 | elif method == "ebdf3":
344 | def wrapped_ebdf3(ts, ys, func):
345 | return ebdf3_step(ts[-1] - ts[-2], ys[-2], func(ts[-2], ys[-2]),
346 | ts[-2] - ts[-3], ys[-3],
347 | ts[-3] - ts[-4], ys[-4])
348 | stepper = wrapped_ebdf3
349 | n_start = 3
350 |
351 | else:
352 | raise NotImplementedError("method "+method+" not implement (yet?)")
353 |
354 | # Generate enough values to start the main method (using emr)
355 | ts, ys = higher_order_explicit_start(n_start, func, ts, ys)
356 |
357 | # Call the real stepping function
358 | return _odeint_explicit(func, ts, ys, dt, tmax, stepper, time_adaptor)
359 |
360 |
361 | def _odeint_explicit(func, ts, ys, dt, tmax,
362 | stepper, target_error=None, time_adaptor=None):
363 |
364 | while ts[-1] < tmax:
365 |
366 | # Step (note: to be similar to implicit code pass dummy value of
367 | # ynp1 into stepper)
368 | t_np1 = ts[-1] + dt
369 | y_np1 = stepper(ts+[t_np1], ys+[None], func)
370 |
371 | # Calculate the next value of dt if needed
372 | if time_adaptor is not None:
373 | try:
374 | dt = time_adaptor(ts+[t_np1], ys+[y_np1], target_error)
375 |
376 | # If the scaling factor is too small then don't store this
377 | # timestep, instead repeat it with the new step size.
378 | except FailedTimestepError as exception_data:
379 | sys.stderr.write('Rejected time step\n')
380 | dt = exception_data.new_dt
381 | continue
382 |
383 | # Store values
384 | ys.append(y_np1)
385 | ts.append(t_np1)
386 |
387 | return ts, ys
388 |
389 |
390 | # Newton solver and helpers
391 | # ============================================================
392 | def newton(residual, x0, jacobian_func=None, newton_tol=1e-8,
393 | solve_function=None,
394 | jacobian_fd_eps=1e-10, max_iter=20):
395 | """Find the minimum of the residual function using Newton's method.
396 |
397 | Optionally specify a Jacobian calculation function, a tolerance and/or
398 | a function to solve the linear system J.dx = r.
399 |
400 | If no Jacobian_Func is given the Jacobian is finite differenced.
401 | If no solve function is given then sp.linalg.solve is used.
402 |
403 | Norm for measuring residual is max(abs(..)).
404 | """
405 | if jacobian_func is None:
406 | jacobian_func = par(
407 | finite_diff_jacobian,
408 | residual,
409 | eps=jacobian_fd_eps)
410 |
411 | if solve_function is None:
412 | solve_function = sp.linalg.solve
413 |
414 | # Wrap the solve function to deal with non-matrix cases (i.e. when we
415 | # only have one degree of freedom and the "Jacobian" is just a number).
416 | def wrapped_solve(A, b):
417 | if len(b) == 1:
418 | return b/A[0][0]
419 | else:
420 | try:
421 | return solve_function(A, b)
422 | except scipy.linalg.LinAlgError:
423 | print "\n", A, b, "\n"
424 | raise
425 |
426 | # Call the real Newton solve function
427 | return _newton(residual, x0, jacobian_func, newton_tol,
428 | wrapped_solve, max_iter)
429 |
430 |
431 | def _newton(residual, x0, jacobian_func, newton_tol, solve_function, max_iter):
432 | """Core function of newton(...)."""
433 |
434 | if max_iter <= 0:
435 | raise sp.optimize.nonlin.NoConvergence
436 |
437 | r = residual(x0)
438 |
439 | # If max entry is below newton_tol then return
440 | if sp.amax(abs(r)) < newton_tol:
441 | return x0
442 |
443 | # Otherwise reduce residual using Newtons method + recurse
444 | else:
445 | J = jacobian_func(x0)
446 | dx = solve_function(J, r)
447 | return _newton(residual, x0 - dx, jacobian_func, newton_tol,
448 | solve_function, max_iter - 1)
449 |
450 |
451 | def finite_diff_jacobian(residual, x, eps):
452 | """Calculate the matrix of derivatives of the residual w.r.t. input
453 | values by finite differencing.
454 | """
455 | n = len(x)
456 | J = sp.empty((n, n))
457 |
458 | # For each entry in x
459 | for i in range(0, n):
460 | xtemp = x.copy() # Force a copy so that we don't modify x
461 | xtemp[i] += eps
462 | J[:, i] = (residual(xtemp) - residual(x))/eps
463 |
464 | return J
465 |
466 |
467 | # Interpolation helpers
468 | # ============================================================
469 | def my_interpolate(ts, ys, n_interp, use_y_np1_in_interp=False):
470 | # Find the start and end of the slice of ts, ys that we want to use for
471 | # interpolation.
472 | start = -n_interp if use_y_np1_in_interp else -n_interp - 1
473 | end = None if use_y_np1_in_interp else -1
474 |
475 | # Nasty things could go wrong if you try to start adapting with not
476 | # enough points because [-a:-b] notation lets us go past the ends of
477 | # the list without throwing an error! Check it!
478 | assert len(ts[start:end]) == n_interp
479 |
480 | # Actually interpolate the values
481 | t_nph = (ts[-1] + ts[-2])/2
482 | t_nmh = (ts[-2] + ts[-3])/2
483 | interps = krogh_interpolate(
484 | ts[start:end], ys[start:end], [t_nmh, ts[-2], t_nph], der=[0, 1, 2])
485 |
486 | # Unpack (can't get "proper" unpacking to work)
487 | dy_nmh = interps[1][0]
488 | dy_n = interps[1][1]
489 | y_nph = interps[0][2]
490 | dy_nph = interps[1][2]
491 | ddy_nph = interps[2][2]
492 |
493 | return dy_nmh, y_nph, dy_nph, ddy_nph, dy_n
494 |
495 |
496 | def imr_approximation_fake_interpolation(ts, ys):
497 | # Just use imr approximation for "interpolation"!
498 |
499 | dt_n = (ts[-1] + ts[-2])/2
500 | dt_nm1 = (ts[-2] + ts[-3])/2
501 |
502 | # Use imr average approximations
503 | y_nph = (ys[-1] + ys[-2])/2
504 | dy_nph = (ys[-1] - ys[-2])/dt_n
505 | dy_nmh = (ys[-2] - ys[-3])/dt_nm1
506 |
507 | # Finite diff it
508 | ddy_nph = (dy_nph - dy_nmh) / (dt_n/2 + dt_nm1/2)
509 |
510 | return dy_nmh, y_nph, dy_nph, ddy_nph, None
511 |
512 |
513 | # Timestepper residual calculation functions
514 | # ============================================================
515 |
516 | def ab2_step(dt_n, y_n, dy_n, dt_nm1, dy_nm1):
517 | """Take a single step of the Adams-Bashforth 2 method.
518 | """
519 | dtr = dt_n / dt_nm1
520 | y_np1 = y_n + (dt_n/2)*((2 + dtr)*dy_n - dtr*dy_nm1)
521 | return y_np1
522 |
523 |
524 | def ebdf2_step(dt_n, y_n, dy_n, dt_nm1, y_nm1):
525 | """Take a single step of the explicit midpoint rule.
526 | From G&S pg. 715 and Prinja's thesis pg.45.
527 | """
528 | dtr = dt_n / dt_nm1
529 | y_np1 = (1 - dtr**2)*y_n + (1 + dtr)*dt_n*dy_n + (dtr**2)*(y_nm1)
530 | return y_np1
531 |
532 |
533 | def emr_step(ts, ys, func):
534 | dtn = ts[-1] - ts[-2]
535 |
536 | tn = ts[-2]
537 | yn = ys[-2]
538 |
539 | tnph = ts[-1] + dtn/2
540 | ynph = yn + (dtn/2)*func(tn, yn)
541 |
542 | ynp1 = yn + dtn * func(tnph, ynph)
543 |
544 | return ynp1
545 |
546 |
547 | def ibdf2_step(dtn, yn, dynp1, dtnm1, ynm1):
548 | """Take an implicit (normal) bdf2 step, must provide the derivative or
549 | some approximation to it. For solves use residuals instead.
550 |
551 | Generated by sym-bdf3.py
552 | """
553 |
554 | return (
555 | (-dtn**2*ynm1 + dtn*dtnm1*dynp1*(dtn + dtnm1) + yn *
556 | (dtn**2 + 2*dtn*dtnm1 + dtnm1**2))/(dtnm1*(2*dtn + dtnm1))
557 | )
558 |
559 |
560 | def ibdf3_step(dynp1, dtn, yn, dtnm1, ynm1, dtnm2, ynm2):
561 | return (
562 | (
563 | dtn**2*dtnm1*ynm2*(
564 | dtn**2 + 2*dtn*dtnm1 + dtnm1**2) - dtn**2*ynm1*(
565 | dtn**2*dtnm1 + dtn**2*dtnm2 + 2*dtn*dtnm1**2 + 4*dtn*dtnm1*dtnm2 + 2*dtn*dtnm2**2 + dtnm1**3 + 3*dtnm1**2*dtnm2 + 3*dtnm1*dtnm2**2 + dtnm2**3) + dtn*dtnm1*dtnm2*dynp1*(
566 | dtn**2*dtnm1 + dtn**2*dtnm2 + 2*dtn*dtnm1**2 + 3*dtn*dtnm1*dtnm2 + dtn*dtnm2**2 + dtnm1**3 + 2*dtnm1**2*dtnm2 + dtnm1*dtnm2**2) + dtnm2*yn*(
567 | dtn**4 + 4*dtn**3*dtnm1 + 2*dtn**3*dtnm2 + 6*dtn**2*dtnm1**2 + 6*dtn**2*dtnm1*dtnm2 + dtn**2*dtnm2**2 + 4*dtn*dtnm1**3 + 6*dtn*dtnm1**2*dtnm2 + 2*dtn*dtnm1*dtnm2**2 + dtnm1**4 + 2*dtnm1**3*dtnm2 + dtnm1**2*dtnm2**2))/(
568 | dtnm1*dtnm2*(
569 | 3*dtn**2*dtnm1 + 3*dtn**2*dtnm2 + 4*dtn*dtnm1**2 + 6*dtn*dtnm1*dtnm2 + 2*dtn*dtnm2**2 + dtnm1**3 + 2*dtnm1**2*dtnm2 + dtnm1*dtnm2**2))
570 | )
571 |
572 |
573 | def ebdf3_step_wrapper(ts, ys, dyn):
574 | """Get required values from ts, ys vectors and call ebdf3_step.
575 | """
576 |
577 | dtn = ts[-1] - ts[-2]
578 | dtnm1 = ts[-2] - ts[-3]
579 | dtnm2 = ts[-3] - ts[-4]
580 |
581 | yn = ys[-2]
582 | ynm1 = ys[-3]
583 | ynm2 = ys[-4]
584 |
585 | return ebdf3_step(dtn, yn, dyn, dtnm1, ynm1, dtnm2, ynm2)
586 |
587 |
588 | def ebdf3_step(dtn, yn, dyn, dtnm1, ynm1, dtnm2, ynm2):
589 | """Calculate one step of "explicitBDF3", i.e. the third order analogue
590 | of explicit midpoint rule.
591 |
592 | Code is generated using sym-bdf3.py.
593 | """
594 | return (
595 | -(
596 | dyn*(
597 | -dtn**3*dtnm1**2*dtnm2 - dtn**3*dtnm1*dtnm2**2 - 2*dtn**2*dtnm1**3*dtnm2 - 3*dtn**2*dtnm1**2*dtnm2**2 - dtn**2*dtnm1*dtnm2**3 - dtn*dtnm1**4*dtnm2 - 2*dtn*dtnm1**3*dtnm2**2 - dtn*dtnm1**2*dtnm2**3) + yn*(
598 | 2*dtn**3*dtnm1*dtnm2 + dtn**3*dtnm2**2 + 3*dtn**2*dtnm1**2*dtnm2 + 3*dtn**2*dtnm1*dtnm2**2 + dtn**2*dtnm2**3 - dtnm1**4*dtnm2 - 2*dtnm1**3*dtnm2**2 - dtnm1**2*dtnm2**3) + ynm1*(
599 | -dtn**3*dtnm1**2 - 2*dtn**3*dtnm1*dtnm2 - dtn**3*dtnm2**2 - dtn**2*dtnm1**3 - 3*dtn**2*dtnm1**2*dtnm2 - 3*dtn**2*dtnm1*dtnm2**2 - dtn**2*dtnm2**3) + ynm2*(
600 | dtn**3*dtnm1**2 + dtn**2*dtnm1**3))/(
601 | dtnm1**4*dtnm2 + 2*dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3)
602 | )
603 |
604 |
605 | def ebdf3_dynm1_step(ts, ys, dynm1):
606 | dtn = ts[-1] - ts[-2]
607 | dtnm1 = ts[-2] - ts[-3]
608 | dtnm2 = ts[-3] - ts[-4]
609 |
610 | yn = ys[-2]
611 | ynm1 = ys[-3]
612 | ynm2 = ys[-4]
613 |
614 | return (
615 | dynm1*(
616 | -dtn**3*dtnm1**2*dtnm2/(
617 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3) - dtn**3*dtnm1*dtnm2**2/(
618 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3) - 2*dtn**2*dtnm1**3*dtnm2/(
619 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3) - 3*dtn**2*dtnm1**2*dtnm2**2/(
620 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3) - dtn**2*dtnm1*dtnm2**3/(
621 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3) - dtn*dtnm1**4*dtnm2/(
622 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3) - 2*dtn*dtnm1**3*dtnm2**2/(
623 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3) - dtn*dtnm1**2*dtnm2**3/(
624 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3)) + yn*(
625 | dtn**3*dtnm2**2/(
626 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3) + 3*dtn**2*dtnm1*dtnm2**2/(
627 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3) + dtn**2*dtnm2**3/(
628 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3) + 3*dtn*dtnm1**2*dtnm2**2/(
629 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3) + 2*dtn*dtnm1*dtnm2**3/(
630 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3) + dtnm1**3*dtnm2**2/(
631 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3) + dtnm1**2*dtnm2**3/(
632 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3)) + ynm1*(
633 | dtn**3*dtnm1**2/(
634 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3) - dtn**3*dtnm2**2/(
635 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3) + 2*dtn**2*dtnm1**3/(
636 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3) - 3*dtn**2*dtnm1*dtnm2**2/(
637 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3) - dtn**2*dtnm2**3/(
638 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3) + dtn*dtnm1**4/(
639 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3) - 3*dtn*dtnm1**2*dtnm2**2/(
640 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3) - 2*dtn*dtnm1*dtnm2**3/(
641 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3)) + ynm2*(
642 | -dtn**3*dtnm1**2/(
643 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3) - 2*dtn**2*dtnm1**3/(
644 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3) - dtn*dtnm1**4/(
645 | dtnm1**3*dtnm2**2 + dtnm1**2*dtnm2**3))
646 | )
647 |
648 |
649 | def imr_residual(base_residual, ts, ys):
650 | y_nph = (ys[-1] + ys[-2])/2
651 | t_nph = (ts[-1] + ts[-2])/2
652 | dydt_nph = imr_dydt(ts, ys)
653 | return base_residual(t_nph, y_nph, dydt_nph)
654 |
655 |
656 | def imr_dydt(ts, ys):
657 | """Get dy/dt at the midpoint as used by imr.
658 | """
659 | dypnh_dt = (ys[-1] - ys[-2])/(ts[-1] - ts[-2])
660 | return dypnh_dt
661 |
662 |
663 | def interpolate_dyn(ts, ys):
664 | #??ds probably not accurate enough
665 |
666 | order = 3
667 | ts = ts[-1*order-1:]
668 | ys = ys[-1*order-1:]
669 |
670 | ynp1_list = ys[1:]
671 | yn_list = ys[:-1]
672 | dts = utils.ts2dts(ts)
673 |
674 | # double check steps match
675 | imr_ts = map(lambda tn, tnp1: (tn + tnp1)/2, ts[1:], ts[:-1])
676 | imr_dys = map(lambda dt, ynp1, yn: (ynp1 - yn)/dt,
677 | dts, ynp1_list, yn_list)
678 |
679 | dyn = (sp.interpolate.barycentric_interpolate
680 | (imr_ts, imr_dys, ts[-2]))
681 |
682 | return dyn
683 |
684 |
685 | def bdf1_residual(base_residual, ts, ys):
686 | dt_n = ts[-1] - ts[-2]
687 | y_n = ys[-2]
688 | y_np1 = ys[-1]
689 |
690 | dydt = (y_np1 - y_n) / dt_n
691 | return base_residual(ts[-1], y_np1, dydt)
692 |
693 |
694 | def bdf_residual(base_residual, ts, ys, dydt_func):
695 | """ Calculate residual at latest time and y-value with a bdf
696 | approximation for the y derivative.
697 | """
698 | return base_residual(ts[-1], ys[-1], dydt_func(ts, ys))
699 |
700 |
701 | def bdf2_dydt(ts, ys):
702 | """Get dy/dt at time ts[-1] (allowing for varying dt).
703 | Gresho & Sani, pg. 715"""
704 | dt_n = ts[-1] - ts[-2]
705 | dt_nm1 = ts[-2] - ts[-3]
706 |
707 | y_np1 = ys[-1]
708 | y_n = ys[-2]
709 | y_nm1 = ys[-3]
710 |
711 | # Copied from oomph-lib (algebraic rearrangement of G&S forumla).
712 | dydt = (((1/dt_n) + (1/(dt_n + dt_nm1))) * y_np1
713 | - ((dt_n + dt_nm1)/(dt_n * dt_nm1)) * y_n
714 | + (dt_n / ((dt_n + dt_nm1) * dt_nm1)) * y_nm1)
715 |
716 | return dydt
717 |
718 |
719 | def bdf3_dydt(ts, ys):
720 | """Get dydt at time ts[-1] to O(dt^3).
721 |
722 | Code is generated using sym-bdf3.py.
723 | """
724 |
725 | dtn = ts[-1] - ts[-2]
726 | dtnm1 = ts[-2] - ts[-3]
727 | dtnm2 = ts[-3] - ts[-4]
728 |
729 | ynp1 = ys[-1]
730 | yn = ys[-2]
731 | ynm1 = ys[-3]
732 | ynm2 = ys[-4]
733 |
734 | return (
735 | dtn*(dtn + dtnm1)*(-(-(ynm1 - ynm2)/dtnm2 + (yn - ynm1)/dtnm1)/(dtnm1 + dtnm2) + (-(yn - ynm1)/dtnm1 + (ynp1 - yn)/dtn)/(dtn + dtnm1)) /
736 | (dtn + dtnm1 + dtnm2) + dtn*(-(yn - ynm1)/dtnm1 + (ynp1 - yn)/dtn) /
737 | (dtn + dtnm1) + (ynp1 - yn)/dtn
738 | )
739 |
740 |
741 | def bdf4_dydt(ts, ys):
742 | """Get dydt at time ts[-1] using bdf4 approximation.
743 |
744 | Code is generated using sym-bdf3.py.
745 | """
746 |
747 | dtn = ts[-1] - ts[-2]
748 | dtnm1 = ts[-2] - ts[-3]
749 | dtnm2 = ts[-3] - ts[-4]
750 | dtnm3 = ts[-4] - ts[-5]
751 |
752 | ynp1 = ys[-1]
753 | yn = ys[-2]
754 | ynm1 = ys[-3]
755 | ynm2 = ys[-4]
756 | ynm3 = ys[-5]
757 |
758 | return (
759 | dtn*(dtn + dtnm1)*(-(-(ynm1 - ynm2)/dtnm2 + (yn - ynm1)/dtnm1)/(dtnm1 + dtnm2) + (-(yn - ynm1)/dtnm1 + (ynp1 - yn)/dtn)/(dtn + dtnm1))/(dtn + dtnm1 + dtnm2) + dtn*(dtn + dtnm1)*((-(-(ynm1 - ynm2)/dtnm2 + (yn - ynm1)/dtnm1)/(dtnm1 + dtnm2) + (-(yn - ynm1)/dtnm1 + (ynp1 - yn)/dtn)/(dtn + dtnm1)) /
760 | (dtn + dtnm1 + dtnm2) - (-(-(ynm2 - ynm3)/dtnm3 + (ynm1 - ynm2)/dtnm2)/(dtnm2 + dtnm3) + (-(ynm1 - ynm2)/dtnm2 + (yn - ynm1)/dtnm1)/(dtnm1 + dtnm2))/(dtnm1 + dtnm2 + dtnm3))*(dtn + dtnm1 + dtnm2)/(dtn + dtnm1 + dtnm2 + dtnm3) + dtn*(-(yn - ynm1)/dtnm1 + (ynp1 - yn)/dtn)/(dtn + dtnm1) + (ynp1 - yn)/dtn
761 | )
762 |
763 |
764 | bdf2_residual = par(bdf_residual, dydt_func=bdf2_dydt)
765 | bdf3_residual = par(bdf_residual, dydt_func=bdf3_dydt)
766 | bdf4_residual = par(bdf_residual, dydt_func=bdf4_dydt)
767 |
768 |
769 | # Assumption: we never actually undo a timestep (otherwise dys will become
770 | # out of sync with ys).
771 | class TrapezoidRuleResidual(object):
772 |
773 | """A class to calculate trapezoid rule residuals.
774 |
775 | We need a class because we need to store the past data. Other residual
776 | calculations do not.
777 | """
778 |
779 | def __init__(self):
780 | self.dys = []
781 |
782 | def calculate_new_dy_if_needed(self, ts, ys):
783 | """If dy_n/dt has not been calculated on this step then calculate
784 | it from previous values of y and dydt by inverting the trapezoid
785 | rule.
786 | """
787 | if len(self.dys) < len(ys) - 1:
788 | dt_nm1 = ts[-2] - ts[-3]
789 | dy_n = (2.0 / dt_nm1) * (ys[-2] - ys[-3]) - self.dys[-1]
790 | self.dys.append(dy_n)
791 |
792 | def _get_initial_dy(self, base_residual, ts, ys):
793 | """Calculate a step with imr to get dydt at y_n.
794 | """
795 |
796 | # We want to ignore the most recent two steps (the one being solved
797 | # for "now" outside this function and the one we are computing the
798 | # derivative at). We also want to ensure nothing is modified in the
799 | # solutions list:
800 | temp_ts = copy.deepcopy(ts[:-2])
801 | temp_ys = copy.deepcopy(ys[:-2])
802 |
803 | # Timestep should be double the timestep used for the previous
804 | # step, so that the imr is at y_n.
805 | dt_n = 2*(ts[-2] - ts[-3])
806 |
807 | # Calculate time step
808 | temp_ts, temp_ys = _odeint(base_residual, temp_ts, temp_ys, dt_n,
809 | temp_ts[-1] + dt_n, imr_residual)
810 |
811 | # Check that we got the right times: the midpoint should be at
812 | # the step before the most recent time.
813 | utils.assert_almost_equal((temp_ts[-1] + temp_ts[-2])/2, ts[-2])
814 |
815 | # Now invert imr to get the derivative
816 | dy_nph = (temp_ys[-1] - temp_ys[-2])/dt_n
817 |
818 | # Fill in dummys (as many as we have y values) followed by the
819 | # derivative we just calculated.
820 | self.dys = [float('nan')] * (len(ys)-1)
821 | self.dys[-1] = dy_nph
822 |
823 | def __call__(self, base_residual, ts, ys):
824 | if len(self.dys) == 0:
825 | self._get_initial_dy(base_residual, ts, ys)
826 |
827 | dt_n = ts[-1] - ts[-2]
828 | t_np1 = ts[-1]
829 | y_n = ys[-2]
830 | y_np1 = ys[-1]
831 |
832 | self.calculate_new_dy_if_needed(ts, ys)
833 | dy_n = self.dys[-1]
834 |
835 | dy_np1 = (2.0/dt_n) * (y_np1 - y_n) - dy_n
836 | return base_residual(t_np1, y_np1, dy_np1)
837 |
838 | # Adaptive timestepping functions
839 | # ============================================================
840 |
841 |
842 | def default_dt_scaling(target_error, error_estimate, timestepper_order):
843 | """Standard way of rescaling the time step to attain the target error.
844 | Taken from Gresho and Sani (various places).
845 | """
846 | try:
847 | power = (1.0/(1.0 + timestepper_order))
848 | scaling_factor = (target_error/error_estimate)**power
849 |
850 | except ZeroDivisionError:
851 | scaling_factor = MAX_ALLOWED_DT_SCALING_FACTOR
852 |
853 | return scaling_factor
854 |
855 |
856 | def failed_timestep_scaling(*_):
857 | """Return scaling factor for a failed time step, ignores all input
858 | arguments.
859 | """
860 | return TIMESTEP_FAILURE_DT_SCALING_FACTOR
861 |
862 |
863 | def create_random_time_adaptor(base_dt,
864 | min_scaling=TIMESTEP_FAILURE_DT_SCALING_FACTOR,
865 | max_scaling=MAX_ALLOWED_DT_SCALING_FACTOR):
866 | """Create time adaptor which randomly changes the time step to some
867 | multiple of base_dt. Scaling factor is within the allowed range. For
868 | testing purposes.
869 | """
870 | def random_time_adaptor(*_):
871 | return base_dt * random.uniform(min_scaling, max_scaling)
872 | return random_time_adaptor
873 |
874 |
875 | def scale_timestep(dt, target_error, error_norm, order,
876 | scaling_function=default_dt_scaling):
877 | """Scale dt by a scaling factor. Mostly this function is needed to
878 | check that the scaling factor and new time step are within the
879 | allowable bounds.
880 | """
881 |
882 | # Calculate the scaling factor and the candidate for next step size.
883 | scaling_factor = scaling_function(target_error, error_norm, order)
884 | new_dt = scaling_factor * dt
885 |
886 | # If the error is too bad (i.e. scaling factor too small) reject the
887 | # step, unless we are already dealing with a rejected step;
888 | if scaling_factor < MIN_ALLOWED_DT_SCALING_FACTOR \
889 | and not scaling_function is failed_timestep_scaling:
890 | raise FailedTimestepError(new_dt)
891 |
892 | # or if the scaling factor is really large just use the max scaling.
893 | elif scaling_factor > MAX_ALLOWED_DT_SCALING_FACTOR:
894 | scaling_factor = MAX_ALLOWED_DT_SCALING_FACTOR
895 |
896 | # If the timestep would get too big then return the max time step;
897 | if new_dt > MAX_ALLOWED_TIMESTEP:
898 | return MAX_ALLOWED_TIMESTEP
899 |
900 | # or if the timestep would become too small then fail;
901 | elif new_dt < MIN_ALLOWED_TIMESTEP:
902 | error = "Tried to reduce dt to " + str(new_dt) +\
903 | " which is less than the minimum of " + str(MIN_ALLOWED_TIMESTEP)
904 | raise ConvergenceFailure(error)
905 |
906 | # otherwise scale the timestep normally.
907 | else:
908 | return new_dt
909 |
910 |
911 | def general_time_adaptor(ts, ys, target_error, method_order, lte_calculator,
912 | **kwargs):
913 | """General base function for time adaptivity function.
914 |
915 | Partially evaluate with a method order and an lte_calculator to create
916 | a complete time adaptor function.
917 |
918 | Other args are passed down to the lte calculator.
919 | """
920 |
921 | # Get the local truncation error estimator
922 | lte_est = lte_calculator(ts, ys, **kwargs)
923 |
924 | # Get the 2-norm
925 | error_norm = sp.linalg.norm(sp.array(lte_est, ndmin=1), 2)
926 |
927 | # Return the scaled timestep (with lots of checks).
928 | return scale_timestep(ts[-1] - ts[-2], target_error, error_norm,
929 | method_order)
930 |
931 |
932 | def bdf2_mp_prinja_lte_estimate(ts, ys):
933 | """Estimate LTE using combination of bdf2 and explicit midpoint. From
934 | Prinja's thesis.
935 | """
936 |
937 | # Get local values (makes maths more readable)
938 | dt_n = ts[-1] - ts[-2]
939 | dt_nm1 = ts[-2] - ts[-3]
940 | dtr = dt_n / dt_nm1
941 | dtrinv = 1.0 / dtr
942 |
943 | y_np1 = ys[-1]
944 | y_n = ys[-2]
945 | y_nm1 = ys[-3]
946 |
947 | # Invert bdf2 to get derivative
948 | dy_n = bdf2_dydt(ts[:-1], ys[:-1])
949 |
950 | # Calculate predictor value (variable dt explicit mid point rule)
951 | y_np1_EMR = ebdf2_step(dt_n, y_n, dy_n, dt_nm1, y_nm1)
952 |
953 | error_weight = (dt_nm1 + dt_n) / (3*dt_n + 2*dt_nm1)
954 |
955 | # Calculate truncation error -- oomph-lib
956 | error = (y_np1 - y_np1_EMR) * error_weight
957 |
958 | return error
959 |
960 |
961 | def bdf2_mp_gs_lte_estimate(ts, ys):
962 | """Estimate LTE using combination of bdf2 and explicit midpoint. From
963 | oomph-lib and G&S.
964 | """
965 |
966 | # Get local values (makes maths more readable)
967 | dt_n = ts[-1] - ts[-2]
968 | dt_nm1 = ts[-2] - ts[-3]
969 | dtr = dt_n / dt_nm1
970 | dtrinv = 1.0 / dtr
971 |
972 | y_np1 = ys[-1]
973 | y_n = ys[-2]
974 | y_nm1 = ys[-3]
975 |
976 | # Invert bdf2 to get predictor data (using the exact same function as
977 | # was used in the residual calculation).
978 | dy_n = bdf2_dydt(ts[:-1], ys[:-1])
979 |
980 | # Calculate predictor value (variable dt explicit mid point rule)
981 | y_np1_EMR = ebdf2_step(dt_n, y_n, dy_n, dt_nm1, y_nm1)
982 |
983 | error_weight = ((1.0 + dtrinv)**2) / \
984 | (1.0 + 3.0*dtrinv + 4.0 * dtrinv**2
985 | + 2.0 * dtrinv**3)
986 |
987 | # Calculate truncation error -- oomph-lib
988 | error = (y_np1 - y_np1_EMR) * error_weight
989 |
990 | return error
991 |
992 |
993 | # ??Ds use prinja's
994 | bdf2_mp_lte_estimate = bdf2_mp_prinja_lte_estimate
995 |
996 |
997 | def tr_ab_lte_estimate(ts, ys, dydt_func):
998 | dt_n = ts[-1] - ts[-2]
999 | dt_nm1 = ts[-2] - ts[-3]
1000 | dtrinv = dt_nm1 / dt_n
1001 |
1002 | y_np1 = ys[-1]
1003 | y_n = ys[-2]
1004 | y_nm1 = ys[-3]
1005 |
1006 | dy_n = dydt_func(ts[-2], y_n)
1007 | dy_nm1 = dydt_func(ts[-3], y_nm1)
1008 |
1009 | # Predict with AB2
1010 | y_np1_AB2 = ab2_step(dt_n, y_n, dy_n, dt_nm1, dy_nm1)
1011 |
1012 | # Estimate LTE
1013 | lte_est = (y_np1 - y_np1_AB2) / (3*(1 + dtrinv))
1014 | return lte_est
1015 |
1016 |
1017 | def ebdf3_lte_estimate(ts, ys, dydt_func=None):
1018 | """Estimate lte for any second order integration method by comparing
1019 | with the third order explicit bdf method.
1020 | """
1021 |
1022 | # Use BDF approximation to dyn if no function given
1023 | if dydt_func is None:
1024 | # dyn = bdf3_dydt(ts[:-1], ys[:-1])
1025 | dyn = interpolate_dyn(ts, ys)
1026 | else:
1027 | dyn = dydt_func(ts[-2], ys[-2])
1028 |
1029 | y_np1_EBDF3 = ebdf3_step_wrapper(ts, ys, dyn)
1030 |
1031 | return ys[-1] - y_np1_EBDF3
1032 |
1033 |
1034 | def get_ltes_from_data(maints, mainys, lte_est):
1035 |
1036 | ltes = []
1037 |
1038 | for ts, ys in zip(utils.partial_lists(maints, 6),
1039 | utils.partial_lists(mainys, 6)):
1040 |
1041 | this_lte = lte_est(ts, ys)
1042 |
1043 | ltes.append(this_lte)
1044 |
1045 | return ltes
1046 |
1047 |
1048 | # Testing
1049 | # ============================================================
1050 | import matplotlib.pyplot as plt
1051 | from simpleode.core.example_residuals import *
1052 |
1053 |
1054 | def check_problem(method, residual, exact, tol=1e-4, tmax=2.0):
1055 | """Helper function to run odeint with a specified method for a problem
1056 | and check that the solution matches.
1057 | """
1058 |
1059 | ts, ys = odeint(residual, [exact(0.0)], tmax, dt=1e-6,
1060 | method=method, target_error=tol)
1061 |
1062 | # Total error should be bounded by roughly n_steps * LTE
1063 | overall_tol = len(ys) * tol * 10
1064 | utils.assert_list_almost_equal(ys, map(exact, ts), overall_tol)
1065 |
1066 | return ts, ys
1067 |
1068 |
1069 | def test_bad_timestep_handling():
1070 | """ Check that rejecting timesteps works.
1071 | """
1072 | tmax = 0.4
1073 | tol = 1e-4
1074 |
1075 | def list_cummulative_sums(values, start):
1076 | temp = [start]
1077 | for v in values:
1078 | temp.append(temp[-1] + v)
1079 | return temp
1080 |
1081 | dts = [1e-6, 1e-6, 1e-6, (1. - 0.01)*tmax]
1082 | initial_ts = list_cummulative_sums(dts[:-1], 0.)
1083 | initial_ys = [sp.array(exp3_exact(t), ndmin=1) for t in initial_ts]
1084 |
1085 | adaptor = par(general_time_adaptor, lte_calculator=bdf2_mp_lte_estimate,
1086 | method_order=2)
1087 |
1088 | ts, ys = _odeint(exp3_residual, initial_ts, initial_ys, dts[-1], tmax,
1089 | bdf2_residual, tol, adaptor)
1090 |
1091 | # plt.plot(ts,ys)
1092 | # plt.plot(ts[1:], utils.ts2dts(ts))
1093 | # plt.plot(ts, map(exp3_exact, ts))
1094 | # plt.show()
1095 |
1096 | overall_tol = len(ys) * tol * 2 # 2 is a fudge factor...
1097 | utils.assert_list_almost_equal(ys, map(exp3_exact, ts), overall_tol)
1098 |
1099 |
1100 | def test_ab2():
1101 |
1102 | def check_explicit_stepper(stepper, exact_symb):
1103 |
1104 | exact, residual, dys, J = utils.symb2functions(exact_symb)
1105 |
1106 | base_dt = 1e-3
1107 | ts, ys = odeint_explicit(dys[1], exact(0.0), base_dt, 1.0, stepper,
1108 | time_adaptor=create_random_time_adaptor(base_dt))
1109 |
1110 | exact_ys = map(exact, ts)
1111 | utils.assert_list_almost_equal(ys, exact_ys, 1e-4)
1112 |
1113 | t = sympy.symbols('t')
1114 | functions = [2*t**2,
1115 | sympy.exp(t),
1116 | 3*sympy.exp(-t)
1117 | ]
1118 |
1119 | steppers = ['ab2',
1120 | # 'ebdf2',
1121 | # 'ebdf3'
1122 | ]
1123 |
1124 | for func in functions:
1125 | for stepper in steppers:
1126 | yield check_explicit_stepper, stepper, func
1127 |
1128 |
1129 | def test_dydt_calcs():
1130 |
1131 | def check_dydt_calcs(dydt_calculator, order, dt, dydt_exact, y_exact):
1132 | """Check that derivative approximations are roughly as accurate as
1133 | expected for a few functions.
1134 | """
1135 |
1136 | ts = sp.arange(0, 0.5, dt)
1137 | exact_ys = map(y_exact, ts)
1138 | exact_dys = map(dydt_exact, ts, exact_ys)
1139 |
1140 | est_dys = map(dydt_calculator, utils.partial_lists(ts, 5),
1141 | utils.partial_lists(exact_ys, 5))
1142 |
1143 | utils.assert_list_almost_equal(est_dys, exact_dys[4:], 10*(dt**order))
1144 |
1145 | fs = [(poly_dydt, poly_exact),
1146 | (exp_dydt, exp_exact),
1147 | (exp_of_poly_dydt, exp_of_poly_exact),
1148 | ]
1149 |
1150 | dydt_calculators = [(bdf2_dydt, 2),
1151 | (bdf3_dydt, 3),
1152 | (imr_dydt, 1),
1153 | ]
1154 | dts = [0.1, 0.01, 0.001]
1155 |
1156 | for dt in dts:
1157 | for dydt_exact, y_exact in fs:
1158 | for dydt_calculator, order in dydt_calculators:
1159 | yield check_dydt_calcs, dydt_calculator, order, dt, dydt_exact, y_exact
1160 |
1161 |
1162 | def test_exp_timesteppers():
1163 |
1164 | # Auxilary checking function
1165 | def check_exp_timestepper(method, tol):
1166 | def residual(t, y, dydt):
1167 | return y - dydt
1168 | tmax = 1.0
1169 | dt = 0.001
1170 | ts, ys = odeint(exp_residual, [exp(0.0)], tmax, dt=dt,
1171 | method=method)
1172 |
1173 | # plt.plot(ts,ys)
1174 | # plt.plot(ts, map(exp,ts), '--r')
1175 | # plt.show()
1176 | utils.assert_almost_equal(ys[-1], exp(tmax), tol)
1177 |
1178 | # List of test parameters
1179 | methods = [('bdf2', 1e-5),
1180 | ('bdf1', 1e-2), # First order method...
1181 | ('imr', 1e-5),
1182 | ('trapezoid', 1e-5),
1183 | ]
1184 |
1185 | # Generate tests
1186 | for meth, tol in methods:
1187 | yield check_exp_timestepper, meth, tol
1188 |
1189 |
1190 | def test_vector_timesteppers():
1191 |
1192 | # Auxilary checking function
1193 | def check_vector_timestepper(method, tol):
1194 | def residual(t, y, dydt):
1195 | return sp.array([-1.0 * sin(t), y[1]]) - dydt
1196 | tmax = 1.0
1197 | ts, ys = odeint(residual, [cos(0.0), exp(0.0)], tmax, dt=0.001,
1198 | method=method)
1199 |
1200 | utils.assert_almost_equal(ys[-1][0], cos(tmax), tol[0])
1201 | utils.assert_almost_equal(ys[-1][1], exp(tmax), tol[1])
1202 |
1203 | # List of test parameters
1204 | methods = [('bdf2', [1e-4, 1e-4]),
1205 | ('bdf1', [1e-2, 1e-2]), # First order methods suck...
1206 | ('imr', [1e-4, 1e-4]),
1207 | ('trapezoid', [1e-4, 1e-4]),
1208 | ]
1209 |
1210 | # Generate tests
1211 | for meth, tol in methods:
1212 | yield check_vector_timestepper, meth, tol
1213 |
1214 |
1215 | def test_adaptive_dt():
1216 |
1217 | methods = [('bdf2 mp', 1e-4),
1218 | # ('imr fe ab', 1e-4),
1219 | # ('imr ab', 1e-4),
1220 | ('imr ebdf3', 1e-5), # test with and without explicit f
1221 | ({'label': 'imr ebdf3'}, 1e-5),
1222 | ({'label': 'tr ab'}, 1e-4),
1223 | ]
1224 |
1225 | functions = [(exp_residual, exp, exp_dydt),
1226 | # (exp_of_minus_t_residual, exp_of_minus_t_exact, exp_of_minus_t_dydt),
1227 | (poly_residual, poly_exact, poly_dydt),
1228 | (exp_of_poly_residual, exp_of_poly_exact, exp_of_poly_dydt)
1229 | ]
1230 |
1231 | for meth, tol in methods:
1232 | for residual, exact, dydt in functions:
1233 |
1234 | # If we can, then put the dydt function name into the dict,
1235 | # most methods shouldn't need this.
1236 | try:
1237 | meth['dydt_func'] = dydt
1238 | except TypeError:
1239 | pass
1240 |
1241 | yield check_problem, meth, residual, exact, tol
1242 |
1243 |
1244 | def test_sharp_dt_change():
1245 |
1246 | # Parameters, don't fiddle with these too much or it might miss the
1247 | # step altogether...
1248 | alpha = 20
1249 | step_time = 0.4
1250 | tmax = 2.5
1251 | tol = 1e-4
1252 |
1253 | # Set up functions
1254 | residual = par(tanh_residual, alpha=alpha, step_time=step_time)
1255 | exact = par(tanh_exact, alpha=alpha, step_time=step_time)
1256 |
1257 | # Run it
1258 | return check_problem('bdf2 mp', residual, exact, tol=tol)
1259 |
1260 |
1261 | # def test_with_stiff_problem():
1262 | # """Check that imr fe ab works well for stiff problem (i.e. has a
1263 | # non-insane number of time steps).
1264 | # """
1265 | # Slow test!
1266 |
1267 | # mu = 1000
1268 | # residual = par(van_der_pol_residual, mu=mu)
1269 |
1270 | # ts, ys = odeint(residual, [2.0, 0], 1000.0, dt=1e-6,
1271 | # method='imr ab', target_error=1e-3)
1272 |
1273 | # print len(ts)
1274 | # plt.plot(ts, [y[0] for y in ys])
1275 | # plt.plot(ts[1:], utils.ts2dts(ts))
1276 | # plt.show()
1277 |
1278 | # n_steps = len(ts)
1279 | # assert n_steps < 5000
1280 |
1281 | def test_newton():
1282 | def check_newton(residual, exact):
1283 | solution = newton(residual, sp.array([1.0]*len(exact)))
1284 | utils.assert_list_almost_equal(solution, exact)
1285 |
1286 | tests = [(lambda x: sp.array([x**2 - 2]), sp.array([sp.sqrt(2)])),
1287 | (lambda x: sp.array([x[0]**2 - 2, x[1] - x[0] - 1]),
1288 | sp.array([sp.sqrt(2), sp.sqrt(2) + 1])),
1289 | ]
1290 |
1291 | for res, exact in tests:
1292 | check_newton(res, exact)
1293 |
1294 |
1295 | def test_symbolic_compare_step_time_residual():
1296 |
1297 | # Define the symbols we need
1298 | St = sympy.symbols('t')
1299 | Sdts = sympy.symbols('Delta0:9')
1300 | Sys = sympy.symbols('y0:9')
1301 | Sdys = sympy.symbols('dy0:9')
1302 |
1303 | # Generate the stuff needed to run the residual
1304 | def fake_eqn_residual(ts, ys, dy):
1305 | return Sdys[0] - dy
1306 | fake_ts = utils.dts2ts(St, Sdts[::-1])
1307 | fake_ys = Sys[::-1]
1308 |
1309 | # Check bdf2
1310 | step_result_bdf2 = ibdf2_step(Sdts[0], Sys[1], Sdys[0], Sdts[1], Sys[2])
1311 | res_result_bdf2 = bdf2_residual(fake_eqn_residual, fake_ts, fake_ys)
1312 | res_bdf2_step = sympy.solve(res_result_bdf2, Sys[0])
1313 |
1314 | assert len(res_bdf2_step) == 1
1315 | utils.assert_sym_eq(res_bdf2_step[0], step_result_bdf2)
1316 |
1317 |
1318 | # Check bdf3 -- ??ds too complex..
1319 | # step_result_bdf3 = ibdf3_step(Sdts[0], Sys[1], Sdys[0], Sdts[1], Sys[2],
1320 | # Sdts[2], Sys[3])
1321 | # res_bdf3_result_bdf3 = bdf3_residual(fake_eqn_residual, fake_ts, fake_ys)
1322 | # res_bdf3_step = sympy.solve(res_bdf3_result_bdf3, Sys[0])
1323 |
1324 | # assert len(res_bdf3_step) == 1
1325 | # utils.assert_sym_eq(res_bdf3_step[0], step_result_bdf3)
1326 |
1327 |
1328 | def test_get_ltes_from_data():
1329 |
1330 | # Generate results
1331 | dt = 0.01
1332 | ys, ts = odeint(exp_residual, [exp(0.0)], tmax=0.5, dt=dt,
1333 | method="bdf2")
1334 |
1335 | # Generate ltes
1336 | ltes = get_ltes_from_data(ts, ys, bdf2_mp_lte_estimate)
1337 |
1338 | # Just check that the length is right and that they are the right
1339 | # order of magnitude to be ltes.
1340 | assert len(ltes) == len(ys) - 5
1341 | for lte in ltes:
1342 | utils.assert_same_order_of_magnitude(lte, dt**3)
1343 |
1344 | #
1345 |
--------------------------------------------------------------------------------
/algebra/two_predictor.py:
--------------------------------------------------------------------------------
1 |
2 | from __future__ import division
3 | from __future__ import absolute_import
4 |
5 | import sympy
6 | import scipy.misc
7 | import sys
8 | import itertools as it
9 | import math
10 | import collections
11 |
12 | from sympy import Rational as sRat
13 | from sympy.simplify.cse_main import cse
14 |
15 |
16 | from pprint import pprint as pp
17 | from operator import mul
18 | from functools import partial as par
19 | # import sympy.simplify.simplify as simpl
20 |
21 | import simpleode.core.utils as utils
22 | import simpleode.core.ode as ode
23 |
24 |
25 | # Error calculations
26 | # ============================================================
27 | def imr_lte(dtn, dddynph, Fddynph):
28 | """From my derivations
29 | """
30 | return dtn**3*dddynph/24 + dtn*imr_f_approximation_error(dtn, Fddynph)
31 |
32 |
33 | def bdf2_lte(dtn, dtnm1, dddyn):
34 | """Gresho and Sani pg.715, sign inverted
35 | """
36 | return -((dtn + dtnm1)**2/(dtn*(2*dtn + dtnm1))) * dtn**3 * dddyn/6
37 |
38 |
39 | def bdf3_lte(*_):
40 | """Gresho and Sani pg.715, sign inverted
41 | """
42 | return 0 # No error to O(dtn**4) (third order)
43 |
44 |
45 | def ebdf2_lte(dtn, dtnm1, dddyn):
46 | """Gresho and Sani pg.715, sign inverted, dtn/dtnm1 corrected as in Prinja
47 | """
48 | return (1 + dtnm1/dtn) * dtn**3 * dddyn / 6
49 |
50 |
51 | def ebdf3_lte(*_):
52 | return 0 # no error to O(dtn**4) (third order)
53 |
54 |
55 | def ab2_lte(dtn, dtnm1, dddyn):
56 | return ((2 + 3*(dtnm1/dtn)) * dtn**3 * dddyn)/12
57 |
58 |
59 | def tr_lte(dtn, dddyn):
60 | return -dtn**3 * dddyn/12
61 |
62 |
63 | def imr_f_approximation_error(dtn, Fddynph):
64 | """My derivations:
65 | y'_imr = y'(t_{n+1/2}) + dtn**2 * Fddynph/8 + O(dtn**3)
66 |
67 | => y'(t_{n+1/2}) - y'_imr = -dtn**2 * Fddynph/8 + O(dtn**3)
68 |
69 | """
70 | return -dtn**2*Fddynph/8
71 |
72 |
73 | # Helper functions
74 | # ============================================================
75 | def constify_step(expr):
76 | return expr.subs([(Sdts[1], Sdts[0]),
77 | (Sdts[2], Sdts[0]), (Sdts[3], Sdts[0]),
78 | (Sdts[4], Sdts[0])])
79 |
80 |
81 | def cse_print(expr):
82 | cses, simple_expr = cse(expr)
83 | print
84 | print sympy.pretty(simple_expr)
85 | pp(cses)
86 | print
87 |
88 |
89 | def system2matrix(system, variables):
90 | """Create a matrix from a system of equations (assuming it's linear!).
91 | """
92 | A = sympy.Matrix([[None]*len(system)]*len(variables))
93 | for i, eqn in enumerate(system):
94 | for j, var in enumerate(variables):
95 | # Create a dict where all vars except this one are zero, this
96 | # one is one.
97 | subs_dict = dict([(v, 1 if v == var else 0) for v in variables])
98 | A[i, j] = eqn.subs(subs_dict)
99 |
100 | return A
101 |
102 |
103 | def is_rational(x):
104 | try:
105 | # If it's a sympy object this is all we need
106 | return x.is_rational
107 | except AttributeError:
108 | # Otherwise assume only integers are rational (not other way to
109 | # represent rational numbers afaik).
110 | return is_integer(x)
111 |
112 |
113 | def is_integer(x):
114 | """Check if x is an integer by comparing it with floor(x). This should work
115 | well with floats, sympy rationals etc.
116 | """
117 | return math.floor(x) == x
118 |
119 |
120 | def is_half_integer(x):
121 | return x == (math.floor(x) + float(sRat(1, 2)))
122 |
123 |
124 | def rational_as_mixed(x):
125 | """Convert a rational number to (integer_part, remainder_as_fraction)
126 | """
127 | assert is_rational(x) # Don't want to accidentally end up with floats
128 | # in here as very long rationals!
129 | x_int = int(x)
130 | return x_int, sRat(x - x_int)
131 |
132 |
133 | def sum_dts(a, b):
134 | """Get t_a - t_b in terms of dts.
135 |
136 | e.g.
137 | a = 0, b = 2:
138 | t_0 - t_2 = t_{n+1} - t_{n-1} = dt_{n+1} + dt_n = Sdts[0] + Sdts[1]
139 |
140 | a = 2, b = 0:
141 | t_2 - t_0 = - Sdts[0] - Sdts[1]
142 | """
143 |
144 | # Doesn't work for negative a, b
145 | assert a >= 0 and b >= 0
146 |
147 | # if a and b are in the "wrong" order then it's just the negative of
148 | # the sum with them in the "right" order.
149 | if a > b:
150 | return -1 * sum_dts(b, a)
151 |
152 | # Deal with non-integer a
153 | a_int, a_frac = rational_as_mixed(a)
154 | if a_frac != 0:
155 | result = -a_frac * Sdts[a_int] + sum_dts(a_int, b)
156 | return result
157 |
158 | b_int, b_frac = rational_as_mixed(b)
159 | if b_frac != 0:
160 | return b_frac * Sdts[b_int] + sum_dts(a, b_int)
161 |
162 | return sum(Sdts[a:b])
163 |
164 |
165 | # Define symbol names
166 | # ============================================================
167 | Sdts = sympy.symbols('Delta0:9')
168 | Sys = sympy.symbols('y0:9')
169 | Sdys = sympy.symbols('Dy0:9')
170 | St = sympy.symbols('t')
171 | Sdddynph = sympy.symbols("y'''_h")
172 | SFddynph = sympy.symbols("F.y''_h")
173 | y_np1_exact = sympy.symbols('y_0')
174 | y_np1_imr, y_np1_p2, y_np1_p1 = sympy.symbols('y_0_imr y_0_p2 y_0_p1')
175 |
176 |
177 | # Calculate full errors
178 | # ============================================================
179 | def generate_p_dt_func(symbolic_func):
180 | """Helper function: convert a symbolic function for predictor dt into a
181 | python function f(ts) = predictor_dt.
182 | """
183 | f = sympy.lambdify(Sdts[:5], symbolic_func)
184 |
185 | def p_dt(ts):
186 | assert len(ts) >= 6
187 | # Get last 5 dts in order: n, nm1, nm2 etc.
188 | dts = utils.ts2dts(ts[-6:])[::-1]
189 | return f(*dts) # plug them into the symbolic function
190 | return p_dt
191 |
192 |
193 | PTInfo = collections.namedtuple('PTInfo', ['time', 'y_est', 'dy_est'])
194 |
195 |
196 | def bdf2_imr_ptinfos(pt):
197 | # assert pt == sRat(1,2)
198 | return [PTInfo(pt.time, None, "imr"),
199 | PTInfo(pt.time + sRat(1, 2) + 1, "corr_val", None),
200 | PTInfo(pt.time + sRat(1, 2) + 2, "corr_val", None)]
201 |
202 |
203 | def bdf3_imr_ptinfos(pt):
204 | # assert pt == sRat(1,2)
205 | return [PTInfo(pt.time, None, "imr"),
206 | PTInfo(pt.time + sRat(1, 2), "corr_val", None),
207 | PTInfo(pt.time + sRat(1, 2) + 1, "corr_val", None),
208 | PTInfo(pt.time + sRat(1, 2) + 2, "corr_val", None)]
209 |
210 |
211 | def t_at_time_point(ts, time_point):
212 | """Get the value of time at a "time point" (i.e. the i in n+1-i). Deal with
213 | non integer points by linear interpolation.
214 | """
215 | assert time_point >= 0
216 |
217 | if is_integer(time_point):
218 | return ts[-(time_point+1)]
219 |
220 | # Otherwise linearly interpolate
221 | else:
222 | pa = int(math.floor(time_point))
223 | pb = int(math.ceil(time_point))
224 | frac = time_point - pa
225 | ta = t_at_time_point(ts, pa)
226 | tb = t_at_time_point(ts, pb)
227 | return ta + frac*(tb - ta)
228 |
229 |
230 | def ptinfo2yerr(pt):
231 | """Construct the sympy expression giving the error of the y approximation
232 | requested.
233 | """
234 |
235 | # Use (implicit) bdf2 with the derivative at tnp1 given by implicit
236 | # midpoint rule. Only works at half time steps.
237 | if pt.y_est == "bdf2 imr":
238 | _, y_np1_bdf2 = generate_predictor_scheme(
239 | bdf2_imr_ptinfos(pt), "ibdf2")
240 | y_error = -y_np1_bdf2.subs(y_np1_exact, 0)
241 |
242 | # Use (implicit) bdf3 with the derivative at tnp1 given by implicit
243 | # midpoint rule. Only works at half time steps.
244 | elif pt.y_est == "bdf3 imr":
245 | _, y_np1_bdf3 = generate_predictor_scheme(
246 | bdf3_imr_ptinfos(pt), "ibdf3")
247 | y_error = -y_np1_bdf3.subs(y_np1_exact, 0)
248 |
249 | # Just use corrector value at this point, counts as exact for lte.
250 | elif pt.y_est == "corr_val":
251 | y_error = 0
252 |
253 | elif pt.y_est == "exact":
254 | y_error = 0
255 |
256 | # None: don't use this value
257 | elif pt.y_est is None:
258 | y_error = None
259 |
260 | else:
261 | raise ValueError("Unrecognised y_est name " + str(pt.y_est))
262 |
263 | return y_error
264 |
265 |
266 | def ptinfo2yfunc(pt, y_of_t_func=None):
267 | """Construct a python function to calculate the approximation to y
268 | requested.
269 | """
270 |
271 | # Use (implicit) bdf2 with the derivative at tnp1 given by implicit
272 | # midpoint rule. Only works at half time steps.
273 | if pt.y_est == "bdf2 imr":
274 | y_func, _ = generate_predictor_scheme(bdf2_imr_ptinfos(pt), "ibdf2")
275 |
276 | # Using (implicit) bdf3 with the derivative at tnp1 given by implicit
277 | # midpoint rule. Only works at half time steps.
278 | elif pt.y_est == "bdf3 imr":
279 | y_func, _ = generate_predictor_scheme(bdf3_imr_ptinfos(pt), "ibdf3")
280 |
281 | # Just use corrector value at this point, counts as exact for lte.
282 | elif pt.y_est == "corr_val":
283 | y_func = lambda ts, ys: ys[-(1+pt.time)] # ??ds
284 |
285 | # Use given exact y function
286 | elif pt.y_est == "exact":
287 | assert y_of_t_func is not None
288 |
289 | def y_func(ts, ys):
290 | return y_of_t_func(t_at_time_point(ts, pt.time))
291 |
292 | # None: don't use this value
293 | elif pt.y_est is None:
294 | y_func = None
295 |
296 | else:
297 | raise ValueError("Unrecognised y_est name " + str(pt.y_est))
298 |
299 | return y_func
300 |
301 |
302 | def ptinfo2dyerr(pt):
303 | """Construct the sympy expression giving the error of the dy approximation
304 | requested.
305 | """
306 |
307 | # Use the dy estimate from implicit midpoint rule (obviously only works
308 | # at the midpoint).
309 | if pt.dy_est == "imr":
310 | if not is_half_integer(pt.time):
311 | raise ValueError("imr dy approximation Only works for half integer "
312 | + "points but given the point " + str(pt.time))
313 |
314 | # This works even for time points other than nph because in the
315 | # Taylor expansion {Fddy}_nmh = {Fddy}_nph + higher order terms,
316 | # luckily for us these end up in O(dtn**4) in the end.
317 | dy_error = imr_f_approximation_error(Sdts[0], SFddynph)
318 |
319 | # Use the provided f with known values to calculate dydt.
320 | elif pt.dy_est == "exact":
321 | dy_error = 0
322 |
323 | elif pt.dy_est == "fd4":
324 | dy_error = 0 # assuming we use 4th order fd with all points at
325 | # integers
326 |
327 | # ??ds
328 | elif pt.dy_est == "exp test":
329 | dy_error = 0
330 |
331 | # Don't use this value
332 | elif pt.dy_est is None:
333 | dy_error = None
334 |
335 | else:
336 | raise ValueError(
337 | "Unrecognised dy_est name in error construction " + str(pt.dy_est))
338 |
339 | return dy_error
340 |
341 |
342 | def ptinfo2dyfunc(pt, dydt_func):
343 | """Construct a python function to calculate the approximation to dy
344 | requested. If not using "exact" for dy_est the dydt_func can/should
345 | be None.
346 | """
347 |
348 | # Use the dy estimate from implicit midpoint rule (obviously only works
349 | # at the midpoint).
350 | if pt.dy_est == "imr":
351 | if not is_half_integer(pt.time):
352 | raise ValueError("imr dy approximation Only works for half integer "
353 | + "points but given the point " + str(pt.time))
354 |
355 | # Need to drop some of the later time values if time point is
356 | # not the midpoint of 0 and 1 points (i.e. 1/2). Specifically, we
357 | # need:
358 | # 1/2 -> ts[:None]
359 | # 3/2 -> ts[:-1]
360 | # 5/2 -> ts[:-2]
361 | if pt.time == sRat(1, 2):
362 | # dy_func = ode.imr_dydt
363 | def dy_func(ts, ys):
364 | val = ode.imr_dydt(ts, ys)
365 | print "imr f(t) =", val
366 | return val
367 | else:
368 | x = -math.floor(pt.time)
369 |
370 | def dy_func(ts, ys):
371 | val = ode.imr_dydt(ts[:-int(math.floor(pt.time))],
372 | ys[:-int(math.floor(pt.time))])
373 | print "imr f(t) =", val
374 | return val
375 |
376 | elif pt.dy_est == "fd4":
377 | def dy_func(ts, ys):
378 | coeffs = [-1/12, -2/3, 0, 2/3, -1/12]
379 | ys_used = ys[-6:-1]
380 |
381 | assert len(ys) >= 6
382 |
383 | # ??ds only for constant step! with variable steps we can put
384 | # the 0 at a midpoint to reduce n-prev-steps needed.
385 |
386 | return sp.dot(coeffs, ys_used)
387 |
388 | # ??ds Use real dydt for exp
389 | elif pt.dy_est == "exp test":
390 | def dy_func(ts, ys):
391 | return ys[-(pt.time+1)]
392 |
393 | # Use the provided f with known values to calculate dydt. Only for
394 | # integer time points (i.e. where we already know y etc.) for now.
395 | elif pt.dy_est == "exact":
396 | assert dydt_func is not None
397 |
398 | if is_integer(pt.time):
399 | dy_func = lambda ts, ys: dydt_func(ts[pt.time])
400 | else:
401 | # Can't get y without additional approximations...
402 | def dy_func(ts, ys):
403 | val = dydt_func(t_at_time_point(ts, pt.time))
404 | print "f(t) =", val
405 | return val
406 |
407 | # None = "this value at this point should not be used"
408 | elif pt.dy_est is None:
409 | dy_func = None
410 |
411 | else:
412 | raise ValueError(
413 | "Unrecognised dy_est name in function construction " + str(pt.dy_est))
414 |
415 | return dy_func
416 |
417 |
418 | def generate_predictor_scheme(pt_infos, predictor_name, symbolic=None):
419 |
420 | # Extract symbolic expressions from what we're given.
421 | if symbolic is not None:
422 | try:
423 | symb_exact, symb_F = symbolic
424 |
425 | except TypeError: # not iterable
426 | symb_exact = symbolic
427 |
428 | Sy = sympy.symbols('y', real=True)
429 | symb_dy = sympy.diff(symb_exact, St, 1).subs(symb_exact, Sy)
430 | symb_F = sympy.diff(symb_dy, Sy).subs(Sy, symb_exact)
431 |
432 | dydt_func = sympy.lambdify(St, sympy.diff(symb_exact, St, 1))
433 | f_y = sympy.lambdify(St, symb_exact)
434 |
435 | else:
436 | dydt_func = None
437 | f_y = None
438 |
439 | # To cancel errors we need the final step to be at t_np1
440 | # assert pt_infos[0].time == 0
441 | n_hist = len(pt_infos) + 5
442 |
443 | # Create symbolic and python functions of (corrector) dts and ts
444 | # respectively that give the appropriate dts for this predictor.
445 | p_dtns = []
446 | p_dtn_funcs = []
447 | for pt1, pt2 in zip(pt_infos[:-1], pt_infos[1:]):
448 | p_dtns.append(sum_dts(pt1.time, pt2.time))
449 | p_dtn_funcs.append(generate_p_dt_func(p_dtns[-1]))
450 |
451 | # For each time point the predictor uses construct symbolic error
452 | # estimates for the requested estimate at that point and python
453 | # functions to calculate the value of the estimate.
454 | y_errors = map(ptinfo2yerr, pt_infos)
455 | y_funcs = map(par(ptinfo2yfunc, y_of_t_func=f_y), pt_infos)
456 | dy_errors = map(ptinfo2dyerr, pt_infos)
457 | dy_funcs = map(par(ptinfo2dyfunc, dydt_func=dydt_func), pt_infos)
458 |
459 | # Construct errors and function for the predictor
460 | # ============================================================
461 | if predictor_name == "ebdf2" or predictor_name == "wrong step ebdf2":
462 |
463 | if predictor_name == "wrong step ebdf2":
464 | temp_p_dtnm1 = p_dtns[1] + Sdts[0]
465 | else:
466 | temp_p_dtnm1 = p_dtns[1]
467 |
468 | y_np1_p_expr = y_np1_exact - (
469 | # Natural ebdf2 lte:
470 | ebdf2_lte(p_dtns[0], temp_p_dtnm1, Sdddynph)
471 | # error due to approximation to derivative at tn:
472 | + ode.ebdf2_step(p_dtns[0], 0, dy_errors[1], p_dtns[1], 0)
473 | # error due to approximation to yn
474 | + ode.ebdf2_step(p_dtns[0], y_errors[1], 0, p_dtns[1], 0)
475 | # error due to approximation to ynm1 (typically zero)
476 | + ode.ebdf2_step(p_dtns[0], 0, 0, p_dtns[1], y_errors[2]))
477 |
478 | def predictor_func(ts, ys):
479 |
480 | dtn = p_dtn_funcs[0](ts)
481 | yn = y_funcs[1](ts, ys)
482 | dyn = dy_funcs[1](ts, ys)
483 |
484 | dtnm1 = p_dtn_funcs[1](ts)
485 | ynm1 = y_funcs[2](ts, ys)
486 | return ode.ebdf2_step(dtn, yn, dyn, dtnm1, ynm1)
487 |
488 | elif predictor_name == "ab2":
489 |
490 | y_np1_p_expr = y_np1_exact - (
491 | # Natural ab2 lte:
492 | ab2_lte(p_dtns[0], p_dtns[1], Sdddynph)
493 | # error due to approximation to derivative at tn
494 | + ode.ab2_step(p_dtns[0], 0, dy_errors[1], p_dtns[1], 0)
495 | # error due to approximation to derivative at tnm1
496 | + ode.ab2_step(p_dtns[0], 0, 0, p_dtns[1], dy_errors[2])
497 | # error due to approximation to yn
498 | + ode.ab2_step(p_dtns[0], y_errors[1], 0, p_dtns[1], 0))
499 |
500 | def predictor_func(ts, ys):
501 |
502 | dtn = p_dtn_funcs[0](ts)
503 | yn = y_funcs[1](ts, ys)
504 | dyn = dy_funcs[1](ts, ys)
505 |
506 | dtnm1 = p_dtn_funcs[1](ts)
507 | dynm1 = dy_funcs[2](ts, ys)
508 |
509 | return ode.ab2_step(dtn, yn, dyn, dtnm1, dynm1)
510 |
511 | elif predictor_name == "ibdf2":
512 |
513 | y_np1_p_expr = y_np1_exact - (
514 | # Natural bdf2 lte:
515 | bdf2_lte(p_dtns[0], p_dtns[1], Sdddynph)
516 | # error due to approximation to derivative at tnp1
517 | + ode.ibdf2_step(p_dtns[0], 0, dy_errors[0], p_dtns[1], 0)
518 | # errors due to approximations to y at tn and tnm1
519 | + ode.ibdf2_step(p_dtns[0], y_errors[1], 0, p_dtns[1], 0)
520 | + ode.ibdf2_step(p_dtns[0], 0, 0, p_dtns[1], y_errors[2]))
521 |
522 | def predictor_func(ts, ys):
523 |
524 | pdts = [f(ts) for f in p_dtn_funcs]
525 |
526 | dynp1 = dy_funcs[0](ts, ys)
527 | yn = y_funcs[1](ts, ys)
528 | ynm1 = y_funcs[2](ts, ys)
529 |
530 | tsin = [t_at_time_point(ts, pt.time)
531 | for pt in reversed(pt_infos[1:])]
532 | ysin = [ys[-(pt.time+1)] for pt in reversed(pt_infos[1:])]
533 | dt = pdts[0]
534 |
535 | return ode.ibdf2_step(pdts[0], yn, dynp1, pdts[1], ynm1)
536 |
537 | elif predictor_name == "ibdf3":
538 |
539 | y_np1_p_expr = y_np1_exact - (
540 | # Natural bdf2 lte:
541 | bdf3_lte(p_dtns[0], p_dtns[1], Sdddynph)
542 | # error due to approximation to derivative at tnp1
543 | + ode.ibdf3_step(
544 | dy_errors[0],
545 | p_dtns[0],
546 | 0,
547 | p_dtns[1],
548 | 0,
549 | p_dtns[2],
550 | 0)
551 | # errors due to approximations to y at tn, tnm1, tnm2
552 | + ode.ibdf3_step(
553 | 0,
554 | p_dtns[0],
555 | y_errors[1],
556 | p_dtns[1],
557 | 0,
558 | p_dtns[2],
559 | 0)
560 | + ode.ibdf3_step(
561 | 0,
562 | p_dtns[0],
563 | 0,
564 | p_dtns[1],
565 | y_errors[2],
566 | p_dtns[2],
567 | 0)
568 | + ode.ibdf3_step(0, p_dtns[0], 0, p_dtns[1], 0, p_dtns[2], y_errors[3]))
569 |
570 | def predictor_func(ts, ys):
571 |
572 | pdts = [f(ts) for f in p_dtn_funcs]
573 |
574 | dynp1 = dy_funcs[0](ts, ys)
575 | yn = y_funcs[1](ts, ys)
576 | ynm1 = y_funcs[2](ts, ys)
577 | ynm2 = y_funcs[3](ts, ys)
578 |
579 | return ode.ibdf3_step(dynp1, pdts[0], yn, pdts[1], ynm1,
580 | pdts[2], ynm2)
581 |
582 | elif predictor_name == "ebdf3":
583 | y_np1_p_expr = y_np1_exact - (
584 | # Natural ebdf3 lte error:
585 | ebdf3_lte(p_dtns[0], p_dtns[1], p_dtns[2], Sdddynph)
586 | # error due to approximation to derivative at tn
587 | + ode.ebdf3_step(
588 | p_dtns[0],
589 | 0,
590 | dy_errors[1],
591 | p_dtns[1],
592 | 0,
593 | p_dtns[2],
594 | 0)
595 | # errors due to approximation to y at tn, tnm1, tnm2
596 | + ode.ebdf3_step(p_dtns[0], y_errors[1], 0,
597 | p_dtns[1], 0, p_dtns[2], 0)
598 | + ode.ebdf3_step(p_dtns[0], 0, 0,
599 | p_dtns[1], y_errors[2], p_dtns[2], 0)
600 | + ode.ebdf3_step(p_dtns[0], 0, 0,
601 | p_dtns[1], 0, p_dtns[2], y_errors[3]))
602 |
603 | def predictor_func(ts, ys):
604 |
605 | pdts = [f(ts) for f in p_dtn_funcs]
606 |
607 | dyn = dy_funcs[1](ts, ys)
608 | yn = y_funcs[1](ts, ys)
609 | ynm1 = y_funcs[2](ts, ys)
610 | ynm2 = y_funcs[3](ts, ys)
611 |
612 | return ode.ebdf3_step(pdts[0], yn, dyn,
613 | pdts[1], ynm1,
614 | pdts[2], ynm2)
615 |
616 | elif predictor_name == "use exact dddy":
617 |
618 | symb_dddy = sympy.diff(symb_exact, St, 3)
619 | f_dddy = sympy.lambdify(St, symb_dddy)
620 |
621 | print symb_exact
622 | print "dddy =", symb_dddy
623 |
624 | # "Predictor" is just exactly dddy, error forumlated so that matrix
625 | # turns out right. Calculate at one before last point (same as lte
626 | # "location").
627 | def predictor_func(ts, ys):
628 | tn = t_at_time_point(ts, pt_infos[1].time)
629 | return f_dddy(tn)
630 |
631 | y_np1_p_expr = Sdddynph
632 |
633 | elif predictor_name == "use exact Fddy":
634 |
635 | symb_ddy = sympy.diff(symb_exact, St, 2)
636 | f_Fddy = sympy.lambdify(St, symb_F * symb_ddy)
637 |
638 | print "Fddy =", symb_F * symb_ddy
639 |
640 | # "Predictor" is just exactly dddy, error forumlated so that matrix
641 | # turns out right. Calculate at one before last point (same as lte
642 | # "location").
643 | def predictor_func(ts, ys):
644 | tn = t_at_time_point(ts, pt_infos[1].time)
645 | return f_Fddy(tn)
646 |
647 | y_np1_p_expr = SFddynph
648 |
649 | else:
650 | raise ValueError("Unrecognised predictor name " + predictor_name)
651 |
652 | return predictor_func, y_np1_p_expr
653 |
654 |
655 | def generate_predictor_pair_scheme(p1_points, p1_predictor,
656 | p2_points, p2_predictor,
657 | **kwargs):
658 | """Generate two-predictor lte system of equations and predictor step
659 | functions.
660 | """
661 |
662 | # Generate the two schemes
663 | p1_func, y_np1_p1_expr = generate_predictor_scheme(p1_points, p1_predictor,
664 | **kwargs)
665 | p2_func, y_np1_p2_expr = generate_predictor_scheme(p2_points, p2_predictor,
666 | **kwargs)
667 |
668 | # LTE for IMR: just natural lte:
669 | y_np1_imr_expr = y_np1_exact - imr_lte(Sdts[0], Sdddynph, SFddynph)
670 |
671 | # Return error expressions and stepper functions
672 | return (y_np1_p1_expr, y_np1_p2_expr, y_np1_imr_expr), (p1_func, p2_func)
673 |
674 |
675 | def generate_predictor_pair_lte_est(lte_equations, predictor_funcs):
676 |
677 | assert len(lte_equations) == 3, "only for imr: need 3 ltes to solve"
678 |
679 | (p1_func, p2_func) = predictor_funcs
680 |
681 | A = system2matrix(lte_equations, [Sdddynph, SFddynph, y_np1_exact])
682 |
683 | # Look at some things for the constant step case:
684 | cse_print(constify_step(A))
685 | print sympy.pretty(constify_step(A).det())
686 |
687 | x = A.inv()
688 |
689 | cse_print(constify_step(x))
690 |
691 | # We can get nice expressions by factorising things (row 2 dotted with
692 | # [predictor values] gives us y_np1_exact):
693 | exact_ynp1_symb = sum([y_est * xi.factor() for xi, y_est in
694 | zip(x.row(2), [y_np1_p1, y_np1_p2, y_np1_imr])])
695 |
696 | exact_ynp1_func = sympy.lambdify((Sdts[0], Sdts[1], Sdts[2], Sdts[3],
697 | y_np1_p1, y_np1_p2, y_np1_imr),
698 | exact_ynp1_symb)
699 |
700 | # Debugging:
701 | dddy_symb = sum([y_est * xi.factor() for xi, y_est in
702 | zip(x.row(0), [y_np1_p1, y_np1_p2, y_np1_imr])])
703 | Fddy_symb = sum([y_est * xi.factor() for xi, y_est in
704 | zip(x.row(1), [y_np1_p1, y_np1_p2, y_np1_imr])])
705 | dddy_func = sympy.lambdify((Sdts[0], Sdts[1], Sdts[2], Sdts[3],
706 | y_np1_p1, y_np1_p2, y_np1_imr),
707 | dddy_symb)
708 | Fddy_func = sympy.lambdify((Sdts[0], Sdts[1], Sdts[2], Sdts[3],
709 | y_np1_p1, y_np1_p2, y_np1_imr),
710 | Fddy_symb)
711 |
712 | print sympy.pretty(constify_step(dddy_symb))
713 | print sympy.pretty(constify_step(Fddy_symb))
714 | print sympy.pretty(constify_step(exact_ynp1_symb))
715 |
716 | def lte_est(ts, ys):
717 |
718 | # Compute predicted values
719 | y_np1_p1 = p1_func(ts, ys)
720 | y_np1_p2 = p2_func(ts, ys)
721 |
722 | y_np1_imr = ys[-1]
723 | dtn = ts[-1] - ts[-2]
724 | dtnm1 = ts[-2] - ts[-3]
725 | dtnm2 = ts[-3] - ts[-4]
726 | dtnm3 = ts[-4] - ts[-5]
727 |
728 | # Calculate the exact value (to O(dtn**4))
729 | y_np1_exact = exact_ynp1_func(dtn, dtnm1, dtnm2, dtnm3,
730 | y_np1_p1, y_np1_p2, y_np1_imr)
731 |
732 | dddy_est = dddy_func(
733 | dtn,
734 | dtnm1,
735 | dtnm2,
736 | dtnm3,
737 | y_np1_p1,
738 | y_np1_p2,
739 | y_np1_imr)
740 | Fddy_est = Fddy_func(
741 | dtn,
742 | dtnm1,
743 | dtnm2,
744 | dtnm3,
745 | y_np1_p1,
746 | y_np1_p2,
747 | y_np1_imr)
748 | # print "%0.16f"%y_np1_imr, "%0.16f"%y_np1_p1, "%0.16f"%y_np1_p2
749 | print
750 | print "abs(y_np1_imr - y_np1_p1) =", abs(y_np1_imr - y_np1_p1)
751 | print "abs(y_np1_p2 - y_np1_imr) =", abs(y_np1_p2 - y_np1_imr)
752 | print "dddy_est =", dddy_est
753 | print "Fddy_est =", Fddy_est
754 | print "y_np1_exact - y_np1_imr =", y_np1_exact - y_np1_imr
755 | print "dtn**3 * (dddy_est/24 - Fddy_est/8) =", dtn**3 * (dddy_est/24 - Fddy_est/8)
756 |
757 | # Compare with IMR value to get truncation error
758 | return y_np1_exact - y_np1_imr
759 |
760 | return lte_est
761 |
762 |
763 | # import simpleode.core.example_residuals as er
764 | # import scipy as sp
765 | # from matplotlib.pyplot import show as pltshow
766 | # from matplotlib.pyplot import subplots
767 |
768 | # def main():
769 |
770 | # Function to integrate
771 |
772 | # residual = er.exp_residual
773 | # exact = er.exp_exact
774 |
775 | # residual = par(er.damped_oscillation_residual, 1, 0)
776 | # exact = par(er.damped_oscillation_exact, 1, 0)
777 |
778 | # method
779 | # lte_est = generate_predictor_pair((0, sRat(1,2), 2, "ebdf2"),
780 | # (0, sRat(1,2), sRat(3,2), "ab2"),
781 | # "bdf3",
782 | # "midpoint")
783 | # my_adaptor = par(ode.general_time_adaptor, lte_calculator=lte_est,
784 | # method_order=2)
785 | # init_actions = par(ode.higher_order_start, 6)
786 |
787 | # Do it
788 | # ts, ys = ode._odeint(residual, [sp.array(exact(0.0), ndmin=1)], [0.0],
789 | # 1e-4, 5.0, ode.midpoint_residual,
790 | # 1e-6, my_adaptor, init_actions)
791 |
792 | # Plot
793 |
794 | # Get errors + exact solution
795 | # exacts = map(exact, ts)
796 | # errors = [sp.linalg.norm(y - ex, 2) for y, ex in zip(ys, exacts)]
797 |
798 |
799 | # fig, axes = subplots(4, 1, sharex=True)
800 | # dt_axis=axes[1]
801 | # result_axis=axes[0]
802 | # exact_axis=axes[2]
803 | # error_axis=axes[3]
804 | # method_name = "w18 lte est imr"
805 | # if exact_axis is not None:
806 | # exact_axis.plot(ts, exacts, label=method_name)
807 | # exact_axis.set_xlabel('$t$')
808 | # exact_axis.set_ylabel('$y(t)$')
809 |
810 | # if error_axis is not None:
811 | # error_axis.plot(ts, errors, label=method_name)
812 | # error_axis.set_xlabel('$t$')
813 | # error_axis.set_ylabel('$||y(t) - y_n||_2$')
814 |
815 | # if dt_axis is not None:
816 | # dt_axis.plot(ts[1:], utils.ts2dts(ts),
817 | # label=method_name)
818 | # dt_axis.set_xlabel('$t$')
819 | # dt_axis.set_ylabel('$\Delta_n$')
820 |
821 |
822 | # if result_axis is not None:
823 | # result_axis.plot(ts, ys, label=method_name)
824 | # result_axis.set_xlabel('$t$')
825 | # result_axis.set_ylabel('$y_n$')
826 |
827 | # pltshow()
828 |
829 |
830 | # Tests
831 | # ============================================================
832 | import simpleode.core.example_residuals as er
833 | import scipy as sp
834 | import operator as op
835 |
836 | # def check_dddy_estimates(exact_symb):
837 | # dt = 5e-2
838 |
839 | # Derive the required functions/derivatives:
840 | # exact = sympy.lambdify(sympy.symbols('t'), exact_symb)
841 |
842 | # dy_symb = sympy.diff(exact_symb, sympy.symbols('t'), 1).subs(exact_symb, sympy.symbols('y'))
843 | # residual_symb = sympy.symbols('Dy') - dy_symb
844 | # residual = sympy.lambdify((sympy.symbols('t'), sympy.symbols('y'), sympy.symbols('Dy')),
845 | # residual_symb)
846 |
847 | # dfdy_symb = sympy.diff(dy_symb, sympy.symbols('y'))
848 | # ddy_symb = sympy.diff(exact_symb, sympy.symbols('t'), 2)
849 | # Fdoty = sympy.lambdify((sympy.symbols('t'), sympy.symbols('y')),
850 | # dfdy_symb * ddy_symb)
851 | # exact_dddy_symb = sympy.diff(exact_symb, sympy.symbols('t'), 3)
852 | # exact_dddy = sympy.lambdify(sympy.symbols('t'), exact_dddy_symb)
853 |
854 | # print dfdy_symb, ddy_symb
855 |
856 |
857 | # Solve with imr
858 | # ts, est_ys = ode.odeint(residual, exact(0.0), dt=dt,
859 | # tmax=3.0, method='imr',
860 | # newton_tol=1e-10, jacobian_fd_eps=1e-12)
861 |
862 | # Construct predictors
863 | # p1_steps = (0, sRat(1,2), 3)
864 | # p2_steps = (0, sRat(1,2), 4)
865 | # lte_equations, (p1_func, p2_func) = general_two_predictor(p1_steps, p2_steps)
866 |
867 | # Compare estimates of values with actual values
868 | # n = 5
869 | # for par_ts, par_ys in zip(utils.partial_lists(ts, n), utils.partial_lists(est_ys, n)):
870 | # y_np1_p1 = p1_func(par_ts, par_ys)
871 | # y_np1_p2 = p2_func(par_ts, par_ys)
872 |
873 | # dtn = par_ts[-1] - par_ts[-2]
874 | # dtnm1 = par_ts[-2] - par_ts[-3]
875 | # y_np1_imr = par_ys[-1]
876 |
877 | # dddy_est = t17_dddy_est(dtn, dtnm1, y_np1_p1, y_np1_p2, y_np1_imr)
878 |
879 | # print dtnm1, dtn
880 | # print "%0.16f" % y_np1_imr, "%0.16f" % y_np1_p1, "%0.16f" % y_np1_p2
881 | # print
882 | # print abs(y_np1_imr - y_np1_p2)
883 | # assert abs(y_np1_imr - y_np1_p2) > 1e-8
884 | # assert abs(y_np1_imr - y_np1_p1) > 1e-8
885 |
886 | # Fddy_est = t17_Fddy_est(dtn, dtnm1, y_np1_p1, y_np1_p2, y_np1_imr)
887 |
888 | # dddy = exact_dddy(par_ts[-1])
889 | # Fddy = Fdoty(par_ts[-1], par_ys[-1])
890 |
891 | # utils.assert_almost_equal(dddy_est, , min(1e-6, 30* dt**4))
892 | # utils.assert_almost_equal(Fddy_est, Fddy, min(1e-6, 30* dt**4))
893 |
894 |
895 | # check we actually did something!
896 | # assert utils.partial_lists(ts, n) != []
897 |
898 |
899 | # def test_dddy_estimates():
900 |
901 | #
902 | # t = sympy.symbols('t')
903 |
904 | # equations = [
905 | # 3*t**3,
906 | # sympy.tanh(t),
907 | # sympy.exp(-t)
908 | # ]
909 |
910 |
911 | # for exact_symb in equations:
912 | # yield check_dddy_estimates, exact_symb
913 |
914 |
915 | def test_sum_dts():
916 |
917 | # Check a simple fractional case
918 | utils.assert_sym_eq(sum_dts(sRat(1, 2), 1), Sdts[0]/2)
919 |
920 | # Check two numbers the same gives zero always
921 | utils.assert_sym_eq(sum_dts(1, 1), 0)
922 | utils.assert_sym_eq(sum_dts(0, 0), 0)
923 | utils.assert_sym_eq(sum_dts(sRat(1, 2), sRat(1, 2)), 0)
924 |
925 | def check_sum_dts(a, b):
926 |
927 | # Check we can swap the sign
928 | utils.assert_sym_eq(sum_dts(a, b), -sum_dts(b, a))
929 |
930 | # Starting half a step earlier
931 | utils.assert_sym_eq(sum_dts(a, b + sRat(1, 2)),
932 | sRat(1, 2)*Sdts[int(b)] + sum_dts(a, b))
933 |
934 | # Check that we can split it up
935 | utils.assert_sym_eq(sum_dts(a, b),
936 | sum_dts(a, b-1) + sum_dts(b-1, b))
937 |
938 | # Make sure b>=1 or the last check will fail due to negative b.
939 | cases = [(0, 1),
940 | (5, 8),
941 | (sRat(1, 2), 3),
942 | (sRat(2, 2), 3),
943 | (sRat(3, 2), 3),
944 | (0, sRat(9, 7)),
945 | (sRat(3/4), sRat(9, 7)),
946 | ]
947 |
948 | for a, b in cases:
949 | yield check_sum_dts, a, b
950 |
951 |
952 | def test_ltes():
953 |
954 | import numpy
955 | numpy.seterr(
956 | all='raise',
957 | divide='raise',
958 | over=None,
959 | under=None,
960 | invalid=None)
961 |
962 | def check_lte(method_residual, lte, exact_symb, base_dt, implicit):
963 |
964 | exact, residual, dys, J = utils.symb2functions(exact_symb)
965 | dddy = dys[3]
966 | Fddy = lambda t, y: J(t, y) * dys[2](t, y)
967 |
968 | newton_tol = 1e-10
969 |
970 | # tmax varies with dt so that we can vary dt over orders of
971 | # magnitude.
972 | tmax = 50*dt
973 |
974 | # Run ode solver
975 | if implicit:
976 | ts, ys = ode._odeint(
977 | residual, [0.0], [sp.array([exact(0.0)], ndmin=1)],
978 | dt, tmax, method_residual,
979 | target_error=None,
980 | time_adaptor=ode.create_random_time_adaptor(base_dt),
981 | initialisation_actions=par(ode.higher_order_start, 3),
982 | newton_tol=newton_tol)
983 |
984 | else:
985 | ts, ys = ode.odeint_explicit(
986 | dys[1], exact(0.0), base_dt, tmax, method_residual,
987 | time_adaptor=ode.create_random_time_adaptor(base_dt))
988 |
989 | dts = utils.ts2dts(ts)
990 |
991 | # Check it's accurate-ish
992 | exact_ys = map(exact, ts)
993 | errors = map(op.sub, exact_ys, ys)
994 | utils.assert_list_almost_zero(errors, 1e-3)
995 |
996 | # Calculate ltes by two methods. Note that we need to drop a few
997 | # values because exact calculation (may) need a few dts. Could be
998 | # dodgy: exact dddys might not correspond to dddy in experiment if
999 | # done over long time and we've wandered away from the solution.
1000 | exact_dddys = map(dddy, ts, ys)
1001 | exact_Fddys = map(Fddy, ts, ys)
1002 | exact_ltes = map(lte, dts[2:], dts[1:-1], dts[:-2],
1003 | exact_dddys[3:], exact_Fddys[3:])
1004 | error_diff_ltes = map(op.sub, errors[1:], errors[:-1])[2:]
1005 |
1006 | # Print for debugging when something goes wrong
1007 | print exact_ltes
1008 | print error_diff_ltes
1009 |
1010 | # Probably the best test is that they give the same order of
1011 | # magnitude and the same sign... Can't test much more than that
1012 | # because we have no idea what the constant in front of the dt**4
1013 | # term is. Effective zero (noise level) is either dt**4 or newton
1014 | # tol, whichever is larger.
1015 | z = 50 * max(dt**4, newton_tol)
1016 | map(par(utils.assert_same_sign, fp_zero=z),
1017 | exact_ltes, error_diff_ltes)
1018 | map(par(utils.assert_same_order_of_magnitude, fp_zero=z),
1019 | exact_ltes, error_diff_ltes)
1020 |
1021 | # For checking imr in more detail on J!=0 cases
1022 | # if method_residual is ode.imr_residual:
1023 | # if J(1,2) != 0:
1024 | # assert False
1025 |
1026 | t = sympy.symbols('t')
1027 | functions = [2*t**2,
1028 | t**3 + 3*t**4,
1029 | sympy.exp(t),
1030 | 3*sympy.exp(-t),
1031 | sympy.sin(t),
1032 | sympy.sin(t)**2 + sympy.cos(t)**2
1033 | ]
1034 |
1035 | methods = [
1036 | (ode.imr_residual, True,
1037 | lambda dtn, _, _1, dddyn, Fddy: imr_lte(dtn, dddyn, Fddy)
1038 | ),
1039 |
1040 | (ode.bdf2_residual, True,
1041 | lambda dtn, dtnm1, _, dddyn, _1: bdf2_lte(dtn, dtnm1, dddyn)
1042 | ),
1043 |
1044 | (ode.bdf3_residual, True,
1045 | lambda dtn, dtnm1, dtnm2, dddyn, _: bdf3_lte(dtn, dtnm1, dtnm2, dddyn)
1046 | ),
1047 |
1048 | ('ab2', False,
1049 | lambda dtn, dtnm1, _, dddyn, _1: ab2_lte(dtn, dtnm1, dddyn)
1050 | ),
1051 |
1052 | # ('ebdf2', False,
1053 | # lambda dtn, dtnm1, _, dddyn, _1: ebdf2_lte(dtn, dtnm1, dddyn)
1054 | # ),
1055 |
1056 | # ('ebdf3', False,
1057 | # lambda *_: ebdf3_lte()
1058 | # ),
1059 |
1060 | ]
1061 |
1062 | # Seems to work from 1e-2 down until newton method stops converging due
1063 | # to FD'ed Jacobian. Just do a middling value so that we can wobble the
1064 | # step size around lots without problems.
1065 | dts = [1e-3]
1066 |
1067 | for exact_symb in functions:
1068 | for method_residual, implicit, lte in methods:
1069 | for dt in dts:
1070 | yield check_lte, method_residual, lte, exact_symb, dt, implicit
1071 |
1072 |
1073 | # ??ds test generated predictor calculation functions as well!
1074 |
1075 | def test_imr_predictor_equivalence():
1076 | # Check the we generate imr's lte if we plug in the right times and
1077 | # approximations to ebdf2 (~explicit midpoint rule).
1078 | ynp1_imr = y_np1_exact - imr_lte(Sdts[0], Sdddynph, SFddynph)
1079 |
1080 | _, ynp1_p1 = generate_predictor_scheme([PTInfo(0, None, None),
1081 | PTInfo(
1082 | sRat(1, 2), "bdf2 imr", "imr"),
1083 | PTInfo(1, "corr_val", None)],
1084 | "ebdf2")
1085 | utils.assert_sym_eq(ynp1_imr, ynp1_p1)
1086 |
1087 | # Should be exactly the same with ebdf to calculate the y-est at the
1088 | # midpoint (because the midpoint value is ignored).
1089 | _, ynp1_p2 = generate_predictor_scheme([PTInfo(0, None, None),
1090 | PTInfo(
1091 | sRat(1, 2), "bdf3 imr", "imr"),
1092 | PTInfo(1, "corr_val", None)],
1093 | "ebdf2")
1094 | utils.assert_sym_eq(ynp1_imr, ynp1_p2)
1095 |
1096 |
1097 | def test_tr_ab2_scheme_generation():
1098 | """Make sure tr-ab can be derived using same methodology as I'm using
1099 | (also checks lte expressions).
1100 | """
1101 |
1102 | dddy = sympy.symbols("y'''")
1103 | y_np1_tr = sympy.symbols("y_{n+1}_tr")
1104 |
1105 | ab_pred, ynp1_ab2_expr = generate_predictor_scheme([PTInfo(0, None, None),
1106 | PTInfo(
1107 | 1,
1108 | "corr_val",
1109 | "exp test"),
1110 | PTInfo(
1111 | 2, "corr_val", "exp test")],
1112 | "ab2",
1113 | symbolic=sympy.exp(St))
1114 |
1115 | # ??ds hacky, have to change the symbol to represent where y''' is being
1116 | # evaluated by hand!
1117 | ynp1_ab2_expr = ynp1_ab2_expr.subs(Sdddynph, dddy)
1118 |
1119 | # Check that it gives the same result as we know from the lte
1120 | utils.assert_sym_eq(y_np1_exact - ab2_lte(Sdts[0], Sdts[1], dddy),
1121 | ynp1_ab2_expr)
1122 |
1123 | # Now do the solve etc.
1124 | y_np1_tr_expr = y_np1_exact - tr_lte(Sdts[0], dddy)
1125 | A = system2matrix([ynp1_ab2_expr, y_np1_tr_expr], [dddy, y_np1_exact])
1126 | x = A.inv()
1127 |
1128 | exact_ynp1_symb = sum([y_est * xi.factor() for xi, y_est in
1129 | zip(x.row(1), [y_np1_p1, y_np1_tr])])
1130 |
1131 | exact_ynp1_f = sympy.lambdify(
1132 | (y_np1_p1,
1133 | y_np1_tr,
1134 | Sdts[0],
1135 | Sdts[1]),
1136 | exact_ynp1_symb)
1137 |
1138 | utils.assert_sym_eq(exact_ynp1_symb - y_np1_tr,
1139 | (y_np1_p1 - y_np1_tr)/(3*(1 + Sdts[1]/Sdts[0])))
1140 |
1141 | # Construct an lte estimator from this estimate
1142 | def lte_est(ts, ys):
1143 | ynp1_p = ab_pred(ts, ys)
1144 |
1145 | dtn = ts[-1] - ts[-2]
1146 | dtnm1 = ts[-2] - ts[-3]
1147 |
1148 | ynp1_exact = exact_ynp1_f(ynp1_p, ys[-1], dtn, dtnm1)
1149 | return ynp1_exact - ys[-1]
1150 |
1151 | # Solve exp using tr
1152 | t0 = 0.0
1153 | dt = 1e-2
1154 | ts, ys = ode.odeint(er.exp_residual, er.exp_exact(t0),
1155 | tmax=2.0, dt=dt, method='tr')
1156 |
1157 | # Get error estimates using standard tr ab and the one we just
1158 | # constructed here, then compare.
1159 | this_ltes = ode.get_ltes_from_data(ts, ys, lte_est)
1160 |
1161 | tr_ab_lte = par(ode.tr_ab_lte_estimate, dydt_func=lambda t, y: y)
1162 | standard_ltes = ode.get_ltes_from_data(ts, ys, tr_ab_lte)
1163 |
1164 | # Should be the same (actually the sign is different, but this doesn't
1165 | # matter in lte).
1166 | utils.assert_list_almost_equal(
1167 | this_ltes, map(lambda a: a*-1, standard_ltes), 1e-8)
1168 |
1169 |
1170 | def test_bdf2_ebdf2_scheme_generation():
1171 | """Make sure adaptive bdf2 can be derived using same methodology as I'm
1172 | using (also checks lte expressions).
1173 | """
1174 |
1175 | dddy = sympy.symbols("y'''")
1176 | y_np1_bdf2 = sympy.symbols("y_{n+1}_bdf2")
1177 |
1178 | y_np1_ebdf2_expr = y_np1_exact - ebdf2_lte(Sdts[0], Sdts[1], dddy)
1179 | y_np1_bdf2_expr = y_np1_exact - bdf2_lte(Sdts[0], Sdts[1], dddy)
1180 |
1181 | A = system2matrix([y_np1_ebdf2_expr, y_np1_bdf2_expr], [dddy, y_np1_exact])
1182 | x = A.inv()
1183 |
1184 | exact_ynp1_symb = sum([y_est * xi.factor() for xi, y_est in
1185 | zip(x.row(1), [y_np1_p1, y_np1_bdf2])])
1186 |
1187 | answer = -(Sdts[1] + Sdts[0])*(
1188 | y_np1_bdf2 - y_np1_p1)/(3*Sdts[0] + 2*Sdts[1])
1189 |
1190 | utils.assert_sym_eq(exact_ynp1_symb - y_np1_bdf2,
1191 | answer)
1192 |
1193 |
1194 | def test_generate_predictor_dt_func():
1195 |
1196 | symbs = [Sdts[0], Sdts[1], Sdts[2], Sdts[0] + Sdts[1],
1197 | Sdts[0]/2 + Sdts[1]/2]
1198 |
1199 | t = sympy.symbols('t')
1200 |
1201 | fake_ts = utils.dts2ts(t, Sdts[::-1])
1202 |
1203 | for symb in symbs:
1204 | print fake_ts
1205 | yield utils.assert_sym_eq, symb, generate_p_dt_func(symb)(fake_ts)
1206 |
1207 |
1208 | def test_is_integer():
1209 | tests = [(0, True),
1210 | (0.0, True),
1211 | (0.1, False),
1212 | (1, True),
1213 | (1.0, True),
1214 | (1.1, False),
1215 | (-1.0, True),
1216 | (-1, True),
1217 | (-1.1, False),
1218 | (sp.nan, False),
1219 | # (sp.inf, False), # Returns True, not really what I want but
1220 | # not easily fixable for all possible infs
1221 | # (afaik)
1222 | (1 + 1e-15, False),
1223 | (1 - 1e-15, False),
1224 | ]
1225 |
1226 | for t, result in tests:
1227 | assert is_integer(t) == result
1228 |
1229 |
1230 | def test_is_half_integer():
1231 |
1232 | tests = [(0, False),
1233 | (1239012424481273, False),
1234 | (sRat(1, 2), True),
1235 | (1.5, True),
1236 | (sRat(5, 2), True),
1237 | (2.0 + sRat(1, 2), True),
1238 | (1.5 + 1e-15, False), # 1e-16 fails (gives true)
1239 | (1.51, False),
1240 | ]
1241 |
1242 | for t, result in tests:
1243 | assert is_half_integer(t) == result
1244 |
1245 |
1246 | def test_t_at_time_point():
1247 | tests = [0, 1, sRat(1, 2), sRat(3, 2), 1 + sRat(1, 2), sRat(4, 5), ]
1248 | ts = range(11)
1249 | for pt in tests:
1250 | utils.assert_almost_equal(t_at_time_point(ts, pt), 10 - pt)
1251 |
1252 | # def test_symbolic_predictor_func_comparison():
1253 |
1254 |
1255 | # base = sRat(1,2)
1256 | # p2, _ = generate_predictor_scheme([PTInfo(base, None, "imr"),
1257 | # PTInfo(base + sRat(1,2) + 1, "corr_val", None),
1258 | # PTInfo(base + sRat(1,2) + 2, "corr_val", None)],
1259 | # "ibdf2")
1260 | # p3, _ = generate_predictor_scheme([PTInfo(base, None, "imr"),
1261 | # PTInfo(base + sRat(1,2) + 1, "corr_val", None),
1262 | # PTInfo(base + sRat(1,2) + 2, "corr_val", None),
1263 | # PTInfo(base + sRat(1,2) + 3, "corr_val", None)],
1264 | # "ibdf3")
1265 | # t = sympy.symbols('t')
1266 | # fake_ts = utils.dts2ts(t, Sdts[::-1])
1267 | # fake_ys = sym_ys[::-1]
1268 | # sym_p2 = p2(fake_ts, fake_ys)
1269 | # sym_p3 = p3(fake_ts, fake_ys)
1270 | # print sympy.pretty(sym_p2.simplify())
1271 | # print sympy.pretty(constify_step(sym_p2).simplify())
1272 | # print sympy.pretty(sym_p3.simplify())
1273 | # print sympy.pretty(constify_step(sym_p3).simplify())
1274 | # assert False
1275 | #
1276 | # def test_predictor_error_numerical():
1277 | # def check_predictor_error_numerical(exact_symb, pts_info,
1278 | # predictor_name):
1279 | # Generate forumlae
1280 | # f_exact, residual, f_dys, f_jacobian = utils.symb2functions(exact_symb)
1281 | # f_dddy = f_dys[3]
1282 | # f_ddy = f_dys[2]
1283 | # Get derivative in terms of t only (needed to get exact dydt at
1284 | # non-integer points since we don't know y there).
1285 | # dydt = sympy.diff(exact_symb, St, 1)
1286 | # Generate some midpoint method steps
1287 | # dt = 0.01
1288 | # ts, ys = ode.odeint(residual, f_exact(0.0), dt=dt, tmax=0.5,
1289 | # method="imr", newton_tol=1e-10,
1290 | # jacobian_fd_eps=1e-12)
1291 | # Generate the predictor function + error estimate
1292 | # pfunc, ynp1_p_expr = generate_predictor_scheme(pts_info, predictor_name,
1293 | # dydt)
1294 | # perr = -1*ynp1_p_expr.subs(y_np1_exact, 0)
1295 | # Get values at predictor points
1296 | # py_np1 = pfunc(ts, ys)
1297 | # pts = [t_at_time_point(ts, pt.time) for pt in reversed(pts_info)]
1298 | # pys = map(f_exact, pts[:-1]) +[py_np1]
1299 | # exact_np1_p = f_exact(pts[-1])
1300 | # Compare predicted value with exact value
1301 | # error_n = f_exact(ts[-2]) - ys[-2]
1302 | # error_np1_p = exact_np1_p - py_np1
1303 | # error_change = error_np1_p - error_n
1304 | # print "e_n =", error_n, "e_np1 =", error_np1_p, "e diff =", error_change
1305 | # exact_ys = map(lambda t: sp.array([f_exact(t)], ndmin=1), ts)
1306 | # pfromexact = pfunc(ts, exact_ys)
1307 | # print "pfromexact =", pfromexact, "error_np1 =", exact_np1_p -
1308 | # pfromexact
1309 | # Get last few dts in reverse order (like Sdts order)
1310 | # dts = utils.ts2dts(ts[-10:])[::-1]
1311 | # Compute lte
1312 | # tnph = ts[-2] + (ts[-1] + ts[-2])/2
1313 | # ynph = f_exact(tnph)
1314 | # f_lte = sympy.lambdify([Sdddynph, SFddynph]+list(Sdts), perr)
1315 | # dddynph = f_dddy(tnph, ynph)
1316 | # Fddynph = f_jacobian(tnph, ynph) * f_ddy(tnph, ynph)
1317 | # lte_estimate = f_lte(dddynph, Fddynph, *dts)
1318 | # print "dddynph =", dddynph, "Fddynph =", Fddynph
1319 | # print error_change, "~", lte_estimate, "??"
1320 | # assert False
1321 | # The test function itself:
1322 | # St = sympy.symbols('t')
1323 | # exacts = [
1324 | # sympy.exp(2*St),
1325 | # sympy.sin(St),
1326 | # ]
1327 | # predictors = [
1328 | # Simple:
1329 | # ([PTInfo(sRat(1,2), None, "imr"),
1330 | # PTInfo(2, "corr_val", None),
1331 | # PTInfo(3, "corr_val", None)],
1332 | # "ibdf2"),
1333 | # ([PTInfo(0, None, None),
1334 | # PTInfo(sRat(1,2), "bdf3 imr", "imr"),
1335 | # PTInfo(2, "corr_val", None)],
1336 | # "wrong step ebdf2"),
1337 | # ([PTInfo(sRat(1,2), None, "imr"),
1338 | # PTInfo(1, "corr_val", None),
1339 | # PTInfo(2, "corr_val", None)],
1340 | # "ibdf2"),
1341 | # ([PTInfo(sRat(1,2), None, "exact"),
1342 | # PTInfo(2, "corr_val", None),
1343 | # PTInfo(3, "corr_val", None),
1344 | # PTInfo(4, "corr_val", None)],
1345 | # "ibdf3"),
1346 | # ([PTInfo(sRat(1,2), None, "imr"),
1347 | # PTInfo(1, "corr_val", None),
1348 | # PTInfo(2, "corr_val", None),
1349 | # PTInfo(3, "corr_val", None)],
1350 | # "ibdf3"),
1351 | # Two level (bdfx to get ynph):
1352 | # bdf3:
1353 | # ([PTInfo(0, None, None),
1354 | # PTInfo(sRat(1,2), "bdf3 imr", "imr"),
1355 | # PTInfo(sRat(3,2), None, "imr")],
1356 | # "ab2"),
1357 | # ([PTInfo(0, None, None),
1358 | # PTInfo(sRat(1,2), "bdf3 imr", "imr"),
1359 | # PTInfo(2, "corr_val", None)],
1360 | # "ebdf2"),
1361 | # bdf2:
1362 | # ([PTInfo(0, None, None),
1363 | # PTInfo(sRat(1,2), "bdf2 imr", "imr"),
1364 | # PTInfo(sRat(3,2), None, "imr")],
1365 | # "ab2"),
1366 | # ([PTInfo(0, None, None),
1367 | # PTInfo(sRat(1,2), "bdf2 imr", "imr"),
1368 | # PTInfo(2, "corr_val", None)],
1369 | # "ebdf2"),
1370 | # ]
1371 | # for exact in exacts:
1372 | # for pts, pname in predictors:
1373 | # yield check_predictor_error_numerical, exact, pts, pname
1374 | def test_exact_predictors():
1375 |
1376 | def check_exact_predictors(exact, predictor):
1377 | p1_func, y_np1_p1_expr = \
1378 | generate_predictor_scheme(*predictor, symbolic=exact)
1379 |
1380 | # LTE for IMR: just natural lte:
1381 | y_np1_imr_expr = y_np1_exact - imr_lte(Sdts[0], Sdddynph, SFddynph)
1382 |
1383 | # Generate another predictor
1384 | p2_func, y_np1_p2_expr = \
1385 | generate_predictor_scheme([PTInfo(sRat(1, 2), None, "imr"),
1386 | PTInfo(2, "corr_val", None),
1387 | PTInfo(3, "corr_val", None)], "ibdf2")
1388 |
1389 | A = system2matrix([y_np1_p1_expr, y_np1_p2_expr, y_np1_imr_expr],
1390 | [Sdddynph, SFddynph, y_np1_exact])
1391 |
1392 | # Solve for dddy and Fddy:
1393 | x = A.inv()
1394 | dddy_symb = sum([y_est * xi.factor() for xi, y_est in
1395 | zip(x.row(0), [y_np1_p1, y_np1_p2, y_np1_imr])])
1396 | Fddy_symb = sum([y_est * xi.factor() for xi, y_est in
1397 | zip(x.row(1), [y_np1_p1, y_np1_p2, y_np1_imr])])
1398 |
1399 | # Check we got the right matrix and the right formulae
1400 | if predictor[1] == "use exact dddy":
1401 | assert A.row(0) == sympy.Matrix([[1, 0, 0]]).row(0)
1402 | utils.assert_sym_eq(dddy_symb.simplify(), y_np1_p1)
1403 |
1404 | elif predictor[1] == "use exact Fddy":
1405 | assert A.row(0) == sympy.Matrix([[0, 1, 0]]).row(0)
1406 | utils.assert_sym_eq(Fddy_symb.simplify(), y_np1_p1)
1407 | else:
1408 | assert False
1409 |
1410 | exacts = [sympy.exp(St),
1411 | sympy.sin(St),
1412 | ]
1413 |
1414 | exact_predictors = [
1415 | ([PTInfo(0, None, None),
1416 | PTInfo(sRat(1, 2), None, None)],
1417 | "use exact dddy"),
1418 |
1419 | ([PTInfo(0, None, None),
1420 | PTInfo(sRat(1, 2), None, None)],
1421 | "use exact Fddy"),
1422 | ]
1423 |
1424 | for exact in exacts:
1425 | for p in exact_predictors:
1426 | yield check_exact_predictors, exact, p
1427 |
1428 |
1429 | if __name__ == '__main__':
1430 | sys.exit(test_predictor_error_numerical())
1431 |
--------------------------------------------------------------------------------