diff --git a/.gitignore b/.gitignore index 6c4a347..ba1871c 100644 --- a/.gitignore +++ b/.gitignore @@ -6,4 +6,5 @@ __pycache__/ *.egg-info/ # Sphinx documentation +docs/build/.doctrees/ docs/build/doctrees/ diff --git a/docs/build/html/.buildinfo b/docs/build/html/.buildinfo index 8106eaa..2c89628 100644 --- a/docs/build/html/.buildinfo +++ b/docs/build/html/.buildinfo @@ -1,4 +1,4 @@ # Sphinx build info version 1 # This file hashes the configuration used when building these files. When it is not found, a full rebuild will be done. -config: 94375f4299332632f508e2242b7c30d8 +config: aaf67f6f94ce2e6ce3750a4b226f6461 tags: 645f666f9bcd5a90fca523b33c5a78b7 diff --git a/docs/build/html/_modules/data.html b/docs/build/html/_modules/data.html new file mode 100644 index 0000000..679abdd --- /dev/null +++ b/docs/build/html/_modules/data.html @@ -0,0 +1,179 @@ + + + + + + + data — pylib 2019.5.19 documentation + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Source code for data

+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""Read and write data to or from file.
+
+.. module:: data
+  :platform: *nix, Windows
+  :synopsis: Handle data files.
+
+.. moduleauthor:: Daniel Weschke <daniel.weschke@directbox.de>
+"""
+from __future__ import print_function
+import pickle
+
+
[docs]def data_read(file_name, x_column, y_column): + """Read ascii data file. + + :param filename: file to read + :type filename: str + :param x_column: column index for the x data (first column is 0) + :type x_column: int + :param y_column: column index for the y data (first column is 0) + :type y_column: int + + :returns: x and y + :rtype: tuple(list, list) + """ + import re + file = open(file_name) + x = [] + y = [] + for row in file: + fields = re.split(r'\s+', row.strip()) + #print(filds) + x.append(float(fields[x_column])) + y.append(float(fields[y_column])) + file.close() + return x, y
+ +
[docs]def data_load(file_name, verbose=False): + """Load stored program objects from binary file. + + :param file_name: file to load + :type file_name: str + :param verbose: verbose information (default = False) + :type verbose: bool + + :returns: loaded data + :rtype: object + """ + if verbose: + print('check if data is available') + try: + with open(file_name, 'rb') as input: + object_data = pickle.load(input) # one load for every dump is needed to load all the data + if verbose: + print('found:') + print(object_data) + except IOError: + object_data = None + if verbose: + print('no saved datas found') + return object_data
+ +
[docs]def data_store(file_name, object_data): + """Store program objects to binary file. + + :param file_name: file to store + :type file_name: str + :param object_data: data to store + :type object_data: object + """ + with open(file_name, 'wb') as output: + pickle.dump(object_data, output, pickle.HIGHEST_PROTOCOL) # every dump needs a load
+ +
[docs]def main(): + """Main function.""" + file_name = "slit_test_scan.dat" + x, y = data_read(file_name, 3, 2) + print(x) + print(y)
+
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/build/html/_modules/date.html b/docs/build/html/_modules/date.html new file mode 100644 index 0000000..3ab7901 --- /dev/null +++ b/docs/build/html/_modules/date.html @@ -0,0 +1,222 @@ + + + + + + + date — pylib 2019.5.19 documentation + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Source code for date

+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""Calculate spacial dates.
+
+:Date: 2018-01-15
+
+.. module:: date
+  :platform: *nix, Windows
+  :synopsis: Special dates.
+   
+.. moduleauthor:: Daniel Weschke <daniel.weschke@directbox.de>
+"""
+from __future__ import division, print_function, unicode_literals
+
+
[docs]def gaußsche_osterformel(year): + """Gaußsche Osterformel. + + :param year: the year to calculate the Easter Sunday + :type year: int + + :returns: the day of Easter Sunday as a day in march. + :rtype: int + + :ivar X: Das Jahr / year + :vartype X: int + :ivar K(X): Die Säkularzahl + :vartype K(X): int + :ivar M(X): Die säkulare Mondschaltung + :vartype M(X): int + :ivar S(K): Die säkulare Sonnenschaltung + :vartype S(K): int + :ivar A(X): Den Mondparameter + :vartype A(X): int + :ivar D(A,M): Den Keim für den ersten Vollmond im Frühling + :vartype D(A,M): int + :ivar R(D,A): Die kalendarische Korrekturgröße + :vartype R(D,A): int + :ivar OG(D,R): Die Ostergrenze + :vartype OG(D,R): int + :ivar SZ(X,S): Den ersten Sonntag im März + :vartype SZ(X,S): int + :ivar OE(OG,SZ): Die Entfernung des Ostersonntags von der Ostergrenze (Osterentfernung in Tagen) + :vartype OE(OG,SZ): int + :ivar OS(OG,OE): Das Datum des Ostersonntags als Märzdatum (32. März = 1. April usw.) + :vartype OS(OG,OE): int + + Algorithmus gilt für den Gregorianischen Kalender. + + source: https://de.wikipedia.org/wiki/Gau%C3%9Fsche_Osterformel + """ + x = year + k = x // 100 + m = 15 + (3*k + 3) // 4 - (8*k + 13) // 25 + s = 2 - (3*k + 3) // 4 + a = x % 19 + d = (19*a + m) % 30 + r = (d + a // 11) // 29 + og = 21 + d - r + sz = 7 - (x + x // 4 + s) % 7 + oe = 7 - (og - sz) % 7 + os = og + oe + return os
+ +
[docs]def easter_sunday(year): + """Easter Sunday. + + :param year: the year to calculate the Easter Sunday + :type year: int + + :returns: the day of Easter Sunday + :rtype: datetime.date""" + import datetime + march = datetime.date(year, 3, 1) + day = march + datetime.timedelta(days=gaußsche_osterformel(year)) + return day
+ +
[docs]def easter_friday(year): + """Easter Friday. + + :param year: the year to calculate the Easter Friday + :type year: int + + :returns: the day of Easter Friday + :rtype: datetime.date""" + import datetime + day = easter_sunday(year) + datetime.timedelta(days=-2) + return day
+ +
[docs]def easter_monday(year): + """Easter Monday. + + :param year: the year to calculate the Easter Monday + :type year: int + + :returns: the day of Easter Monday + :rtype: datetime.date""" + import datetime + day = easter_sunday(year) + datetime.timedelta(days=+1) + return day
+ +
[docs]def ascension_of_jesus(year): + """Ascension of Jesus. + + :param year: the year to calculate the ascension of Jesus + :type year: int + + :returns: the day of ascension of Jesus + :rtype: datetime.date""" + import datetime + day = easter_sunday(year) + datetime.timedelta(days=+39) + return day
+ +
[docs]def pentecost(year): + """Pentecost. + + :param year: the year to calculate the Pentecost + :type year: int + + :returns: the day of Pentecost + :rtype: datetime.date""" + import datetime + day = easter_sunday(year) + datetime.timedelta(days=+49) + return day
+
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/build/html/_modules/geometry.html b/docs/build/html/_modules/geometry.html new file mode 100644 index 0000000..e31d1ca --- /dev/null +++ b/docs/build/html/_modules/geometry.html @@ -0,0 +1,306 @@ + + + + + + + geometry — pylib 2019.5.19 documentation + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Source code for geometry

+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""2D geometry objects.
+
+:Date: 2019-03-21
+
+.. module:: geometry
+  :platform: *nix, Windows
+  :synopsis: Geometry objects.
+   
+.. moduleauthor:: Daniel Weschke <daniel.weschke@directbox.de>
+"""
+import math
+import numpy as np
+
+
+
[docs]def translate(vec, *pts): + """Translate a point or polygon by a given vector. + + :param vec: translation vector + :type vec: tuple + :param `*pts`: points to translate + + :returns: (point_x, point_y) or (point1, point2, ...) + :rtype: tuple + """ + vx, vy = vec + return tuple([(x+vx, y+vy) for (x, y) in pts])
+ + +
[docs]def rotate(origin, angle, *pts, **kwargs): + """Rotate a point or polygon counterclockwise by a given angle around a given + origin. The angle should be given in radians. + + :param origin: the center of rotation + :type origin: tuple + :param angle: the rotation angle + :type angle: int or float + :param `*pts`: points to rotate + :param `**kwargs`: options + + :returns: (point_x, point_y) or (point1, point2, ...) + :rtype: tuple + """ + ox, oy = origin + + # add first point to the end + if kwargs is not None and "closed" in kwargs and kwargs["closed"] is True: + pts += (pts[0],) + + result = tuple([(ox + math.cos(angle) * (px - ox) - math.sin(angle) * (py - oy), + oy + math.sin(angle) * (px - ox) + math.cos(angle) * (py - oy)) + for (px, py) in pts]) + + if len(pts) == 1: + return result[0][0], result[0][1] + + return result
+ + +
[docs]def rotate_deg(origin, angle, *pts, **kwargs): + """Rotate a point or polygon counterclockwise by a given angle around a given + origin. The angle should be given in degrees. + + :param origin: the center of rotation + :type origin: tuple + :param angle: the rotation angle + :type angle: int or float + :param `*pts`: points to rotate + :param `**kwargs`: options + + :returns: (point_x, point_y) or (point1, point2, ...) + :rtype: tuple + + .. seealso:: + :meth:`rotate` + """ + return rotate(origin, angle*math.pi/180, *pts, **kwargs)
+ + +
[docs]def rectangle(width, height): + """\ + :param width: the width of the rectangle + :type width: int or float + :param height: the height of the rectangle + :type height: int or float + + :returns: (point1, point2, point3, point4) + :rtype: tuple + """ + pt1 = (-width/2, -height/2) + pt2 = (width/2, -height/2) + pt3 = (width/2, height/2) + pt4 = (-width/2, height/2) + return pt1, pt2, pt3, pt4, pt1
+ + +
[docs]def square(width): + """\ + :param width: the edge size of the square + :type width: int or float + + :returns: (point1, point2, point3, point4) + :rtype: tuple + + .. seealso:: + :meth:`rectangle` + """ + return rectangle(width, width)
+ + +# +# matplotlib format, return lists for x and y +# + +
[docs]def points(*pts): + """\ + :param `*pts`: points to rearrange + + :returns: ((point1_x, point2_x), (point1_y, point2_y), ...) + :rtype: tuple + """ + return zip(*pts)
+ + +
[docs]def line(point1, point2, samples=2): + """\ + .. math:: + y = \\frac{y_2-y_1}{x_2-x_1}(x-x_1) + y_1 + + :param point1: one end point + :type point1: tuple + :param point2: other end point + :type point2: tuple + :param samples: number of sampling points + :type samples: int + + :returns: ((point1_x, point2_x), (points1_y, point2_y)) or + ([sample_point1_x, sample_point2_x, ...], + [sample_points1_y, sample_point2_y, ...]) + :rtype: tuple + """ + p1x, p1y = point1 + p2x, p2y = point2 + + denominator = (p1x - p2x) + + if samples > 2 and denominator > 0: + x = np.linspace(p1x, p2x) + a = (p1y - p2y) / denominator + b = (p1x*p2y - p2x*p1y) / denominator + y = a*x + b + return x, y + return (p1x, p2x), (p1y, p2y) # matplotlib format
+ + +
[docs]def cubic(point1, angle1, point2, angle2, samples=50): + """\ + :param point1: one end point + :type point1: tuple + :param angle1: the slope at the one end point + :type angle1: int or float + :param point2: other end point + :type point2: tuple + :param angle2: the slope at the other end point + :type angle2: int or float + :param samples: number of sampling points + :type samples: int + + :returns: ([sample_point1_x, sample_point2_x, ...], + [sample_points1_y, sample_point2_y, ...]) + :rtype: tuple + """ + p1x, p1y = point1 + p2x, p2y = point2 + + x = np.linspace(p1x, p2x, num=samples) + + p1ys = math.tan(angle1) + p2ys = math.tan(angle2) + a = (p1x*p1ys + p1x*p2ys - p2x*p1ys - p2x*p2ys - 2*p1y + 2*p2y)/(p1x**3 - 3*p1x**2*p2x + 3*p1x*p2x**2 - p2x**3) + b = (- p1x**2*p1ys - 2*p1x**2*p2ys - p1x*p2x*p1ys + p1x*p2x*p2ys + 3*p1x*p1y - 3*p1x*p2y + 2*p2x**2*p1ys + p2x**2*p2ys + 3*p2x*p1y - 3*p2x*p2y)/(p1x**3 - 3*p1x**2*p2x + 3*p1x*p2x**2 - p2x**3) + c = (p1x**3*p2ys + 2*p1x**2*p2x*p1ys + p1x**2*p2x*p2ys - p1x*p2x**2*p1ys - 2*p1x*p2x**2*p2ys - 6*p1x*p2x*p1y + 6*p1x*p2x*p2y - p2x**3*p1ys)/(p1x**3 - 3*p1x**2*p2x + 3*p1x*p2x**2 - p2x**3) + d = (- p1x**3*p2x*p2ys + p1x**3*p2y - p1x**2*p2x**2*p1ys + p1x**2*p2x**2*p2ys - 3*p1x**2*p2x*p2y + p1x*p2x**3*p1ys + 3*p1x*p2x**2*p1y - p2x**3*p1y)/(p1x**3 - 3*p1x**2*p2x + 3*p1x*p2x**2 - p2x**3) + y = a*x**3 + b*x**2 + c*x + d + return x, y
+ + +
[docs]def cubic_deg(point1, angle1, point2, angle2): + """\ + :param point1: one end point + :type point1: tuple + :param angle1: the slope at the one end point + :type angle1: int or float + :param point2: other end point + :type point2: tuple + :param angle2: the slope at the other end point + :type angle2: int or float + + :returns: ([sample_point1_x, sample_point2_x, ...], + [sample_points1_y, sample_point2_y, ...]) + :rtype: tuple + + .. seealso:: + :meth:`cubic` + """ + return cubic(point1, angle1 * math.pi/180, point2, angle2 * math.pi/180)
+
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/build/html/_modules/index.html b/docs/build/html/_modules/index.html new file mode 100644 index 0000000..f359fb7 --- /dev/null +++ b/docs/build/html/_modules/index.html @@ -0,0 +1,104 @@ + + + + + + + Overview: module code — pylib 2019.5.19 documentation + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

All modules for which code is available

+ + +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/build/html/_modules/numerical/fit.html b/docs/build/html/_modules/numerical/fit.html new file mode 100644 index 0000000..b0719af --- /dev/null +++ b/docs/build/html/_modules/numerical/fit.html @@ -0,0 +1,194 @@ + + + + + + + numerical.fit — pylib 2019.5.19 documentation + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Source code for numerical.fit

+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""Function and approximation.
+
+.. module:: fit
+  :platform: *nix, Windows
+  :synopsis: Function and approximation.
+
+.. moduleauthor:: Daniel Weschke <daniel.weschke@directbox.de>
+"""
+from __future__ import print_function
+from pylab import array, argmax, gradient, exp, sqrt, log, linspace
+from scipy.optimize import curve_fit
+
+
[docs]def gauss(x, *p): + """Gauss distribution function. + + .. math:: + f(x)=ae^{-(x-b)^{2}/(2c^{2})} + + :param x: positions where the gauss function will be calculated + :type x: int or float or list or numpy.ndarray + :param p: gauss parameters [a, b, c, d]: + + * a -- amplitude (:math:`\int y \\,\\mathrm{d}x=1 \Leftrightarrow a=1/(c\\sqrt{2\\pi})` ) + * b -- expected value :math:`\\mu` (position of maximum, default = 0) + * c -- standard deviation :math:`\\sigma` (variance :math:`\\sigma^2=c^2`) + * d -- vertical offset (default = 0) + :type p: list + + :returns: gauss values at given positions x + :rtype: numpy.ndarray + """ + x = array(x) # cast e. g. list to numpy array + a, b, c, d = p + return a*exp(-(x - b)**2./(2. * c**2.)) + d
+ +
[docs]def gauss_fit(x, y, e=None, x_fit=None, verbose=False): + """Fit Gauss distribution function to data. + + :param x: positions + :type x: int or float or list or numpy.ndarray + :param y: values + :type y: int or float or list or numpy.ndarray + :param e: error values (default = None) + :type e: int or float or list or numpy.ndarray + :param x_fit: positions of fitted function (default = None, if None then x + is used) + :type x_fit: int or float or list or numpy.ndarray + :param verbose: verbose information (default = False) + :type verbose: bool + + :returns: + * numpy.ndarray -- fitted values (y_fit) + * numpy.ndarray -- parameters of gauss distribution function (popt: + amplitude a, expected value :math:`\\mu`, standard deviation + :math:`\\sigma`, vertical offset d) + * numpy.float64 -- full width at half maximum (FWHM) + :rtype: tuple + + .. seealso:: + :meth:`gauss` + """ + x = array(x) # cast e. g. list to numpy array + y = array(y) # cast e. g. list to numpy array + y_max = max(y) + y_max_pos = argmax(y) + x_y_max = x[y_max_pos] + + # starting parameter + p0 = [y_max, x_y_max, .1, y[0]] + if verbose: + print('p0:', end=' ') + print(p0) + if e is not None: + popt, pcov = curve_fit(gauss, x, y, p0=p0, sigma=e) + else: + popt, pcov = curve_fit(gauss, x, y, p0=p0) + if verbose: + print('popt:', end=' ') + print(popt) + #print(pcov) + + FWHM = 2*sqrt(2*log(2))*popt[2] + if verbose: + print('FWHM', FWHM) + + if x_fit is None: + x_fit = x + y_fit = gauss(x_fit, *popt) + + return y_fit, popt, FWHM
+ +if __name__ == "__main__": + True +
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/build/html/_modules/numerical/integration.html b/docs/build/html/_modules/numerical/integration.html new file mode 100644 index 0000000..e85af51 --- /dev/null +++ b/docs/build/html/_modules/numerical/integration.html @@ -0,0 +1,250 @@ + + + + + + + numerical.integration — pylib 2019.5.19 documentation + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Source code for numerical.integration

+# -*- coding: utf-8 -*-
+"""Numerical integration, numerical quadrature.
+
+de: numerische Integration, numerische Quadratur.
+
+:Date: 2015-10-15
+
+.. module:: integration
+  :platform: *nix, Windows
+  :synopsis: Numerical integration.
+
+.. moduleauthor:: Daniel Weschke <daniel.weschke@directbox.de>
+"""
+
+from __future__ import division
+from numpy import linspace, trapz, zeros
+
+
[docs]def trapez(f, a=0, b=1, N=10, x=None, verbose=False, + save_values=False): + r""" + Integration of :math:`f(x)` using the trapezoidal rule + (Simpson's rule, Kepler's rule). + + de: Trapezregel, Simpsonregel (Thomas Simpson), Keplersche + Fassregel (Johannes Kepler) + + :param f: function to integrate. + :type f: function or list + :param a: lower limit of integration (default = 0). + :type a: float + :param b: upper limit of integration (default = 1). + :type b: float + :param N: specify the number of subintervals. + :type N: int + :param x: variable of integration, necessary if f is a list + (default = None). + :type x: list + :param verbose: print information (default = False) + :type verbose: bool + + :returns: the definite integral as approximated by trapezoidal + rule. + :rtype: float + + The trapezoidal rule approximates the integral by the area of a + trapezoid with base h=b-a and sides equal to the values of the + integrand at the two end points. + + .. math:: + f_n(x) = f(a)+\frac{f(b)-f(a)}{b-a}(x-a) + + .. math:: + I &= \int\limits_a^b f(x) \,\mathrm{d}x \\ + I &\approx \int\limits_a^b f_n(x) \,\mathrm{d}x \\ + &= \int\limits_a^b + \left( f(a)+\frac{f(b)-f(a)}{b-a}(x-a) \right) + \mathrm{d}x \\ + &= \left.\left( f(a)-a\frac{f(b)-f(a)}{b-a} \right) + x \right\vert_a^b + + \left. \frac{f(b)-f(a)}{b-a} \frac{x^2}{2} + \right\vert_a^b \\ + &= \frac{b-a}{2}\left[f(a)+f(b)\right] + + The composite trapezium rule. If the interval is divided into n + segments (not necessarily equal) + + .. math:: + a = x_0 \leq x_1 \leq x_2 \leq \ldots \leq x_n = b + + .. math:: + I &\approx \sum\limits_{i=0}^{n-1} \frac{1}{2} (x_{i+1}-x_i) + \left[f(x_{i+1})+f(x_i)\right] \\ + + Special Case (Equaliy spaced base points) + + .. math:: + x_{i+1}-x_i = h \quad \forall i + + .. math:: + I \approx h \left\{ \frac{1}{2} \left[f(x_0)+f(x_n)\right] + + \sum\limits_{i=1}^{n-1} f(x_i) \right\} + + .. rubric:: Example + + .. math:: + I &= \int\limits_a^b f(x) \,\mathrm{d}x \\ + f(x) &= x^2 \\ + a &= 0 \\ + b &= 1 + + analytical solution + + .. math:: + I = \int\limits_{0}^{1} x^2 \,\mathrm{d}x + = \left. \frac{1}{3} x^3 \right\vert_0^1 + = \frac{1}{3} + + numerical solution + + >>> f = lambda(x): x**2 + >>> trapez(f, 0, 1, 1) + 0.5 + >>> trapez(f, 0, 1, 10) + 0.3350000000000001 + >>> trapez(f, 0, 1, 100) + 0.33335000000000004 + """ + N = int(N) + # f is function or list + if hasattr(f, '__call__'): + # h width of each subinterval + h = (b-a)/N + + # x variable of integration + x = linspace(a, b, N+1) + if save_values: + # ff contribution from the points + ff = zeros((N+1)) + for n in linspace(0, N, N+1): + ff[n] = f(x[n]) + T = (ff[0]/2.+sum(ff[1:N])+ff[N]/2.)*h + else: + TL = f(x[0]) + TR = f(x[N]) + TI = 0 + for n in range(1, N): + TI = TI + f(x[n]) + T = (TL/2.+TI+TR/2.)*h + else: + N = len(f)-1 + T = 0 + for n in range(N): + T = T + (x[n+1]-x[n])/2*(f[n+1]+f[n]) + + if verbose: + print(T) + + return T
+ + +if __name__ == '__main__': + func = lambda x: x**2 + trapez(func, 0, 1, 1e6, verbose=True) + #print(trapz(func, linspace(0,1,10))) + + trapez([0,1,4,9], x=[0,1,2,3], verbose=True) + #print(trapz([0,1,4,9])) + + trapez([2,2], x=[-1,1], verbose=True) + + trapez([-1,1,1,-1], x=[-1,-1,1,1], verbose=True) +
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/build/html/_modules/numerical/ode.html b/docs/build/html/_modules/numerical/ode.html new file mode 100644 index 0000000..b827064 --- /dev/null +++ b/docs/build/html/_modules/numerical/ode.html @@ -0,0 +1,523 @@ + + + + + + + numerical.ode — pylib 2019.5.19 documentation + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Source code for numerical.ode

+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""Numerical solver of ordinary differential equations.
+
+Solves the initial value problem for systems of first order ordinary differential
+equations.
+
+:Date: 2015-09-21
+
+.. module:: ode
+  :platform: *nix, Windows
+  :synopsis: Numerical solver.
+
+.. moduleauthor:: Daniel Weschke <daniel.weschke@directbox.de>
+"""
+
+from __future__ import division, print_function
+from numpy import array, isnan, sum, zeros, dot
+from numpy.linalg import norm, inv
+
+
[docs]def e1(f, x0, t, *p, verbose=False): + r"""Explicit first-order method / + (standard, or forward) Euler method / + Runge-Kutta 1st order method. + + de: + Euler'sche Polygonzugverfahren / explizite Euler-Verfahren / + Euler-Cauchy-Verfahren / Euler-vorwärts-Verfahren + + :param f: the function to solve + :type f: function + :param x0: initial condition + :type x0: list + :param t: time + :type t: list + :param `*p`: parameters of the function (thickness, diameter, ...) + :param verbose: print information (default = False) + :type verbose: bool + + Approximate the solution of the initial value problem + + .. math :: + \dot{x} &= f(t,x) \\ + x(t_0) &= x_0 + + Choose a value h for the size of every step and set + + .. math :: + t_i = t_0 + i h ~,\quad i=1,2,\ldots,n + + The derivative of the solution is approximated as the forward difference + equation + + .. math :: + \dot{x}_i = f(t_i, x_i) = \frac{x_{i+1} - x_i}{t_{i+1}-t_i} + + Therefore one step :math:`h` of the Euler method from :math:`t_i` to + :math:`t_{i+1}` is + + .. math :: + x_{i+1} &= x_i + (t_{i+1}-t_i) f(t_i, x_i) \\ + x_{i+1} &= x_i + h f(t_i, x_i) \\ + + Example 1: + + .. math :: + m\ddot{u} + d\dot{u} + ku = f(t) \\ + \ddot{u} = m^{-1}(f(t) - d\dot{u} - ku) \\ + + with + + .. math :: + x_1 &= u &\quad \dot{x}_1 = \dot{u} = x_2 \\ + x_2 &= \dot{u} &\quad \dot{x}_2 = \ddot{u} \\ + + becomes + + .. math :: + \dot{x}_1 &= x_2 \\ + \dot{x}_2 &= m^{-1}(f(t) - d x_2 - k x_1) \\ + + or + + .. math :: + \dot{x} &= f(t,x) \\ + \begin{bmatrix} \dot{x}_1 \\ \dot{x}_2 \end{bmatrix} &= + \begin{bmatrix} x_2 \\ m^{-1}(f(t) - d x_2 - k x_1) \end{bmatrix} \\ + &= + \begin{bmatrix} 0 \\ m^{-1} f(t) \end{bmatrix} + + \begin{bmatrix} 0 & 1 \\ -m^{-1} k & -m^{-1} d \end{bmatrix} + \begin{bmatrix} x_1 \\ x_2 \end{bmatrix} + + Example 2: + + .. math :: + m(u)\ddot{u} + d(u,\dot{u})\dot{u} + k(u)u = f(t) \\ + \ddot{u} = m^{-1}(u)(f(t) - d(u,\dot{u})\dot{u} - k(u)u) \\ + + with + + .. math :: + x_1 &= u &\quad \dot{x}_1 = \dot{u} = x_2 \\ + x_2 &= \dot{u} &\quad \dot{x}_2 = \ddot{u} \\ + + becomes + + .. math :: + \dot{x}_1 &= x_2 \\ + \dot{x}_2 &= m^{-1}(x_1)(f(t) - d(x_1,x_2) x_2 - k(x_1) x_1) \\ + + or + + .. math :: + \dot{x} &= f(t,x) \\ + \begin{bmatrix} \dot{x}_1 \\ \dot{x}_2 \end{bmatrix} &= + \begin{bmatrix} x_2 \\ m^{-1}(x_1)(f(t) - d(x_1,x_2) x_2 - k(x_1) x_1) \end{bmatrix} \\ + &= + \begin{bmatrix} 0 \\ m^{-1}(x_1) f(t) \end{bmatrix} + + \begin{bmatrix} 0 & 1 \\ -m^{-1}(x_1) k(x_1) & -m^{-1} d(x_1,x_2) \end{bmatrix} + \begin{bmatrix} x_1 \\ x_2 \end{bmatrix} + + The Euler method is a first-order method, + which means that the local error (error per step) is proportional to the + square of the step size, and the global error (error at a given time) is + proportional to the step size. + """ + x = zeros((len(t), len(x0))) # Preallocate array + x[0,:] = x0 # Initial condition gives solution at first t + for i in range(len(t)-1): # Calculation loop + Dt = t[i+1]-t[i] + dxdt = array(f(x[i,:], t[i], *p)) + x[i+1,:] = x[i,:] + dxdt*Dt # Approximate solution at next value of x + if verbose: + print('Numerical integration of ODE using explicit first-order method (Euler / Runge-Kutta) was successful.') + return x
+ +
[docs]def e2(f, x0, t, *p, verbose=False): + r"""Explicit second-order method / Runge-Kutta 2nd order method. + + :param f: the function to solve + :type f: function + :param x0: initial condition + :type x0: list + :param t: time + :type t: list + :param `*p`: parameters of the function (thickness, diameter, ...) + :param verbose: print information (default = False) + :type verbose: bool + """ + x = zeros((len(t), len(x0))) # Preallocate array + x[0,:] = x0 # Initial condition gives solution at first t + for i in range(len(t)-1): # Calculation loop + Dt = t[i+1]-t[i] + k_1 = array(f(x[i,:], t[i], *p)) + k_2 = array(f(x[i,:]+0.5*Dt*k_1, t[i]+0.5*Dt, *p)) + x[i+1,:] = x[i,:] + k_2*Dt # Approximate solution at next value of x + if verbose: + print('Numerical integration of ODE using explicit 2th-order method (Runge-Kutta) was successful.') + return x
+ +
[docs]def e4(f, x0, t, *p, verbose=False): + r"""Explicit fourth-order method / Runge-Kutta 4th order method. + + :param f: the function to solve + :type f: function + :param x0: initial condition + :type x0: list + :param t: time + :type t: list + :param `*p`: parameters of the function (thickness, diameter, ...) + :param verbose: print information (default = False) + :type verbose: bool + """ + x = zeros((len(t), len(x0))) # Preallocate array + x[0,:] = x0 # Initial condition + for i in range(len(t)-1): # Calculation loop + Dt = t[i+1]-t[i] + k_1 = array(f(x[i,:], t[i], *p)) + k_2 = array(f(x[i,:]+0.5*Dt*k_1, t[i]+0.5*Dt, *p)) + k_3 = array(f(x[i,:]+0.5*Dt*k_2, t[i]+0.5*Dt, *p)) + k_4 = array(f(x[i,:]+k_3*Dt, t[i]+Dt, *p)) + x[i+1,:] = x[i,:] + 1./6*(k_1+2*k_2+2*k_3+k_4)*Dt # Approximate solution at next value of x + if verbose: + print('Numerical integration of ODE using explicit 4th-order method (Runge-Kutta) was successful.') + return x
+ +
[docs]def dxdt_Dt(f, x, t, Dt, *p): + r""" + :param f: :math:`f = \dot{x}` + :type f: function + :param Dt: :math:`\Delta{t}` + + :returns: :math:`\Delta x = \dot{x} \Delta t` + """ + return array(dxdt(x, t, *p)) * Dt
+ +
[docs]def fixed_point_iteration(f, xi, t, max_iterations=1000, tol=1e-9, verbose=False): + r""" + :param f: the function to iterate :math:`f = \Delta{x}(t)` + :type f: function + :param xi: initial condition :math:`x_i` + :type xi: list + :param t: time :math:`t` + :type t: float + :param `*p`: parameters of the function (thickness, diameter, ...) + :param max_iterations: maximum number of iterations + :type max_iterations: int + :param tol: tolerance against residuum (default = 1e-9) + :type tol: float + :param verbose: print information (default = False) + :type verbose: bool + + :returns: :math:`x_{i+1}` + + .. math :: + x_{i+1} = x_i + \Delta x + + .. seealso:: + :meth:`dxdt_Dt` for :math:`\Delta x` + """ + xi = x0 + for j in range(max_iterations): # Fixed-point iteration + Dx = array(f(xi, t, *p)) + xi1 = x0 + Dx # Approximate solution at next value of x + residuum = norm(xi1-xi)/norm(xi1) + xi = xi1 + if residuum < tol: + break + iterations = j+1 # number beginning with 1 therefore + 1 + return xi, iterations
+ +
[docs]def i1n(f, x0, t, *p, max_iterations=1000, tol=1e-9, verbose=False): + iterations = zeros((len(t), 1)) + x = zeros((len(t), len(x0))) # Preallocate array + x[0,:] = x0 # Initial condition gives solution at first t + for i in range(len(t)-1): + Dt = t[i+1]-t[i] + xi = x[i,:] + Dx = dxdt_Dt(f, xi, t[i+1], Dt, *p) + x[i+1,:], iterations[i] = fixed_point_iteration(Dx, xi, t, max_iterations, tol, verbose) + if verbose: + print('Numerical integration of ODE using implicite first-order method (Euler) was successful.') + return x, iterations
+ +
[docs]def i1(f, x0, t, *p, max_iterations=1000, tol=1e-9, verbose=False): + r"""Implicite first-order method / backward Euler method. + + :param f: the function to solve + :type f: function + :param x0: initial condition + :type x0: list + :param t: time + :type t: list + :param `*p`: parameters of the function (thickness, diameter, ...) + :param max_iterations: maximum number of iterations + :type max_iterations: int + :param tol: tolerance against residuum (default = 1e-9) + :type tol: float + :param verbose: print information (default = False) + :type verbose: bool + + The backward Euler method has order one and is A-stable. + """ + iterations = zeros((len(t), 1)) + x = zeros((len(t), len(x0))) # Preallocate array + x[0,:] = x0 # Initial condition gives solution at first t + for i in range(len(t)-1): + Dt = t[i+1]-t[i] + xi = x[i,:] + # x(i+1) = x(i) + f(x(i+1), t(i+1)), exact value of f(x(i+1), t(i+1)) is not + # available therefor using Newton-Raphson method + for j in range(max_iterations): # Fixed-point iteration + dxdt = array(f(xi, t[i+1], *p)) + xi1 = x[i,:] + dxdt*Dt # Approximate solution at next value of x + residuum = norm(xi1-xi)/norm(xi1) + xi = xi1 + if residuum < tol: + break + iterations[i] = j+1 + x[i+1,:] = xi + if verbose: + print('Numerical integration of ODE using implicite first-order method (Euler) was successful.') + return x, iterations
+ +
[docs]def newmark_newtonraphson(f, x0, xp0, xpp0, t, *p, gamma=.5, beta=.25, max_iterations=1000, tol=1e-9, verbose=False): + r"""Newmark method. + + :param f: the function to solve + :type f: function + :param x0: initial condition + :type x0: list + :param xp0: initial condition + :type xp0: list + :param xpp0: initial condition + :type xpp0: list + :param t: time + :type t: list + :param `*p`: parameters of the function (thickness, diameter, ...) + :param gamma: newmark parameter for velocity (default = 0.5) + :type gamma: float + :param beta: newmark parameter for displacement (default = 0.25) + :type beta: float + :param max_iterations: maximum number of iterations + :type max_iterations: int + :param tol: tolerance against residuum (default = 1e-9) + :type tol: float + :param verbose: print information (default = False) + :type verbose: bool + """ + iterations = zeros((len(t), 1)) + x = zeros((len(t), len(x0))) # Preallocate array + xp = zeros((len(t), len(xp0))) # Preallocate array + xpp = zeros((len(t), len(xpp0))) # Preallocate array + x[0,:] = x0 # Initial condition gives solution at first t + xp[0,:] = xp0 # Initial condition gives solution at first t + xpp[0,:] = xpp0 # Initial condition gives solution at first t + for i in range(len(t)-1): + Dt = t[i+1]-t[i] + + xi = x[i,:].reshape(3,1) + xpi = xp[i,:].reshape(3,1) + xppi = xpp[i,:].reshape(3,1) + x1 = xi + xp1 = xpi + xpp1 = xppi + j = 0 + for j in range(max_iterations): # Fixed-point iteration + #dxdt = array(f(t[i+1], x1, p)) + #x11 = x[i,:] + dxdt*Dt # Approximate solution at next value of x + + N, dN, dNp, dNpp = f(x1.reshape(-1,).tolist(), + xp1.reshape(-1,).tolist(), xpp1.reshape(-1,).tolist(), + t[i], *p) + if isnan(sum(dN)) or isnan(sum(dNp)) or isnan(sum(dNpp)): + print('divergiert') + break + + xpp11 = xpp1 - dot(inv(dNpp), (N + dot(dN, (x1-xi)) + dot(dNp, (xp1-xpi)))) + xp1 = xpi + Dt*( (1-gamma)*xppi + gamma*xpp11 ) + x1 = xi + Dt*xpi + Dt**2*( (.5-beta)*xppi + beta*xpp11 ) + + residuum = norm(xpp11-xpp1)/norm(xpp11) + xpp1 = xpp11 + if residuum < tol: + break + iterations[i] = j+1 + + xpp[i+1,:] = xpp1.reshape(-1,).tolist() + xp[i+1,:] = xp1.reshape(-1,).tolist() + x[i+1,:] = x1.reshape(-1,).tolist() + if verbose: + print('Numerical integration of ODE using explicite newmark method was successful.') + return x, xp, xpp, iterations
+ # x = concatenate((x, xp, xpp), axis=1) + +
[docs]def newmark_newtonraphson_rdk(fnm, x0, xp0, xpp0, t, *p, gamma=.5, beta=.25, maxIterations=1000, tol=1e-9, verbose=False): + r"""Newmark method. + + :param f: the function to solve + :type f: function + :param x0: initial condition + :type x0: list + :param xp0: initial condition + :type xp0: list + :param xpp0: initial condition + :type xpp0: list + :param t: time + :type t: list + :param `*p`: parameters of the function (thickness, diameter, ...) + :param gamma: newmark parameter for velocity (default = 0.5) + :type gamma: float + :param beta: newmark parameter for displacement (default = 0.25) + :type beta: float + :param max_iterations: maximum number of iterations + :type max_iterations: int + :param tol: tolerance against residuum (default = 1e-9) + :type tol: float + :param verbose: print information (default = False) + :type verbose: bool + """ + iterations = zeros((len(t), 1)) + x = zeros((len(t), len(x0))) # Preallocate array + xp = zeros((len(t), len(xp0))) # Preallocate array + xpp = zeros((len(t), len(xpp0))) # Preallocate array + x[0,:] = x0 # Initial condition gives solution at first t + xp[0,:] = xp0 # Initial condition gives solution at first t + xpp[0,:] = xpp0 # Initial condition gives solution at first t + for i in range(len(t)-1): + Dt = t[i+1]-t[i] + + rm, rmx, rmxpp, rd, rdx, rdxp, rk, rkx, f = fnm(x[i,:], xp[i,:], xpp[i,:], t[i], *p) + + xi = x[i,:].reshape(3,1) + xpi = xp[i,:].reshape(3,1) + xppi = xpp[i,:].reshape(3,1) + x1 = xi + xp1 = xpi + xpp1 = xppi + j = 0 + for j in range(maxIterations): # Fixed-point iteration + #dxdt = array(f(t[i+1], x1, p)) + #x11 = x[i,:] + dxdt*Dt # Approximate solution at next value of x + + r = (rmx+rdx+rkx)*Dt**2./4 + rdxp*Dt/2 + rmxpp + rp = f - (rm + dot(rmx, (Dt*xpi+Dt**2./4*xppi)) - dot(rmxpp, xppi) + \ + rd + dot(rdx, (Dt*xpi+Dt**2./4*xppi)) + dot(rdxp, Dt/2*xppi) + \ + rk + dot(rkx, (Dt*xpi+Dt**2./4*xppi)) ) + xpp11 = dot(inv(r), rp) + xp1 = xpi + Dt*( (1-gamma)*xppi + gamma*xpp11 ) + x1 = xi + Dt*xpi + Dt**2*( (.5-beta)*xppi + beta*xpp11 ) + + residuum = norm(xpp11-xpp1)/norm(xpp11) + xpp1 = xpp11 + if residuum < tol: + break + iterations[i] = j+1 + + xpp[i+1,:] = xpp1.reshape(-1,).tolist() + xp[i+1,:] = xp1.reshape(-1,).tolist() + x[i+1,:] = x1.reshape(-1,).tolist() + if verbose: + print('Numerical integration of ODE using explicite newmark method was successful.') + return x, xp, xpp, iterations
+ # x = concatenate((x, xp, xpp), axis=1) +
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/build/html/_modules/numerical/ode_model.html b/docs/build/html/_modules/numerical/ode_model.html new file mode 100644 index 0000000..2c8e212 --- /dev/null +++ b/docs/build/html/_modules/numerical/ode_model.html @@ -0,0 +1,219 @@ + + + + + + + numerical.ode_model — pylib 2019.5.19 documentation + + + + + + + + + + + + + + + + + + + + +
+
+
+ + +
+ +

Source code for numerical.ode_model

+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""Mathmatical models governed by ordinary differential equations.
+
+Describes initial value problems as systems of first order ordinary differential
+equations.
+
+:Date: 2019-05-25
+
+.. module:: ode_model
+  :platform: *nix, Windows
+  :synopsis: Models of ordinary differential equations.
+
+.. moduleauthor:: Daniel Weschke <daniel.weschke@directbox.de>
+"""
+from __future__ import division, print_function
+from numpy import array, cos, sin, dot, square
+from numpy.linalg import inv
+
+
[docs]def disk(x, t, *p): + """Rotation of an eccentric disk. + + :param x: values of the function + :type x: list + :param t: time + :type t: list + :param `*p`: parameters of the function + + * diameter + * eccentricity + * torque + """ + qp1 = x[3] + qp2 = x[4] + qp3 = x[5] + M = array([[1, 0, cos(x[2])], [0, 1, -sin(x[2])], [0, 0, 1]]) + y = array([[-2*p[0]*x[3]+sin(x[2])*x[5]**2-2*p[0]*cos(x[2])*x[5]-x[0]], \ + [-2*p[0]*x[4]+cos(x[2])*x[5]**2-2*p[0]*sin(x[2])*x[5]-x[1]], \ + [p[2]-p[1]*x[1]*sin(x[2])+p[1]*x[0]*cos(x[2])]]) + qp46 = dot(inv(M), y) + qp4, qp5, qp6 = qp46.reshape(-1,).tolist() # 2d array to 1d array to list + return qp1, qp2, qp3, qp4, qp5, qp6
+ +
[docs]def disk_nm(xn, xpn, xppn, t, *p): + """Rotation of an eccentric disk. + + :param xn: values of the function + :type xn: list + :param xpn: first derivative values of the function + :type xpn: list + :param xppn: second derivative values of the function + :type xppn: list + :param t: time + :type t: list + :param `*p`: parameters of the function + + * diameter + * eccentricity + * torque + """ + N = array([[xppn[0]+cos(xn[2])*xppn[2]+2*p[0]*xpn[0]+2*p[0]*cos(xn[2])*xpn[2]-sin(xn[2])*square(xpn[2])+xn[0]], + [xppn[1]-sin(xn[2])*xppn[2]+2*p[0]*xpn[1]-2*p[0]*sin(xn[2])*xpn[2]-cos(xn[2])*square(xpn[2])+xn[1]], + [xppn[2]+p[1]*(-cos(xn[2])*xn[0]+sin(xn[2])*xn[1])-p[2]]]) + dN = array([[1, 0, -sin(xn[2]*xppn[2])-2*p[0]*sin(xn[2])*xpn[2]-cos(xn[2])*square(xpn[2])], + [0, 1, -cos(xn[2]*xppn[2])-2*p[0]*cos(xn[2])*xpn[2]+sin(xn[2])*square(xpn[2])], + [-p[1]*cos(xn[2]), p[1]*cos(xn[2]), p[1]*(sin(xn[2])*xn[0]+cos(xn[2])*xn[1])]]) + dNp = array([[2*p[0], 0, 2*p[0]*cos(xn[2])-2*sin(xn[2])*xpn[2]], + [0, 2*p[0], -2*p[0]*sin(xn[2])-2*cos(xn[2])*xpn[2]], + [0, 0, 0]]) + dNpp = array([[1, 0, cos(xn[2])], + [0, 1, -sin(xn[2])], + [0, 0, 1]]) + return N, dN, dNp, dNpp
+ +
[docs]def disk_nmmdk(xn, xpn, xppn, t, *p): + """Rotation of an eccentric disk. + + :param xn: values of the function + :type xn: list + :param xpn: derivative values of the function + :type xpn: list + :param xppn: second derivative values of the function + :type xppn: list + :param t: time + :type t: list + :param `*p`: parameters of the function + + * diameter + * eccentricity + * torque + """ + rm = array([[xppn[0]+cos(xn[2])*xppn[2]], + [xppn[1]-sin(xn[2])*xppn[2]], + [xppn[2]]]) + rmx = array([[0, 0, -sin(xn[2]*xppn[2])], + [0, 0, -cos(xn[2]*xppn[2])], + [0, 0, 0]]) + rmxpp = array([[1, 0, cos(xn[2])], + [0, 1, -sin(xn[2])], + [0, 0, 1]]) + rd = array([[2*p[0]*xpn[0]+2*p[0]*cos(xn[2])*xpn[2]-sin(xn[2])*square(xpn[2])], + [2*p[0]*xpn[1]-2*p[0]*sin(xn[2])*xpn[2]-cos(xn[2])*square(xpn[2])], + [0]]) + rdx = array([[0, 0, -2*p[0]*sin(xn[2])*xpn[2]-cos(xn[2])*square(xpn[2])], + [0, 0, -2*p[0]*cos(xn[2])*xpn[2]+sin(xn[2])*square(xpn[2])], + [0, 0, 0]]) + rdxp = array([[2*p[0], 0, 2*p[0]*cos(xn[2])-2*sin(xn[2])*xpn[2]], + [0, 2*p[0], -2*p[0]*sin(xn[2])-2*cos(xn[2])*xpn[2]], + [0, 0, 0]]) + rk = array([[xn[0]], + [xn[1]], + [p[1]*(-cos(xn[2])*xn[0]+sin(xn[2])*xn[1])]]) + rkx = array([[ 1, 0, 0], + [ 0, 1, 0], + [-p[1]*cos(xn[2]), p[1]*cos(xn[2]), p[1]*(sin(xn[2])*xn[0]+cos(xn[2])*xn[1])]]) + f = array([[0], [0], [p[2]]]) + return rm, rmx, rmxpp, rd, rdx, rdxp, rk, rkx, f
+ +if __name__ == '__main__': + True +
+ +
+ +
+
+ +
+
+ + + + + + + \ No newline at end of file diff --git a/docs/build/html/_sources/fit.rst.txt b/docs/build/html/_sources/fit.rst.txt deleted file mode 100644 index 21a5d59..0000000 --- a/docs/build/html/_sources/fit.rst.txt +++ /dev/null @@ -1,7 +0,0 @@ -fit module -========== - -.. automodule:: fit - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/modules.rst.txt b/docs/build/html/_sources/modules.rst.txt index 6a908e5..4679bea 100644 --- a/docs/build/html/_sources/modules.rst.txt +++ b/docs/build/html/_sources/modules.rst.txt @@ -6,7 +6,5 @@ src data date - fit geometry - solver - solver_model + numerical diff --git a/docs/build/html/_sources/numerical.rst.txt b/docs/build/html/_sources/numerical.rst.txt new file mode 100644 index 0000000..e37c893 --- /dev/null +++ b/docs/build/html/_sources/numerical.rst.txt @@ -0,0 +1,46 @@ +numerical package +================= + +Submodules +---------- + +numerical.fit module +-------------------- + +.. automodule:: numerical.fit + :members: + :undoc-members: + :show-inheritance: + +numerical.integration module +---------------------------- + +.. automodule:: numerical.integration + :members: + :undoc-members: + :show-inheritance: + +numerical.ode module +-------------------- + +.. automodule:: numerical.ode + :members: + :undoc-members: + :show-inheritance: + +numerical.ode\_model module +--------------------------- + +.. automodule:: numerical.ode_model + :members: + :undoc-members: + :show-inheritance: + + +Module contents +--------------- + +.. automodule:: numerical + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/build/html/_sources/solver.rst.txt b/docs/build/html/_sources/solver.rst.txt deleted file mode 100644 index 0d6d757..0000000 --- a/docs/build/html/_sources/solver.rst.txt +++ /dev/null @@ -1,7 +0,0 @@ -solver module -============= - -.. automodule:: solver - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_sources/solver_model.rst.txt b/docs/build/html/_sources/solver_model.rst.txt deleted file mode 100644 index bc08685..0000000 --- a/docs/build/html/_sources/solver_model.rst.txt +++ /dev/null @@ -1,7 +0,0 @@ -solver\_model module -==================== - -.. automodule:: solver_model - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/build/html/_static/alabaster.css b/docs/build/html/_static/alabaster.css index b1d8d1a..8ccb045 100644 --- a/docs/build/html/_static/alabaster.css +++ b/docs/build/html/_static/alabaster.css @@ -310,7 +310,7 @@ div.hint { } div.seealso { - background-color: #3c3c3c; + background-color: #25272c; border: 1px solid #2C2C2C; } @@ -439,14 +439,14 @@ ul, ol { } pre { - background: #EEE; + background: #25272c; padding: 7px 30px; margin: 15px 0px; line-height: 1.3em; } div.viewcode-block:target { - background: #ffd; + background: #292b2e; } dl pre, blockquote pre, li pre { diff --git a/docs/build/html/_static/custom.css b/docs/build/html/_static/custom.css index d60ea94..b6a5152 100644 --- a/docs/build/html/_static/custom.css +++ b/docs/build/html/_static/custom.css @@ -5,3 +5,9 @@ table.indextable tr.cap { background-color: #333; } +/* move doc link a bit up */ +.viewcode-back { + float: right; + position: relative; + top: -1.5em; +} diff --git a/docs/build/html/_static/pygments.css b/docs/build/html/_static/pygments.css index dd6621d..80ac0f7 100644 --- a/docs/build/html/_static/pygments.css +++ b/docs/build/html/_static/pygments.css @@ -1,77 +1,78 @@ -.highlight .hll { background-color: #ffffcc } -.highlight { background: #f8f8f8; } -.highlight .c { color: #8f5902; font-style: italic } /* Comment */ -.highlight .err { color: #a40000; border: 1px solid #ef2929 } /* Error */ -.highlight .g { color: #000000 } /* Generic */ -.highlight .k { color: #004461; font-weight: bold } /* Keyword */ -.highlight .l { color: #000000 } /* Literal */ -.highlight .n { color: #000000 } /* Name */ -.highlight .o { color: #582800 } /* Operator */ -.highlight .x { color: #000000 } /* Other */ -.highlight .p { color: #000000; font-weight: bold } /* Punctuation */ -.highlight .ch { color: #8f5902; font-style: italic } /* Comment.Hashbang */ -.highlight .cm { color: #8f5902; font-style: italic } /* Comment.Multiline */ -.highlight .cp { color: #8f5902 } /* Comment.Preproc */ -.highlight .cpf { color: #8f5902; font-style: italic } /* Comment.PreprocFile */ -.highlight .c1 { color: #8f5902; font-style: italic } /* Comment.Single */ -.highlight .cs { color: #8f5902; font-style: italic } /* Comment.Special */ -.highlight .gd { color: #a40000 } /* Generic.Deleted */ -.highlight .ge { color: #000000; font-style: italic } /* Generic.Emph */ -.highlight .gr { color: #ef2929 } /* Generic.Error */ -.highlight .gh { color: #000080; font-weight: bold } /* Generic.Heading */ -.highlight .gi { color: #00A000 } /* Generic.Inserted */ -.highlight .go { color: #888888 } /* Generic.Output */ -.highlight .gp { color: #745334 } /* Generic.Prompt */ -.highlight .gs { color: #000000; font-weight: bold } /* Generic.Strong */ -.highlight .gu { color: #800080; font-weight: bold } /* Generic.Subheading */ -.highlight .gt { color: #a40000; font-weight: bold } /* Generic.Traceback */ -.highlight .kc { color: #004461; font-weight: bold } /* Keyword.Constant */ -.highlight .kd { color: #004461; font-weight: bold } /* Keyword.Declaration */ -.highlight .kn { color: #004461; font-weight: bold } /* Keyword.Namespace */ -.highlight .kp { color: #004461; font-weight: bold } /* Keyword.Pseudo */ -.highlight .kr { color: #004461; font-weight: bold } /* Keyword.Reserved */ -.highlight .kt { color: #004461; font-weight: bold } /* Keyword.Type */ -.highlight .ld { color: #000000 } /* Literal.Date */ -.highlight .m { color: #990000 } /* Literal.Number */ -.highlight .s { color: #4e9a06 } /* Literal.String */ -.highlight .na { color: #c4a000 } /* Name.Attribute */ -.highlight .nb { color: #004461 } /* Name.Builtin */ -.highlight .nc { color: #000000 } /* Name.Class */ -.highlight .no { color: #000000 } /* Name.Constant */ -.highlight .nd { color: #888888 } /* Name.Decorator */ -.highlight .ni { color: #ce5c00 } /* Name.Entity */ -.highlight .ne { color: #cc0000; font-weight: bold } /* Name.Exception */ -.highlight .nf { color: #000000 } /* Name.Function */ -.highlight .nl { color: #f57900 } /* Name.Label */ -.highlight .nn { color: #000000 } /* Name.Namespace */ -.highlight .nx { color: #000000 } /* Name.Other */ -.highlight .py { color: #000000 } /* Name.Property */ -.highlight .nt { color: #004461; font-weight: bold } /* Name.Tag */ -.highlight .nv { color: #000000 } /* Name.Variable */ -.highlight .ow { color: #004461; font-weight: bold } /* Operator.Word */ -.highlight .w { color: #f8f8f8; text-decoration: underline } /* Text.Whitespace */ -.highlight .mb { color: #990000 } /* Literal.Number.Bin */ -.highlight .mf { color: #990000 } /* Literal.Number.Float */ -.highlight .mh { color: #990000 } /* Literal.Number.Hex */ -.highlight .mi { color: #990000 } /* Literal.Number.Integer */ -.highlight .mo { color: #990000 } /* Literal.Number.Oct */ -.highlight .sa { color: #4e9a06 } /* Literal.String.Affix */ -.highlight .sb { color: #4e9a06 } /* Literal.String.Backtick */ -.highlight .sc { color: #4e9a06 } /* Literal.String.Char */ -.highlight .dl { color: #4e9a06 } /* Literal.String.Delimiter */ -.highlight .sd { color: #8f5902; font-style: italic } /* Literal.String.Doc */ -.highlight .s2 { color: #4e9a06 } /* Literal.String.Double */ -.highlight .se { color: #4e9a06 } /* Literal.String.Escape */ -.highlight .sh { color: #4e9a06 } /* Literal.String.Heredoc */ -.highlight .si { color: #4e9a06 } /* Literal.String.Interpol */ -.highlight .sx { color: #4e9a06 } /* Literal.String.Other */ -.highlight .sr { color: #4e9a06 } /* Literal.String.Regex */ -.highlight .s1 { color: #4e9a06 } /* Literal.String.Single */ -.highlight .ss { color: #4e9a06 } /* Literal.String.Symbol */ -.highlight .bp { color: #3465a4 } /* Name.Builtin.Pseudo */ -.highlight .fm { color: #000000 } /* Name.Function.Magic */ -.highlight .vc { color: #000000 } /* Name.Variable.Class */ -.highlight .vg { color: #000000 } /* Name.Variable.Global */ -.highlight .vi { color: #000000 } /* Name.Variable.Instance */ -.highlight .vm { color: #000000 } /* Name.Variable.Magic */ -.highlight .il { color: #990000 } /* Literal.Number.Integer.Long */ \ No newline at end of file +.highlight .hll { background-color: #073642 } +.highlight { background: #002b36; color: #839496 } +.highlight .c { color: #586e75; font-style: italic } /* Comment */ +.highlight .err { color: #839496; background-color: #dc322f } /* Error */ +.highlight .esc { color: #839496 } /* Escape */ +.highlight .g { color: #839496 } /* Generic */ +.highlight .k { color: #859900 } /* Keyword */ +.highlight .l { color: #839496 } /* Literal */ +.highlight .n { color: #839496 } /* Name */ +.highlight .o { color: #586e75 } /* Operator */ +.highlight .x { color: #839496 } /* Other */ +.highlight .p { color: #839496 } /* Punctuation */ +.highlight .ch { color: #586e75; font-style: italic } /* Comment.Hashbang */ +.highlight .cm { color: #586e75; font-style: italic } /* Comment.Multiline */ +.highlight .cp { color: #d33682 } /* Comment.Preproc */ +.highlight .cpf { color: #586e75 } /* Comment.PreprocFile */ +.highlight .c1 { color: #586e75; font-style: italic } /* Comment.Single */ +.highlight .cs { color: #586e75; font-style: italic } /* Comment.Special */ +.highlight .gd { color: #dc322f } /* Generic.Deleted */ +.highlight .ge { color: #839496; font-style: italic } /* Generic.Emph */ +.highlight .gr { color: #dc322f } /* Generic.Error */ +.highlight .gh { color: #839496; font-weight: bold } /* Generic.Heading */ +.highlight .gi { color: #859900 } /* Generic.Inserted */ +.highlight .go { color: #839496 } /* Generic.Output */ +.highlight .gp { color: #839496 } /* Generic.Prompt */ +.highlight .gs { color: #839496; font-weight: bold } /* Generic.Strong */ +.highlight .gu { color: #839496; text-decoration: underline } /* Generic.Subheading */ +.highlight .gt { color: #268bd2 } /* Generic.Traceback */ +.highlight .kc { color: #2aa198 } /* Keyword.Constant */ +.highlight .kd { color: #2aa198 } /* Keyword.Declaration */ +.highlight .kn { color: #cb4b16 } /* Keyword.Namespace */ +.highlight .kp { color: #859900 } /* Keyword.Pseudo */ +.highlight .kr { color: #859900 } /* Keyword.Reserved */ +.highlight .kt { color: #b58900 } /* Keyword.Type */ +.highlight .ld { color: #839496 } /* Literal.Date */ +.highlight .m { color: #2aa198 } /* Literal.Number */ +.highlight .s { color: #2aa198 } /* Literal.String */ +.highlight .na { color: #839496 } /* Name.Attribute */ +.highlight .nb { color: #268bd2 } /* Name.Builtin */ +.highlight .nc { color: #268bd2 } /* Name.Class */ +.highlight .no { color: #268bd2 } /* Name.Constant */ +.highlight .nd { color: #268bd2 } /* Name.Decorator */ +.highlight .ni { color: #268bd2 } /* Name.Entity */ +.highlight .ne { color: #268bd2 } /* Name.Exception */ +.highlight .nf { color: #268bd2 } /* Name.Function */ +.highlight .nl { color: #268bd2 } /* Name.Label */ +.highlight .nn { color: #268bd2 } /* Name.Namespace */ +.highlight .nx { color: #839496 } /* Name.Other */ +.highlight .py { color: #839496 } /* Name.Property */ +.highlight .nt { color: #268bd2 } /* Name.Tag */ +.highlight .nv { color: #268bd2 } /* Name.Variable */ +.highlight .ow { color: #859900 } /* Operator.Word */ +.highlight .w { color: #839496 } /* Text.Whitespace */ +.highlight .mb { color: #2aa198 } /* Literal.Number.Bin */ +.highlight .mf { color: #2aa198 } /* Literal.Number.Float */ +.highlight .mh { color: #2aa198 } /* Literal.Number.Hex */ +.highlight .mi { color: #2aa198 } /* Literal.Number.Integer */ +.highlight .mo { color: #2aa198 } /* Literal.Number.Oct */ +.highlight .sa { color: #2aa198 } /* Literal.String.Affix */ +.highlight .sb { color: #2aa198 } /* Literal.String.Backtick */ +.highlight .sc { color: #2aa198 } /* Literal.String.Char */ +.highlight .dl { color: #2aa198 } /* Literal.String.Delimiter */ +.highlight .sd { color: #586e75 } /* Literal.String.Doc */ +.highlight .s2 { color: #2aa198 } /* Literal.String.Double */ +.highlight .se { color: #2aa198 } /* Literal.String.Escape */ +.highlight .sh { color: #2aa198 } /* Literal.String.Heredoc */ +.highlight .si { color: #2aa198 } /* Literal.String.Interpol */ +.highlight .sx { color: #2aa198 } /* Literal.String.Other */ +.highlight .sr { color: #cb4b16 } /* Literal.String.Regex */ +.highlight .s1 { color: #2aa198 } /* Literal.String.Single */ +.highlight .ss { color: #2aa198 } /* Literal.String.Symbol */ +.highlight .bp { color: #268bd2 } /* Name.Builtin.Pseudo */ +.highlight .fm { color: #268bd2 } /* Name.Function.Magic */ +.highlight .vc { color: #268bd2 } /* Name.Variable.Class */ +.highlight .vg { color: #268bd2 } /* Name.Variable.Global */ +.highlight .vi { color: #268bd2 } /* Name.Variable.Instance */ +.highlight .vm { color: #268bd2 } /* Name.Variable.Magic */ +.highlight .il { color: #2aa198 } /* Literal.Number.Integer.Long */ \ No newline at end of file diff --git a/docs/build/html/data.html b/docs/build/html/data.html index bf20189..0a100a0 100644 --- a/docs/build/html/data.html +++ b/docs/build/html/data.html @@ -37,7 +37,7 @@

Read and write data to or from file.

-data_load(file_name, verbose=False)
+data_load(file_name, verbose=False)[source]

Load stored program objects from binary file.

Parameters
@@ -57,7 +57,7 @@
-data_read(file_name, x_column, y_column)
+data_read(file_name, x_column, y_column)[source]

Read ascii data file.

Parameters
@@ -78,7 +78,7 @@
-data_store(file_name, object_data)
+data_store(file_name, object_data)[source]

Store program objects to binary file.

Parameters
@@ -92,7 +92,7 @@
-main()
+main()[source]

Main function.

diff --git a/docs/build/html/date.html b/docs/build/html/date.html index e0fb1b6..8cbce23 100644 --- a/docs/build/html/date.html +++ b/docs/build/html/date.html @@ -42,7 +42,7 @@
-ascension_of_jesus(year)
+ascension_of_jesus(year)[source]

Ascension of Jesus.

Parameters
@@ -59,7 +59,7 @@
-easter_friday(year)
+easter_friday(year)[source]

Easter Friday.

Parameters
@@ -76,7 +76,7 @@
-easter_monday(year)
+easter_monday(year)[source]

Easter Monday.

Parameters
@@ -93,7 +93,7 @@
-easter_sunday(year)
+easter_sunday(year)[source]

Easter Sunday.

Parameters
@@ -110,7 +110,7 @@
-gaußsche_osterformel(year)
+gaußsche_osterformel(year)[source]

Gaußsche Osterformel.

Parameters
@@ -144,7 +144,7 @@
-pentecost(year)
+pentecost(year)[source]

Pentecost.

Parameters
diff --git a/docs/build/html/fit.html b/docs/build/html/fit.html deleted file mode 100644 index e0b6e50..0000000 --- a/docs/build/html/fit.html +++ /dev/null @@ -1,173 +0,0 @@ - - - - - - - fit module — pylib 2019.5.19 documentation - - - - - - - - - - - - - - - - - - - - -
-
-
- - -
- -
-

fit module

-

Function and approximation.

-
-
-gauss(x, *p)
-

Gauss distribution function.

-
-\[f(x)=ae^{-(x-b)^{2}/(2c^{2})}\]
-
-
Parameters
-
    -
  • x (int or float or list or numpy.ndarray) – positions where the gauss function will be calculated

  • -
  • p (list) –

    gauss parameters [a, b, c, d]:

    -
      -
    • a – amplitude (\(\int y \,\mathrm{d}x=1 \Leftrightarrow a=1/(c\sqrt{2\pi})\) )

    • -
    • b – expected value \(\mu\) (position of maximum, default = 0)

    • -
    • c – standard deviation \(\sigma\) (variance \(\sigma^2=c^2\))

    • -
    • d – vertical offset (default = 0)

    • -
    -

  • -
-
-
Returns
-

gauss values at given positions x

-
-
Return type
-

numpy.ndarray

-
-
-
- -
-
-gauss_fit(x, y, e=None, x_fit=None, verbose=False)
-

Fit Gauss distribution function to data.

-
-
Parameters
-
    -
  • x (int or float or list or numpy.ndarray) – positions

  • -
  • y (int or float or list or numpy.ndarray) – values

  • -
  • e (int or float or list or numpy.ndarray) – error values (default = None)

  • -
  • x_fit (int or float or list or numpy.ndarray) – positions of fitted function (default = None, if None then x -is used)

  • -
  • verbose (bool) – verbose information (default = False)

  • -
-
-
Returns
-

    -
  • numpy.ndarray – fitted values (y_fit)

  • -
  • numpy.ndarray – parameters of gauss distribution function (popt: -amplitude a, expected value \(\mu\), standard deviation -\(\sigma\), vertical offset d)

  • -
  • numpy.float64 – full width at half maximum (FWHM)

  • -
-

-
-
Return type
-

tuple

-
-
-
-

See also

-

gauss()

-
-
- -
-
-main()
-

test function

-
- -
- - -
- -
-
- -
-
- - - - - - - \ No newline at end of file diff --git a/docs/build/html/genindex.html b/docs/build/html/genindex.html index 423ac4b..38c3bb8 100644 --- a/docs/build/html/genindex.html +++ b/docs/build/html/genindex.html @@ -47,6 +47,7 @@ | L | M | N + | O | P | R | S @@ -88,11 +89,13 @@ @@ -100,11 +103,11 @@

E

    @@ -120,7 +123,11 @@

    F

    +
    @@ -128,9 +135,9 @@

    G

      @@ -144,7 +151,13 @@

      I

      +
      @@ -161,22 +174,40 @@

      N

      +
      + +

      O

      + + +
      @@ -210,12 +241,6 @@

      S

      - @@ -225,6 +250,10 @@
      +
      diff --git a/docs/build/html/geometry.html b/docs/build/html/geometry.html index 0f3c4fa..08db166 100644 --- a/docs/build/html/geometry.html +++ b/docs/build/html/geometry.html @@ -42,7 +42,7 @@
      -cubic(point1, angle1, point2, angle2, samples=50)
      +cubic(point1, angle1, point2, angle2, samples=50)[source]
      Parameters
        @@ -65,7 +65,7 @@
        -cubic_deg(point1, angle1, point2, angle2)
        +cubic_deg(point1, angle1, point2, angle2)[source]
        Parameters
          @@ -91,7 +91,7 @@
          -line(point1, point2, samples=2)
          +line(point1, point2, samples=2)[source]
          \[y = \frac{y_2-y_1}{x_2-x_1}(x-x_1) + y_1\]
          @@ -115,7 +115,7 @@
          -points(*pts)
          +points(*pts)[source]
          Parameters

          *pts – points to rearrange

          @@ -131,7 +131,7 @@
          -rectangle(width, height)
          +rectangle(width, height)[source]
          Parameters
            @@ -150,7 +150,7 @@
            -rotate(origin, angle, *pts, **kwargs)
            +rotate(origin, angle, *pts, **kwargs)[source]

            Rotate a point or polygon counterclockwise by a given angle around a given origin. The angle should be given in radians.

            @@ -173,7 +173,7 @@ origin. The angle should be given in radians.

            -rotate_deg(origin, angle, *pts, **kwargs)
            +rotate_deg(origin, angle, *pts, **kwargs)[source]

            Rotate a point or polygon counterclockwise by a given angle around a given origin. The angle should be given in degrees.

            @@ -200,7 +200,7 @@ origin. The angle should be given in degrees.

            -square(width)
            +square(width)[source]
            Parameters

            width (int or float) – the edge size of the square

            @@ -220,7 +220,7 @@ origin. The angle should be given in degrees.

            -translate(vec, *pts)
            +translate(vec, *pts)[source]

            Translate a point or polygon by a given vector.

            Parameters
            diff --git a/docs/build/html/modules.html b/docs/build/html/modules.html index 1d347e6..eaf6ac7 100644 --- a/docs/build/html/modules.html +++ b/docs/build/html/modules.html @@ -38,10 +38,16 @@ diff --git a/docs/build/html/numerical.html b/docs/build/html/numerical.html new file mode 100644 index 0000000..8e5ce87 --- /dev/null +++ b/docs/build/html/numerical.html @@ -0,0 +1,586 @@ + + + + + + + numerical package — pylib 2019.5.19 documentation + + + + + + + + + + + + + + + + + + + + +
            +
            +
            + + +
            + +
            +

            numerical package

            +
            +

            Submodules

            +
            +
            +

            numerical.fit module

            +

            Function and approximation.

            +
            +
            +gauss(x, *p)[source]
            +

            Gauss distribution function.

            +
            +\[f(x)=ae^{-(x-b)^{2}/(2c^{2})}\]
            +
            +
            Parameters
            +
              +
            • x (int or float or list or numpy.ndarray) – positions where the gauss function will be calculated

            • +
            • p (list) –

              gauss parameters [a, b, c, d]:

              +
                +
              • a – amplitude (\(\int y \,\mathrm{d}x=1 \Leftrightarrow a=1/(c\sqrt{2\pi})\) )

              • +
              • b – expected value \(\mu\) (position of maximum, default = 0)

              • +
              • c – standard deviation \(\sigma\) (variance \(\sigma^2=c^2\))

              • +
              • d – vertical offset (default = 0)

              • +
              +

            • +
            +
            +
            Returns
            +

            gauss values at given positions x

            +
            +
            Return type
            +

            numpy.ndarray

            +
            +
            +
            + +
            +
            +gauss_fit(x, y, e=None, x_fit=None, verbose=False)[source]
            +

            Fit Gauss distribution function to data.

            +
            +
            Parameters
            +
              +
            • x (int or float or list or numpy.ndarray) – positions

            • +
            • y (int or float or list or numpy.ndarray) – values

            • +
            • e (int or float or list or numpy.ndarray) – error values (default = None)

            • +
            • x_fit (int or float or list or numpy.ndarray) – positions of fitted function (default = None, if None then x +is used)

            • +
            • verbose (bool) – verbose information (default = False)

            • +
            +
            +
            Returns
            +

              +
            • numpy.ndarray – fitted values (y_fit)

            • +
            • numpy.ndarray – parameters of gauss distribution function (popt: +amplitude a, expected value \(\mu\), standard deviation +\(\sigma\), vertical offset d)

            • +
            • numpy.float64 – full width at half maximum (FWHM)

            • +
            +

            +
            +
            Return type
            +

            tuple

            +
            +
            +
            +

            See also

            +

            gauss()

            +
            +
            + +
            +
            +

            numerical.integration module

            +

            Numerical integration, numerical quadrature.

            +

            de: numerische Integration, numerische Quadratur.

            +
            +
            Date
            +

            2015-10-15

            +
            +
            +
            +
            +trapez(f, a=0, b=1, N=10, x=None, verbose=False, save_values=False)[source]
            +

            Integration of \(f(x)\) using the trapezoidal rule +(Simpson’s rule, Kepler’s rule).

            +

            de: Trapezregel, Simpsonregel (Thomas Simpson), Keplersche +Fassregel (Johannes Kepler)

            +
            +
            Parameters
            +
              +
            • f (function or list) – function to integrate.

            • +
            • a (float) – lower limit of integration (default = 0).

            • +
            • b (float) – upper limit of integration (default = 1).

            • +
            • N (int) – specify the number of subintervals.

            • +
            • x (list) – variable of integration, necessary if f is a list +(default = None).

            • +
            • verbose (bool) – print information (default = False)

            • +
            +
            +
            Returns
            +

            the definite integral as approximated by trapezoidal +rule.

            +
            +
            Return type
            +

            float

            +
            +
            +

            The trapezoidal rule approximates the integral by the area of a +trapezoid with base h=b-a and sides equal to the values of the +integrand at the two end points.

            +
            +\[f_n(x) = f(a)+\frac{f(b)-f(a)}{b-a}(x-a)\]
            +
            +\[\begin{split}I &= \int\limits_a^b f(x) \,\mathrm{d}x \\ +I &\approx \int\limits_a^b f_n(x) \,\mathrm{d}x \\ + &= \int\limits_a^b + \left( f(a)+\frac{f(b)-f(a)}{b-a}(x-a) \right) + \mathrm{d}x \\ + &= \left.\left( f(a)-a\frac{f(b)-f(a)}{b-a} \right) + x \right\vert_a^b + + \left. \frac{f(b)-f(a)}{b-a} \frac{x^2}{2} + \right\vert_a^b \\ + &= \frac{b-a}{2}\left[f(a)+f(b)\right]\end{split}\]
            +

            The composite trapezium rule. If the interval is divided into n +segments (not necessarily equal)

            +
            +\[a = x_0 \leq x_1 \leq x_2 \leq \ldots \leq x_n = b\]
            +
            +\[\begin{split}I &\approx \sum\limits_{i=0}^{n-1} \frac{1}{2} (x_{i+1}-x_i) +\left[f(x_{i+1})+f(x_i)\right] \\\end{split}\]
            +

            Special Case (Equaliy spaced base points)

            +
            +\[x_{i+1}-x_i = h \quad \forall i\]
            +
            +\[I \approx h \left\{ \frac{1}{2} \left[f(x_0)+f(x_n)\right] + + \sum\limits_{i=1}^{n-1} f(x_i) \right\}\]
            +

            Example

            +
            +\[\begin{split}I &= \int\limits_a^b f(x) \,\mathrm{d}x \\ +f(x) &= x^2 \\ +a &= 0 \\ +b &= 1\end{split}\]
            +

            analytical solution

            +
            +\[I = \int\limits_{0}^{1} x^2 \,\mathrm{d}x + = \left. \frac{1}{3} x^3 \right\vert_0^1 + = \frac{1}{3}\]
            +

            numerical solution

            +
            >>> f = lambda(x): x**2
            +>>> trapez(f, 0, 1, 1)
            +0.5
            +>>> trapez(f, 0, 1, 10)
            +0.3350000000000001
            +>>> trapez(f, 0, 1, 100)
            +0.33335000000000004
            +
            +
            +
            + +
            +
            +

            numerical.ode module

            +

            Numerical solver of ordinary differential equations.

            +

            Solves the initial value problem for systems of first order ordinary differential +equations.

            +
            +
            Date
            +

            2015-09-21

            +
            +
            +
            +
            +dxdt_Dt(f, x, t, Dt, *p)[source]
            +
            +
            Parameters
            +
              +
            • f (function) – \(f = \dot{x}\)

            • +
            • Dt\(\Delta{t}\)

            • +
            +
            +
            Returns
            +

            \(\Delta x = \dot{x} \Delta t\)

            +
            +
            +
            + +
            +
            +e1(f, x0, t, *p, verbose=False)[source]
            +

            Explicit first-order method / +(standard, or forward) Euler method / +Runge-Kutta 1st order method.

            +

            de: +Euler’sche Polygonzugverfahren / explizite Euler-Verfahren / +Euler-Cauchy-Verfahren / Euler-vorwärts-Verfahren

            +
            +
            Parameters
            +
              +
            • f (function) – the function to solve

            • +
            • x0 (list) – initial condition

            • +
            • t (list) – time

            • +
            • *p – parameters of the function (thickness, diameter, …)

            • +
            • verbose (bool) – print information (default = False)

            • +
            +
            +
            +

            Approximate the solution of the initial value problem

            +
            +\[\begin{split}\dot{x} &= f(t,x) \\ +x(t_0) &= x_0\end{split}\]
            +

            Choose a value h for the size of every step and set

            +
            +\[t_i = t_0 + i h ~,\quad i=1,2,\ldots,n\]
            +

            The derivative of the solution is approximated as the forward difference +equation

            +
            +\[\dot{x}_i = f(t_i, x_i) = \frac{x_{i+1} - x_i}{t_{i+1}-t_i}\]
            +

            Therefore one step \(h\) of the Euler method from \(t_i\) to +\(t_{i+1}\) is

            +
            +\[\begin{split}x_{i+1} &= x_i + (t_{i+1}-t_i) f(t_i, x_i) \\ +x_{i+1} &= x_i + h f(t_i, x_i) \\\end{split}\]
            +

            Example 1:

            +
            +\[\begin{split}m\ddot{u} + d\dot{u} + ku = f(t) \\ +\ddot{u} = m^{-1}(f(t) - d\dot{u} - ku) \\\end{split}\]
            +

            with

            +
            +\[\begin{split}x_1 &= u &\quad \dot{x}_1 = \dot{u} = x_2 \\ +x_2 &= \dot{u} &\quad \dot{x}_2 = \ddot{u} \\\end{split}\]
            +

            becomes

            +
            +\[\begin{split}\dot{x}_1 &= x_2 \\ +\dot{x}_2 &= m^{-1}(f(t) - d x_2 - k x_1) \\\end{split}\]
            +

            or

            +
            +\[\begin{split}\dot{x} &= f(t,x) \\ +\begin{bmatrix} \dot{x}_1 \\ \dot{x}_2 \end{bmatrix} &= +\begin{bmatrix} x_2 \\ m^{-1}(f(t) - d x_2 - k x_1) \end{bmatrix} \\ +&= +\begin{bmatrix} 0 \\ m^{-1} f(t) \end{bmatrix} + +\begin{bmatrix} 0 & 1 \\ -m^{-1} k & -m^{-1} d \end{bmatrix} +\begin{bmatrix} x_1 \\ x_2 \end{bmatrix}\end{split}\]
            +

            Example 2:

            +
            +\[\begin{split}m(u)\ddot{u} + d(u,\dot{u})\dot{u} + k(u)u = f(t) \\ +\ddot{u} = m^{-1}(u)(f(t) - d(u,\dot{u})\dot{u} - k(u)u) \\\end{split}\]
            +

            with

            +
            +\[\begin{split}x_1 &= u &\quad \dot{x}_1 = \dot{u} = x_2 \\ +x_2 &= \dot{u} &\quad \dot{x}_2 = \ddot{u} \\\end{split}\]
            +

            becomes

            +
            +\[\begin{split}\dot{x}_1 &= x_2 \\ +\dot{x}_2 &= m^{-1}(x_1)(f(t) - d(x_1,x_2) x_2 - k(x_1) x_1) \\\end{split}\]
            +

            or

            +
            +\[\begin{split}\dot{x} &= f(t,x) \\ +\begin{bmatrix} \dot{x}_1 \\ \dot{x}_2 \end{bmatrix} &= +\begin{bmatrix} x_2 \\ m^{-1}(x_1)(f(t) - d(x_1,x_2) x_2 - k(x_1) x_1) \end{bmatrix} \\ +&= +\begin{bmatrix} 0 \\ m^{-1}(x_1) f(t) \end{bmatrix} + +\begin{bmatrix} 0 & 1 \\ -m^{-1}(x_1) k(x_1) & -m^{-1} d(x_1,x_2) \end{bmatrix} +\begin{bmatrix} x_1 \\ x_2 \end{bmatrix}\end{split}\]
            +

            The Euler method is a first-order method, +which means that the local error (error per step) is proportional to the +square of the step size, and the global error (error at a given time) is +proportional to the step size.

            +
            + +
            +
            +e2(f, x0, t, *p, verbose=False)[source]
            +

            Explicit second-order method / Runge-Kutta 2nd order method.

            +
            +
            Parameters
            +
              +
            • f (function) – the function to solve

            • +
            • x0 (list) – initial condition

            • +
            • t (list) – time

            • +
            • *p – parameters of the function (thickness, diameter, …)

            • +
            • verbose (bool) – print information (default = False)

            • +
            +
            +
            +
            + +
            +
            +e4(f, x0, t, *p, verbose=False)[source]
            +

            Explicit fourth-order method / Runge-Kutta 4th order method.

            +
            +
            Parameters
            +
              +
            • f (function) – the function to solve

            • +
            • x0 (list) – initial condition

            • +
            • t (list) – time

            • +
            • *p – parameters of the function (thickness, diameter, …)

            • +
            • verbose (bool) – print information (default = False)

            • +
            +
            +
            +
            + +
            +
            +fixed_point_iteration(f, xi, t, max_iterations=1000, tol=1e-09, verbose=False)[source]
            +
            +
            Parameters
            +
              +
            • f (function) – the function to iterate \(f = \Delta{x}(t)\)

            • +
            • xi (list) – initial condition \(x_i\)

            • +
            • t (float) – time \(t\)

            • +
            • *p – parameters of the function (thickness, diameter, …)

            • +
            • max_iterations (int) – maximum number of iterations

            • +
            • tol (float) – tolerance against residuum (default = 1e-9)

            • +
            • verbose (bool) – print information (default = False)

            • +
            +
            +
            Returns
            +

            \(x_{i+1}\)

            +
            +
            +
            +\[x_{i+1} = x_i + \Delta x\]
            +
            +

            See also

            +

            dxdt_Dt() for \(\Delta x\)

            +
            +
            + +
            +
            +i1(f, x0, t, *p, max_iterations=1000, tol=1e-09, verbose=False)[source]
            +

            Implicite first-order method / backward Euler method.

            +
            +
            Parameters
            +
              +
            • f (function) – the function to solve

            • +
            • x0 (list) – initial condition

            • +
            • t (list) – time

            • +
            • *p – parameters of the function (thickness, diameter, …)

            • +
            • max_iterations (int) – maximum number of iterations

            • +
            • tol (float) – tolerance against residuum (default = 1e-9)

            • +
            • verbose (bool) – print information (default = False)

            • +
            +
            +
            +

            The backward Euler method has order one and is A-stable.

            +
            + +
            +
            +i1n(f, x0, t, *p, max_iterations=1000, tol=1e-09, verbose=False)[source]
            +
            + +
            +
            +newmark_newtonraphson(f, x0, xp0, xpp0, t, *p, gamma=0.5, beta=0.25, max_iterations=1000, tol=1e-09, verbose=False)[source]
            +

            Newmark method.

            +
            +
            Parameters
            +
              +
            • f (function) – the function to solve

            • +
            • x0 (list) – initial condition

            • +
            • xp0 (list) – initial condition

            • +
            • xpp0 (list) – initial condition

            • +
            • t (list) – time

            • +
            • *p – parameters of the function (thickness, diameter, …)

            • +
            • gamma (float) – newmark parameter for velocity (default = 0.5)

            • +
            • beta (float) – newmark parameter for displacement (default = 0.25)

            • +
            • max_iterations (int) – maximum number of iterations

            • +
            • tol (float) – tolerance against residuum (default = 1e-9)

            • +
            • verbose (bool) – print information (default = False)

            • +
            +
            +
            +
            + +
            +
            +newmark_newtonraphson_rdk(fnm, x0, xp0, xpp0, t, *p, gamma=0.5, beta=0.25, maxIterations=1000, tol=1e-09, verbose=False)[source]
            +

            Newmark method.

            +
            +
            Parameters
            +
              +
            • f (function) – the function to solve

            • +
            • x0 (list) – initial condition

            • +
            • xp0 (list) – initial condition

            • +
            • xpp0 (list) – initial condition

            • +
            • t (list) – time

            • +
            • *p – parameters of the function (thickness, diameter, …)

            • +
            • gamma (float) – newmark parameter for velocity (default = 0.5)

            • +
            • beta (float) – newmark parameter for displacement (default = 0.25)

            • +
            • max_iterations (int) – maximum number of iterations

            • +
            • tol (float) – tolerance against residuum (default = 1e-9)

            • +
            • verbose (bool) – print information (default = False)

            • +
            +
            +
            +
            + +
            +
            +

            numerical.ode_model module

            +

            Mathmatical models governed by ordinary differential equations.

            +

            Describes initial value problems as systems of first order ordinary differential +equations.

            +
            +
            Date
            +

            2019-05-25

            +
            +
            +
            +
            +disk(x, t, *p)[source]
            +

            Rotation of an eccentric disk.

            +
            +
            Parameters
            +
              +
            • x (list) – values of the function

            • +
            • t (list) – time

            • +
            • *p

              parameters of the function

              +
                +
              • diameter

              • +
              • eccentricity

              • +
              • torque

              • +
              +

            • +
            +
            +
            +
            + +
            +
            +disk_nm(xn, xpn, xppn, t, *p)[source]
            +

            Rotation of an eccentric disk.

            +
            +
            Parameters
            +
              +
            • xn (list) – values of the function

            • +
            • xpn (list) – first derivative values of the function

            • +
            • xppn (list) – second derivative values of the function

            • +
            • t (list) – time

            • +
            • *p

              parameters of the function

              +
                +
              • diameter

              • +
              • eccentricity

              • +
              • torque

              • +
              +

            • +
            +
            +
            +
            + +
            +
            +disk_nmmdk(xn, xpn, xppn, t, *p)[source]
            +

            Rotation of an eccentric disk.

            +
            +
            Parameters
            +
              +
            • xn (list) – values of the function

            • +
            • xpn (list) – derivative values of the function

            • +
            • xppn (list) – second derivative values of the function

            • +
            • t (list) – time

            • +
            • *p

              parameters of the function

              +
                +
              • diameter

              • +
              • eccentricity

              • +
              • torque

              • +
              +

            • +
            +
            +
            +
            + +
            +
            +

            Module contents

            +
            +
            + + +
            + +
            +
            + +
            +
            + + + + + + + \ No newline at end of file diff --git a/docs/build/html/objects.inv b/docs/build/html/objects.inv index ab7137e..710740c 100644 --- a/docs/build/html/objects.inv +++ b/docs/build/html/objects.inv @@ -2,10 +2,6 @@ # Project: pylib # Version: # The remainder of this file is compressed using zlib. -xڥMr s -RVS++ Tʋ,)Zb~%$AxPA^CZyFӝbP@m -5H;Uȷ^ZCn2E:F[YͤF|73`0Pү.tCN -vƵ5[p ڨkӠz0xu ϋ2XX wa +[0X ޝM.|8H>-UK -%J{+ztjC -g*lm m3jV}Wr --x 3sPʼ~hh8њR'fL8)$gū*j? K;?A/ɾIJ_ {SMM'&#gNCjn&cṯ㗧x3/x*J~?>! ؠC#gBovfem&էt*Sj̳;tMܧϬ9wsL? \ No newline at end of file +xڭ0<h! 40CAQcGD# A&< ddH4}fL;mŬ&"e2uHZ*Dp/!LQQmV3inQpY d | f | g | - s + i | + n | + o @@ -69,7 +71,7 @@ - + + + + + + + + + + + + + + + + + + + + + + + + + + + ode_model(*nix, Windows)
            - fit (*nix, Windows) + fit (*nix, Windows) Function and approximation.
             
            @@ -80,18 +82,61 @@ geometry (*nix, Windows) Geometry objects.
             
            - s
            + i
            - solver (*nix, Windows) + integration (*nix, Windows) + Numerical integration.
             
            + n
            + numerical +
            + numerical +
                + numerical.fit +
                + numerical.integration +
                + numerical.ode +
                + numerical.ode_model +
             
            + o
            + ode (*nix, Windows) Numerical solver.
            - solver_model (*nix, Windows) - Mechanical models.
            + Models of ordinary differential equations.
            diff --git a/docs/build/html/searchindex.js b/docs/build/html/searchindex.js index 5c989c8..c9c5aa6 100644 --- a/docs/build/html/searchindex.js +++ b/docs/build/html/searchindex.js @@ -1 +1 @@ -Search.setIndex({docnames:["data","date","fit","geometry","index","modules","solver","solver_model"],envversion:{"sphinx.domains.c":1,"sphinx.domains.changeset":1,"sphinx.domains.cpp":1,"sphinx.domains.javascript":1,"sphinx.domains.math":2,"sphinx.domains.python":1,"sphinx.domains.rst":1,"sphinx.domains.std":1,sphinx:56},filenames:["data.rst","date.rst","fit.rst","geometry.rst","index.rst","modules.rst","solver.rst","solver_model.rst"],objects:{"":{data:[0,0,0,"-"],date:[1,0,0,"-"],fit:[2,0,0,"-"],geometry:[3,0,0,"-"],solver:[6,0,0,"-"],solver_model:[7,0,0,"-"]},data:{data_load:[0,1,1,""],data_read:[0,1,1,""],data_store:[0,1,1,""],main:[0,1,1,""]},date:{"gau\u00dfsche_osterformel":[1,1,1,""],ascension_of_jesus:[1,1,1,""],easter_friday:[1,1,1,""],easter_monday:[1,1,1,""],easter_sunday:[1,1,1,""],pentecost:[1,1,1,""]},fit:{gauss:[2,1,1,""],gauss_fit:[2,1,1,""],main:[2,1,1,""]},geometry:{cubic:[3,1,1,""],cubic_deg:[3,1,1,""],line:[3,1,1,""],points:[3,1,1,""],rectangle:[3,1,1,""],rotate:[3,1,1,""],rotate_deg:[3,1,1,""],square:[3,1,1,""],translate:[3,1,1,""]},solver:{e1:[6,1,1,""],e2:[6,1,1,""],e4:[6,1,1,""],i1:[6,1,1,""],newmark_newtonraphson:[6,1,1,""],newmark_newtonraphson_rdk:[6,1,1,""]},solver_model:{disk:[7,1,1,""],disk_nm:[7,1,1,""],disk_nmmdk:[7,1,1,""]}},objnames:{"0":["py","module","Python module"],"1":["py","function","Python function"]},objtypes:{"0":"py:module","1":"py:function"},terms:{"1st":6,"1th":[],"2nd":6,"4th":6,"9fsche_osterformel":1,"default":[0,2,6],"f\u00fcr":1,"float":[2,3,6],"fr\u00fchling":1,"function":[0,2,6,7],"gau\u00dfsch":1,"gau\u00dfsche_osterformel":1,"int":[0,1,2,3,6],"korrekturgr\u00f6\u00df":1,"m\u00e4rz":1,"m\u00e4rzdatum":1,"return":[0,1,2,3],"s\u00e4kular":1,"s\u00e4kularzahl":1,"vorw\u00e4rt":6,Das:1,One:6,The:[3,6],against:6,algorithmu:1,als:1,amplitud:2,angl:3,angle1:3,angle2:3,approxim:[2,6],april:1,around:3,ascens:1,ascension_of_jesu:1,ascii:0,backward:6,becom:6,begin:6,beta:6,binari:0,bmatrix:6,bool:[0,2,6],calcul:[1,2],cauchi:6,center:3,choos:6,column:0,condit:6,counterclockwis:3,cubic:3,cubic_deg:3,dai:1,data:[2,5],data_load:0,data_read:0,data_stor:0,date:[3,5,6,7],datetim:1,datum:1,ddot:6,degre:3,den:1,der:1,deriv:7,des:1,describ:7,deviat:2,diamet:[6,7],die:1,differenti:[6,7],disk:7,disk_nm:7,disk_nmmdk:7,displac:6,distribut:2,dot:6,easter:1,easter_fridai:1,easter_mondai:1,easter_sundai:1,eccentr:7,edg:3,end:[3,6],entfernung:1,equat:[6,7],error:[2,6],ersten:1,euler:6,everi:6,exampl:6,expect:2,explicit:6,explizit:6,fals:[0,2,6],file:0,file_nam:0,filenam:0,first:[0,6,7],fit:5,float64:2,fnm:6,forward:6,fourth:6,frac:3,fridai:1,from:[0,6],full:2,fwhm:2,gamma:6,gau:1,gauss:2,gauss_fit:2,geometri:5,gilt:1,given:[2,3,6],global:6,govern:7,gregorianischen:1,half:2,has:6,height:3,http:1,implicit:6,index:[0,4],inform:[0,2,6],initi:[6,7],iter:6,jahr:1,jesu:1,kalend:1,kalendarisch:1,keim:1,kutta:6,kwarg:3,ldot:6,leftrightarrow:2,line:3,list:[0,2,6,7],load:0,local:6,main:[0,2],march:1,mathmat:7,mathrm:2,max_iter:6,maximum:[2,6],maxiter:6,mean:6,mechan:[],method:6,model:7,modul:[4,5],mondai:1,mondparamet:1,mondschaltung:1,ndarrai:2,newmark:6,newmark_newtonraphson:6,newmark_newtonraphson_rdk:6,none:2,number:[3,6],numer:6,numpi:2,object:[0,3],object_data:0,ode1back:[],offset:2,one:[3,6],option:3,order:[6,7],ordinari:[6,7],org:1,origin:3,osterentfernung:1,osterformel:1,ostergrenz:1,ostersonntag:1,other:3,page:4,param:[],paramet:[0,1,2,3,6,7],pentecost:1,per:6,point1:3,point1_i:3,point1_x:3,point2:3,point2_i:3,point2_x:3,point3:3,point4:3,point:3,point_i:3,point_x:3,points1_i:3,polygon:3,polygonzugverfahren:6,popt:2,posit:2,print:6,printmessg:[],problem:[6,7],program:0,proport:6,pts:3,quad:6,radian:3,read:0,rearrang:3,rectangl:3,residuum:6,rk2:[],rk4:[],rotat:[3,7],rotate_deg:3,rung:6,sampl:3,sample_point1_x:3,sample_point2_i:3,sample_point2_x:3,sample_points1_i:3,sche:6,search:4,second:[6,7],set:6,should:3,sigma:2,size:[3,6],slope:3,solut:6,solv:6,solver:5,solver_model:5,sonnenschaltung:1,sonntag:1,sourc:1,spacial:1,sqrt:2,squar:[3,6],stabl:6,standard:[2,6],step:6,store:0,str:0,sundai:1,system:[6,7],t_0:6,t_i:6,tagen:1,test:2,thick:6,time:[6,7],tol:6,toler:6,torqu:7,translat:3,tupl:[0,2,3],type:[0,1,2,3],used:2,usw:1,valu:[2,6,7],variabl:1,varianc:2,vec:3,vector:3,veloc:6,verbos:[0,2,6],verfahren:6,vertic:2,vollmond:1,von:1,where:2,which:6,width:[2,3],wiki:1,wikipedia:1,write:0,x_0:6,x_1:[3,6],x_2:[3,6],x_column:0,x_fit:2,x_i:6,xp0:6,xpn:7,xpp0:6,xppn:7,y_1:3,y_2:3,y_column:0,y_fit:2,year:1},titles:["data module","date module","fit module","geometry module","Welcome to pylib\u2019s documentation!","src","solver module","solver_model module"],titleterms:{data:0,date:1,document:4,fit:2,geometri:3,indic:4,modul:[0,1,2,3,6,7],pylib:4,solver:6,solver_model:7,src:5,tabl:4,welcom:4}}) \ No newline at end of file +Search.setIndex({docnames:["data","date","geometry","index","modules","numerical"],envversion:{"sphinx.domains.c":1,"sphinx.domains.changeset":1,"sphinx.domains.cpp":1,"sphinx.domains.javascript":1,"sphinx.domains.math":2,"sphinx.domains.python":1,"sphinx.domains.rst":1,"sphinx.domains.std":1,"sphinx.ext.viewcode":1,sphinx:56},filenames:["data.rst","date.rst","geometry.rst","index.rst","modules.rst","numerical.rst"],objects:{"":{data:[0,0,0,"-"],date:[1,0,0,"-"],fit:[5,0,0,"-"],geometry:[2,0,0,"-"],integration:[5,0,0,"-"],numerical:[5,0,0,"-"],ode:[5,0,0,"-"],ode_model:[5,0,0,"-"]},"numerical.fit":{gauss:[5,1,1,""],gauss_fit:[5,1,1,""]},"numerical.integration":{trapez:[5,1,1,""]},"numerical.ode":{dxdt_Dt:[5,1,1,""],e1:[5,1,1,""],e2:[5,1,1,""],e4:[5,1,1,""],fixed_point_iteration:[5,1,1,""],i1:[5,1,1,""],i1n:[5,1,1,""],newmark_newtonraphson:[5,1,1,""],newmark_newtonraphson_rdk:[5,1,1,""]},"numerical.ode_model":{disk:[5,1,1,""],disk_nm:[5,1,1,""],disk_nmmdk:[5,1,1,""]},data:{data_load:[0,1,1,""],data_read:[0,1,1,""],data_store:[0,1,1,""],main:[0,1,1,""]},date:{"gau\u00dfsche_osterformel":[1,1,1,""],ascension_of_jesus:[1,1,1,""],easter_friday:[1,1,1,""],easter_monday:[1,1,1,""],easter_sunday:[1,1,1,""],pentecost:[1,1,1,""]},geometry:{cubic:[2,1,1,""],cubic_deg:[2,1,1,""],line:[2,1,1,""],points:[2,1,1,""],rectangle:[2,1,1,""],rotate:[2,1,1,""],rotate_deg:[2,1,1,""],square:[2,1,1,""],translate:[2,1,1,""]},numerical:{fit:[5,0,0,"-"],integration:[5,0,0,"-"],ode:[5,0,0,"-"],ode_model:[5,0,0,"-"]}},objnames:{"0":["py","module","Python module"],"1":["py","function","Python function"]},objtypes:{"0":"py:module","1":"py:function"},terms:{"1st":5,"2nd":5,"4th":5,"9fsche_osterformel":1,"case":5,"default":[0,5],"f\u00fcr":1,"float":[2,5],"fr\u00fchling":1,"function":[0,5],"gau\u00dfsch":1,"gau\u00dfsche_osterformel":1,"int":[0,1,2,5],"korrekturgr\u00f6\u00df":1,"m\u00e4rz":1,"m\u00e4rzdatum":1,"return":[0,1,2,5],"s\u00e4kular":1,"s\u00e4kularzahl":1,"vorw\u00e4rt":5,Das:1,The:[2,5],against:5,algorithmu:1,als:1,amplitud:5,analyt:5,angl:2,angle1:2,angle2:2,approx:5,approxim:5,april:1,area:5,around:2,ascens:1,ascension_of_jesu:1,ascii:0,backward:5,base:5,becom:5,begin:5,beta:5,binari:0,bmatrix:5,bool:[0,5],calcul:[1,5],cauchi:5,center:2,choos:5,column:0,composit:5,condit:5,content:4,counterclockwis:2,cubic:2,cubic_deg:2,dai:1,data:[4,5],data_load:0,data_read:0,data_stor:0,date:[2,4,5],datetim:1,datum:1,ddot:5,definit:5,degre:2,delta:5,den:1,der:1,deriv:5,des:1,describ:5,deviat:5,diamet:5,die:1,differ:5,differenti:5,disk:5,disk_nm:5,disk_nmmdk:5,displac:5,distribut:5,divid:5,dot:5,dxdt_dt:5,easter:1,easter_fridai:1,easter_mondai:1,easter_sundai:1,eccentr:5,edg:2,end:[2,5],entfernung:1,equal:5,equalii:5,equat:5,error:5,ersten:1,euler:5,everi:5,exampl:5,expect:5,explicit:5,explizit:5,f_n:5,fals:[0,5],fassregel:5,file:0,file_nam:0,filenam:0,first:[0,5],fit:4,fixed_point_iter:5,float64:5,fnm:5,foral:5,forward:5,fourth:5,frac:[2,5],fridai:1,from:[0,5],full:5,fwhm:5,gamma:5,gau:1,gauss:5,gauss_fit:5,geometri:4,gilt:1,given:[2,5],global:5,govern:5,gregorianischen:1,half:5,has:5,height:2,http:1,i1n:5,implicit:5,index:[0,3],inform:[0,5],initi:5,integr:4,integrand:5,interv:5,iter:5,jahr:1,jesu:1,johann:5,kalend:1,kalendarisch:1,keim:1,kepler:5,keplersch:5,kutta:5,kwarg:2,lambda:5,ldot:5,left:5,leftrightarrow:5,leq:5,limit:5,limits_:5,limits_a:5,line:2,list:[0,5],load:0,local:5,lower:5,main:0,march:1,mathmat:5,mathrm:5,max_iter:5,maximum:5,maxiter:5,mean:5,method:5,model:5,modul:[3,4],mondai:1,mondparamet:1,mondschaltung:1,ndarrai:5,necessari:5,necessarili:5,newmark:5,newmark_newtonraphson:5,newmark_newtonraphson_rdk:5,none:5,number:[2,5],numer:4,numerisch:5,numpi:5,object:[0,2],object_data:0,ode:4,ode_model:4,offset:5,one:[2,5],option:2,order:5,ordinari:5,org:1,origin:2,osterentfernung:1,osterformel:1,ostergrenz:1,ostersonntag:1,other:2,packag:4,page:3,paramet:[0,1,2,5],pentecost:1,per:5,point1:2,point1_i:2,point1_x:2,point2:2,point2_i:2,point2_x:2,point3:2,point4:2,point:[2,5],point_i:2,point_x:2,points1_i:2,polygon:2,polygonzugverfahren:5,popt:5,posit:5,print:5,problem:5,program:0,proport:5,pts:2,quad:5,quadratur:5,radian:2,read:0,rearrang:2,rectangl:2,residuum:5,right:5,rotat:[2,5],rotate_deg:2,rule:5,rung:5,sampl:2,sample_point1_x:2,sample_point2_i:2,sample_point2_x:2,sample_points1_i:2,save_valu:5,sche:5,search:3,second:5,segment:5,set:5,should:2,side:5,sigma:5,simpson:5,simpsonregel:5,size:[2,5],slope:2,solut:5,solv:5,solver:5,sonnenschaltung:1,sonntag:1,sourc:[0,1,2,5],space:5,spacial:1,special:5,specifi:5,sqrt:5,squar:[2,5],stabl:5,standard:5,step:5,store:0,str:0,subinterv:5,submodul:4,sum:5,sundai:1,system:5,t_0:5,t_i:5,tagen:1,therefor:5,thick:5,thoma:5,time:5,tol:5,toler:5,torqu:5,translat:2,trapez:5,trapezium:5,trapezoid:5,trapezregel:5,tupl:[0,2,5],two:5,type:[0,1,2,5],upper:5,used:5,using:5,usw:1,valu:5,variabl:[1,5],varianc:5,vec:2,vector:2,veloc:5,verbos:[0,5],verfahren:5,vert_0:5,vert_a:5,vertic:5,vollmond:1,von:1,where:5,which:5,width:[2,5],wiki:1,wikipedia:1,write:0,x_0:5,x_1:[2,5],x_2:[2,5],x_column:0,x_fit:5,x_i:5,x_n:5,xp0:5,xpn:5,xpp0:5,xppn:5,y_1:2,y_2:2,y_column:0,y_fit:5,year:1},titles:["data module","date module","geometry module","Welcome to pylib\u2019s documentation!","src","numerical package"],titleterms:{content:5,data:0,date:1,document:3,fit:5,geometri:2,indic:3,integr:5,modul:[0,1,2,5],numer:5,ode:5,ode_model:5,packag:5,pylib:3,src:4,submodul:5,tabl:3,welcom:3}}) \ No newline at end of file diff --git a/docs/build/html/solver.html b/docs/build/html/solver.html deleted file mode 100644 index 8ef563e..0000000 --- a/docs/build/html/solver.html +++ /dev/null @@ -1,289 +0,0 @@ - - - - - - - solver module — pylib 2019.5.19 documentation - - - - - - - - - - - - - - - - - - - - -
            -
            -
            - - -
            - -
            -

            solver module

            -

            Numerical solver of ordinary differential equations.

            -

            Solves the initial value problem for systems of first order ordinary differential -equations.

            -
            -
            Date
            -

            2015-09-21

            -
            -
            -
            -
            -e1(f, x0, t, *p, verbose=False)
            -

            Explicit first-order method / -(standard, or forward) Euler method / -Runge-Kutta 1st order method.

            -

            de: -Euler’sche Polygonzugverfahren / explizite Euler-Verfahren / -Euler-Cauchy-Verfahren / Euler-vorwärts-Verfahren

            -
            -
            Parameters
            -
              -
            • f (function) – the function to solve

            • -
            • x0 (list) – initial condition

            • -
            • t (list) – time

            • -
            • *p – parameters of the function (thickness, diameter, …)

            • -
            • verbose (bool) – print information (default = False)

            • -
            -
            -
            -

            Approximate the solution of the initial value problem

            -
            -\[\begin{split}\dot{x} &= f(t,x) \\ -x(t_0) &= x_0\end{split}\]
            -

            Choose a value h for the size of every step and set

            -
            -\[t_i = t_0 + i h ~,\quad i=1,2,\ldots,n\]
            -

            One step \(h\) of the Euler method from \(t_i\) to \(t_{i+1}\) is

            -
            -\[\begin{split}x_{i+1} &= x_i + (t_{i+1}-t_i) f(t_i, x_i) \\ -x_{i+1} &= x_i + h f(t_i, x_i) \\\end{split}\]
            -

            Example 1:

            -
            -\[\begin{split}m\ddot{u} + d\dot{u} + ku = f(t) \\ -\ddot{u} = m^{-1}(f(t) - d\dot{u} - ku) \\\end{split}\]
            -

            with

            -
            -\[\begin{split}x_1 &= u &\quad \dot{x}_1 = \dot{u} = x_2 \\ -x_2 &= \dot{u} &\quad \dot{x}_2 = \ddot{u} \\\end{split}\]
            -

            becomes

            -
            -\[\begin{split}\dot{x}_1 &= x_2 \\ -\dot{x}_2 &= m^{-1}(f(t) - d x_2 - k x_1) \\\end{split}\]
            -

            or

            -
            -\[\begin{split}\dot{x} &= f(t,x) \\ -\begin{bmatrix} \dot{x}_1 \\ \dot{x}_1 \end{bmatrix} &= -\begin{bmatrix} x_2 \\ m^{-1}(f(t) - d x_2 - k x_1) \end{bmatrix} \\ -&= -\begin{bmatrix} 0 \\ m^{-1} f(t) \end{bmatrix} + -\begin{bmatrix} 0 & 1 \\ -m^{-1} k & -m^{-1} d \end{bmatrix} -\begin{bmatrix} x_1 \\ x_2 \end{bmatrix}\end{split}\]
            -

            Example 2:

            -
            -\[\begin{split}m(u)\ddot{u} + d(u,\dot{u})\dot{u} + k(u)u = f(t) \\ -\ddot{u} = m^{-1}(u)(f(t) - d(u,\dot{u})\dot{u} - k(u)u) \\\end{split}\]
            -

            with

            -
            -\[\begin{split}x_1 &= u &\quad \dot{x}_1 = \dot{u} = x_2 \\ -x_2 &= \dot{u} &\quad \dot{x}_2 = \ddot{u} \\\end{split}\]
            -

            becomes

            -
            -\[\begin{split}\dot{x}_1 &= x_2 \\ -\dot{x}_2 &= m^{-1}(x_1)(f(t) - d(x_1,x_2) x_2 - k(x_1) x_1) \\\end{split}\]
            -

            or

            -
            -\[\begin{split}\dot{x} &= f(t,x) \\ -\begin{bmatrix} \dot{x}_1 \\ \dot{x}_2 \end{bmatrix} &= -\begin{bmatrix} x_2 \\ m^{-1}(x_1)(f(t) - d(x_1,x_2) x_2 - k(x_1) x_1) \end{bmatrix} \\ -&= -\begin{bmatrix} 0 \\ m^{-1}(x_1) f(t) \end{bmatrix} + -\begin{bmatrix} 0 & 1 \\ -m^{-1}(x_1) k(x_1) & -m^{-1} d(x_1,x_2) \end{bmatrix} -\begin{bmatrix} x_1 \\ x_2 \end{bmatrix}\end{split}\]
            -

            The Euler method is a first-order method, -which means that the local error (error per step) is proportional to the -square of the step size, and the global error (error at a given time) is -proportional to the step size.

            -
            - -
            -
            -e2(f, x0, t, *p, verbose=False)
            -

            Explicit second-order method / Runge-Kutta 2nd order method.

            -
            -
            Parameters
            -
              -
            • f (function) – the function to solve

            • -
            • x0 (list) – initial condition

            • -
            • t (list) – time

            • -
            • *p – parameters of the function (thickness, diameter, …)

            • -
            • verbose (bool) – print information (default = False)

            • -
            -
            -
            -
            - -
            -
            -e4(f, x0, t, *p, verbose=False)
            -

            Explicit fourth-order method / Runge-Kutta 4th order method.

            -
            -
            Parameters
            -
              -
            • f (function) – the function to solve

            • -
            • x0 (list) – initial condition

            • -
            • t (list) – time

            • -
            • *p – parameters of the function (thickness, diameter, …)

            • -
            • verbose (bool) – print information (default = False)

            • -
            -
            -
            -
            - -
            -
            -i1(f, x0, t, *p, max_iterations=1000, tol=1e-09, verbose=False)
            -

            Implicite first-order method / backward Euler method.

            -
            -
            Parameters
            -
              -
            • f (function) – the function to solve

            • -
            • x0 (list) – initial condition

            • -
            • t (list) – time

            • -
            • *p – parameters of the function (thickness, diameter, …)

            • -
            • max_iterations (int) – maximum number of iterations

            • -
            • tol (float) – tolerance against residuum (default = 1e-9)

            • -
            • verbose (bool) – print information (default = False)

            • -
            -
            -
            -

            The backward Euler method has order one and is A-stable.

            -
            - -
            -
            -newmark_newtonraphson(f, x0, xp0, xpp0, t, *p, gamma=0.5, beta=0.25, max_iterations=1000, tol=1e-09, verbose=False)
            -

            Newmark method.

            -
            -
            Parameters
            -
              -
            • f (function) – the function to solve

            • -
            • x0 (list) – initial condition

            • -
            • xp0 (list) – initial condition

            • -
            • xpp0 (list) – initial condition

            • -
            • t (list) – time

            • -
            • *p – parameters of the function (thickness, diameter, …)

            • -
            • gamma (float) – newmark parameter for velocity (default = 0.5)

            • -
            • beta (float) – newmark parameter for displacement (default = 0.25)

            • -
            • max_iterations (int) – maximum number of iterations

            • -
            • tol (float) – tolerance against residuum (default = 1e-9)

            • -
            • verbose (bool) – print information (default = False)

            • -
            -
            -
            -
            - -
            -
            -newmark_newtonraphson_rdk(fnm, x0, xp0, xpp0, t, *p, gamma=0.5, beta=0.25, maxIterations=1000, tol=1e-09, verbose=False)
            -

            Newmark method.

            -
            -
            Parameters
            -
              -
            • f (function) – the function to solve

            • -
            • x0 (list) – initial condition

            • -
            • xp0 (list) – initial condition

            • -
            • xpp0 (list) – initial condition

            • -
            • t (list) – time

            • -
            • *p – parameters of the function (thickness, diameter, …)

            • -
            • gamma (float) – newmark parameter for velocity (default = 0.5)

            • -
            • beta (float) – newmark parameter for displacement (default = 0.25)

            • -
            • max_iterations (int) – maximum number of iterations

            • -
            • tol (float) – tolerance against residuum (default = 1e-9)

            • -
            • verbose (bool) – print information (default = False)

            • -
            -
            -
            -
            - -
            - - -
            - -
            -
            - -
            -
            - - - - - - - \ No newline at end of file diff --git a/docs/build/html/solver_model.html b/docs/build/html/solver_model.html deleted file mode 100644 index 597c46c..0000000 --- a/docs/build/html/solver_model.html +++ /dev/null @@ -1,177 +0,0 @@ - - - - - - - solver_model module — pylib 2019.5.19 documentation - - - - - - - - - - - - - - - - - - - - -
            -
            -
            - - -
            - -
            -

            solver_model module

            -

            Mathmatical models governed by ordinary differential equations.

            -

            Describes initial value problems as systems of first order ordinary differential -equations.

            -
            -
            Date
            -

            2019-05-25

            -
            -
            -
            -
            -disk(x, t, *p)
            -

            Rotation of an eccentric disk.

            -
            -
            Parameters
            -
              -
            • x (list) – values of the function

            • -
            • t (list) – time

            • -
            • *p

              parameters of the function

              -
                -
              • diameter

              • -
              • eccentricity

              • -
              • torque

              • -
              -

            • -
            -
            -
            -
            - -
            -
            -disk_nm(xn, xpn, xppn, t, *p)
            -

            Rotation of an eccentric disk.

            -
            -
            Parameters
            -
              -
            • xn (list) – values of the function

            • -
            • xpn (list) – first derivative values of the function

            • -
            • xppn (list) – second derivative values of the function

            • -
            • t (list) – time

            • -
            • *p

              parameters of the function

              -
                -
              • diameter

              • -
              • eccentricity

              • -
              • torque

              • -
              -

            • -
            -
            -
            -
            - -
            -
            -disk_nmmdk(xn, xpn, xppn, t, *p)
            -

            Rotation of an eccentric disk.

            -
            -
            Parameters
            -
              -
            • xn (list) – values of the function

            • -
            • xpn (list) – derivative values of the function

            • -
            • xppn (list) – second derivative values of the function

            • -
            • t (list) – time

            • -
            • *p

              parameters of the function

              -
                -
              • diameter

              • -
              • eccentricity

              • -
              • torque

              • -
              -

            • -
            -
            -
            -
            - -
            - - -
            - -
            -
            - -
            -
            - - - - - - - \ No newline at end of file diff --git a/docs/source/_static/custom.css b/docs/source/_static/custom.css index d60ea94..b6a5152 100644 --- a/docs/source/_static/custom.css +++ b/docs/source/_static/custom.css @@ -5,3 +5,9 @@ table.indextable tr.cap { background-color: #333; } +/* move doc link a bit up */ +.viewcode-back { + float: right; + position: relative; + top: -1.5em; +} diff --git a/docs/source/conf.py b/docs/source/conf.py index 75aecc0..99b7f99 100644 --- a/docs/source/conf.py +++ b/docs/source/conf.py @@ -34,7 +34,8 @@ release = '2019.5.19' # extensions coming with Sphinx (named 'sphinx.ext.*') or your custom # ones. extensions = [ - 'sphinx.ext.autodoc' + 'sphinx.ext.autodoc', + 'sphinx.ext.viewcode', ] # Add any paths that contain templates here, relative to this directory. @@ -52,6 +53,7 @@ exclude_patterns = [] # a list of builtin themes. # html_theme = 'alabaster' +pygments_style = 'solarized-dark' # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, @@ -66,6 +68,8 @@ html_theme_options = { 'base_bg': '#292b2e', 'base_text': '#b2b2b2', 'body_text': '#b2b2b2', + 'viewcode_target_bg': '#292b2e', + 'pre_bg': '#25272c', 'code_text': '#b2b2b2', 'code_hover': 'transparent', 'sidebar_text': '#b2b2b2', @@ -76,6 +80,6 @@ html_theme_options = { 'highlight_bg': '#444F65', 'xref_bg': 'transparent', 'xref_border': 'transparent', - 'seealso_bg': '#3c3c3c', + 'seealso_bg': '#25272c', 'seealso_border': '#2C2C2C', } diff --git a/docs/source/fit.rst b/docs/source/fit.rst deleted file mode 100644 index 21a5d59..0000000 --- a/docs/source/fit.rst +++ /dev/null @@ -1,7 +0,0 @@ -fit module -========== - -.. automodule:: fit - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/source/modules.rst b/docs/source/modules.rst index 6a908e5..4679bea 100644 --- a/docs/source/modules.rst +++ b/docs/source/modules.rst @@ -6,7 +6,5 @@ src data date - fit geometry - solver - solver_model + numerical diff --git a/docs/source/numerical.rst b/docs/source/numerical.rst new file mode 100644 index 0000000..e37c893 --- /dev/null +++ b/docs/source/numerical.rst @@ -0,0 +1,46 @@ +numerical package +================= + +Submodules +---------- + +numerical.fit module +-------------------- + +.. automodule:: numerical.fit + :members: + :undoc-members: + :show-inheritance: + +numerical.integration module +---------------------------- + +.. automodule:: numerical.integration + :members: + :undoc-members: + :show-inheritance: + +numerical.ode module +-------------------- + +.. automodule:: numerical.ode + :members: + :undoc-members: + :show-inheritance: + +numerical.ode\_model module +--------------------------- + +.. automodule:: numerical.ode_model + :members: + :undoc-members: + :show-inheritance: + + +Module contents +--------------- + +.. automodule:: numerical + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/source/solver.rst b/docs/source/solver.rst deleted file mode 100644 index 0d6d757..0000000 --- a/docs/source/solver.rst +++ /dev/null @@ -1,7 +0,0 @@ -solver module -============= - -.. automodule:: solver - :members: - :undoc-members: - :show-inheritance: diff --git a/docs/source/solver_model.rst b/docs/source/solver_model.rst deleted file mode 100644 index bc08685..0000000 --- a/docs/source/solver_model.rst +++ /dev/null @@ -1,7 +0,0 @@ -solver\_model module -==================== - -.. automodule:: solver_model - :members: - :undoc-members: - :show-inheritance: diff --git a/src/data.py b/src/data.py index 1c712d9..da4c15e 100644 --- a/src/data.py +++ b/src/data.py @@ -33,6 +33,7 @@ def data_read(file_name, x_column, y_column): #print(filds) x.append(float(fields[x_column])) y.append(float(fields[y_column])) + file.close() return x, y def data_load(file_name, verbose=False): diff --git a/src/numerical/__init__.py b/src/numerical/__init__.py new file mode 100644 index 0000000..e69de29 diff --git a/src/fit.py b/src/numerical/fit.py similarity index 76% rename from src/fit.py rename to src/numerical/fit.py index 781dc5d..40304d7 100644 --- a/src/fit.py +++ b/src/numerical/fit.py @@ -9,9 +9,8 @@ .. moduleauthor:: Daniel Weschke """ from __future__ import print_function -from pylab import array, argmax, subplot, plot, title, xlim, show, gradient, exp, sqrt, log, linspace +from pylab import array, argmax, gradient, exp, sqrt, log, linspace from scipy.optimize import curve_fit -from data import * def gauss(x, *p): """Gauss distribution function. @@ -92,33 +91,5 @@ def gauss_fit(x, y, e=None, x_fit=None, verbose=False): return y_fit, popt, FWHM -def main(): - """test function""" - file_name = "../tests/test_fit.dat" - x, y = data_read(file_name, 3, 2) - - subplot(2,2,1) - plot(x, y, '.-') - - subplot(2,2,2) - dx = x[1] - x[0] - dydx = gradient(y, dx) # central differences - x_fit = linspace(x[0], x[-1], 150 if len(x) < 50 else len(x)*3) - y_fit, popt, FWHM = gauss_fit(list(reversed(x)), list(reversed(dydx)), x_fit=x_fit, verbose=True) # x must increase! - plot(x, dydx, '.-') - plot(x_fit, y_fit, 'r:') - title('FWHM: %f' % FWHM) - - subplot(2,2,3) - plot(x, y, '.-') - xlim(popt[1]-2*FWHM, popt[1]+2*FWHM) - - subplot(2,2,4) - plot(x, dydx, '.-') - plot(x_fit, y_fit, 'r:') - xlim(popt[1]-2*FWHM, popt[1]+2*FWHM) - - show() - if __name__ == "__main__": - main() + True diff --git a/src/numerical/integration.py b/src/numerical/integration.py new file mode 100644 index 0000000..b7a768a --- /dev/null +++ b/src/numerical/integration.py @@ -0,0 +1,151 @@ +# -*- coding: utf-8 -*- +"""Numerical integration, numerical quadrature. + +de: numerische Integration, numerische Quadratur. + +:Date: 2015-10-15 + +.. module:: integration + :platform: *nix, Windows + :synopsis: Numerical integration. + +.. moduleauthor:: Daniel Weschke +""" + +from __future__ import division +from numpy import linspace, trapz, zeros + +def trapez(f, a=0, b=1, N=10, x=None, verbose=False, + save_values=False): + r""" + Integration of :math:`f(x)` using the trapezoidal rule + (Simpson's rule, Kepler's rule). + + de: Trapezregel, Simpsonregel (Thomas Simpson), Keplersche + Fassregel (Johannes Kepler) + + :param f: function to integrate. + :type f: function or list + :param a: lower limit of integration (default = 0). + :type a: float + :param b: upper limit of integration (default = 1). + :type b: float + :param N: specify the number of subintervals. + :type N: int + :param x: variable of integration, necessary if f is a list + (default = None). + :type x: list + :param verbose: print information (default = False) + :type verbose: bool + + :returns: the definite integral as approximated by trapezoidal + rule. + :rtype: float + + The trapezoidal rule approximates the integral by the area of a + trapezoid with base h=b-a and sides equal to the values of the + integrand at the two end points. + + .. math:: + f_n(x) = f(a)+\frac{f(b)-f(a)}{b-a}(x-a) + + .. math:: + I &= \int\limits_a^b f(x) \,\mathrm{d}x \\ + I &\approx \int\limits_a^b f_n(x) \,\mathrm{d}x \\ + &= \int\limits_a^b + \left( f(a)+\frac{f(b)-f(a)}{b-a}(x-a) \right) + \mathrm{d}x \\ + &= \left.\left( f(a)-a\frac{f(b)-f(a)}{b-a} \right) + x \right\vert_a^b + + \left. \frac{f(b)-f(a)}{b-a} \frac{x^2}{2} + \right\vert_a^b \\ + &= \frac{b-a}{2}\left[f(a)+f(b)\right] + + The composite trapezium rule. If the interval is divided into n + segments (not necessarily equal) + + .. math:: + a = x_0 \leq x_1 \leq x_2 \leq \ldots \leq x_n = b + + .. math:: + I &\approx \sum\limits_{i=0}^{n-1} \frac{1}{2} (x_{i+1}-x_i) + \left[f(x_{i+1})+f(x_i)\right] \\ + + Special Case (Equaliy spaced base points) + + .. math:: + x_{i+1}-x_i = h \quad \forall i + + .. math:: + I \approx h \left\{ \frac{1}{2} \left[f(x_0)+f(x_n)\right] + + \sum\limits_{i=1}^{n-1} f(x_i) \right\} + + .. rubric:: Example + + .. math:: + I &= \int\limits_a^b f(x) \,\mathrm{d}x \\ + f(x) &= x^2 \\ + a &= 0 \\ + b &= 1 + + analytical solution + + .. math:: + I = \int\limits_{0}^{1} x^2 \,\mathrm{d}x + = \left. \frac{1}{3} x^3 \right\vert_0^1 + = \frac{1}{3} + + numerical solution + + >>> f = lambda(x): x**2 + >>> trapez(f, 0, 1, 1) + 0.5 + >>> trapez(f, 0, 1, 10) + 0.3350000000000001 + >>> trapez(f, 0, 1, 100) + 0.33335000000000004 + """ + N = int(N) + # f is function or list + if hasattr(f, '__call__'): + # h width of each subinterval + h = (b-a)/N + + # x variable of integration + x = linspace(a, b, N+1) + if save_values: + # ff contribution from the points + ff = zeros((N+1)) + for n in linspace(0, N, N+1): + ff[n] = f(x[n]) + T = (ff[0]/2.+sum(ff[1:N])+ff[N]/2.)*h + else: + TL = f(x[0]) + TR = f(x[N]) + TI = 0 + for n in range(1, N): + TI = TI + f(x[n]) + T = (TL/2.+TI+TR/2.)*h + else: + N = len(f)-1 + T = 0 + for n in range(N): + T = T + (x[n+1]-x[n])/2*(f[n+1]+f[n]) + + if verbose: + print(T) + + return T + + +if __name__ == '__main__': + func = lambda x: x**2 + trapez(func, 0, 1, 1e6, verbose=True) + #print(trapz(func, linspace(0,1,10))) + + trapez([0,1,4,9], x=[0,1,2,3], verbose=True) + #print(trapz([0,1,4,9])) + + trapez([2,2], x=[-1,1], verbose=True) + + trapez([-1,1,1,-1], x=[-1,-1,1,1], verbose=True) diff --git a/src/solver.py b/src/numerical/ode.py similarity index 69% rename from src/solver.py rename to src/numerical/ode.py index 0e5fc10..44a0caf 100644 --- a/src/solver.py +++ b/src/numerical/ode.py @@ -1,357 +1,424 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -"""Numerical solver of ordinary differential equations. - -Solves the initial value problem for systems of first order ordinary differential -equations. - -:Date: 2015-09-21 - -.. module:: solver - :platform: *nix, Windows - :synopsis: Numerical solver. - -.. moduleauthor:: Daniel Weschke -""" - -from __future__ import division, print_function -from numpy import array, isnan, sum, zeros, dot -from numpy.linalg import norm, inv - -def e1(f, x0, t, *p, verbose=False): - r"""Explicit first-order method / - (standard, or forward) Euler method / - Runge-Kutta 1st order method. - - de: - Euler'sche Polygonzugverfahren / explizite Euler-Verfahren / - Euler-Cauchy-Verfahren / Euler-vorwärts-Verfahren - - :param f: the function to solve - :type f: function - :param x0: initial condition - :type x0: list - :param t: time - :type t: list - :param `*p`: parameters of the function (thickness, diameter, ...) - :param verbose: print information (default = False) - :type verbose: bool - - Approximate the solution of the initial value problem - - .. math :: - \dot{x} &= f(t,x) \\ - x(t_0) &= x_0 - - Choose a value h for the size of every step and set - - .. math :: - t_i = t_0 + i h ~,\quad i=1,2,\ldots,n - - One step :math:`h` of the Euler method from :math:`t_i` to :math:`t_{i+1}` is - - .. math :: - x_{i+1} &= x_i + (t_{i+1}-t_i) f(t_i, x_i) \\ - x_{i+1} &= x_i + h f(t_i, x_i) \\ - - Example 1: - - .. math :: - m\ddot{u} + d\dot{u} + ku = f(t) \\ - \ddot{u} = m^{-1}(f(t) - d\dot{u} - ku) \\ - - with - - .. math :: - x_1 &= u &\quad \dot{x}_1 = \dot{u} = x_2 \\ - x_2 &= \dot{u} &\quad \dot{x}_2 = \ddot{u} \\ - - becomes - - .. math :: - \dot{x}_1 &= x_2 \\ - \dot{x}_2 &= m^{-1}(f(t) - d x_2 - k x_1) \\ - - or - - .. math :: - \dot{x} &= f(t,x) \\ - \begin{bmatrix} \dot{x}_1 \\ \dot{x}_1 \end{bmatrix} &= - \begin{bmatrix} x_2 \\ m^{-1}(f(t) - d x_2 - k x_1) \end{bmatrix} \\ - &= - \begin{bmatrix} 0 \\ m^{-1} f(t) \end{bmatrix} + - \begin{bmatrix} 0 & 1 \\ -m^{-1} k & -m^{-1} d \end{bmatrix} - \begin{bmatrix} x_1 \\ x_2 \end{bmatrix} - - Example 2: - - .. math :: - m(u)\ddot{u} + d(u,\dot{u})\dot{u} + k(u)u = f(t) \\ - \ddot{u} = m^{-1}(u)(f(t) - d(u,\dot{u})\dot{u} - k(u)u) \\ - - with - - .. math :: - x_1 &= u &\quad \dot{x}_1 = \dot{u} = x_2 \\ - x_2 &= \dot{u} &\quad \dot{x}_2 = \ddot{u} \\ - - becomes - - .. math :: - \dot{x}_1 &= x_2 \\ - \dot{x}_2 &= m^{-1}(x_1)(f(t) - d(x_1,x_2) x_2 - k(x_1) x_1) \\ - - or - - .. math :: - \dot{x} &= f(t,x) \\ - \begin{bmatrix} \dot{x}_1 \\ \dot{x}_2 \end{bmatrix} &= - \begin{bmatrix} x_2 \\ m^{-1}(x_1)(f(t) - d(x_1,x_2) x_2 - k(x_1) x_1) \end{bmatrix} \\ - &= - \begin{bmatrix} 0 \\ m^{-1}(x_1) f(t) \end{bmatrix} + - \begin{bmatrix} 0 & 1 \\ -m^{-1}(x_1) k(x_1) & -m^{-1} d(x_1,x_2) \end{bmatrix} - \begin{bmatrix} x_1 \\ x_2 \end{bmatrix} - - The Euler method is a first-order method, - which means that the local error (error per step) is proportional to the - square of the step size, and the global error (error at a given time) is - proportional to the step size. - """ - x = zeros((len(t), len(x0))) # Preallocate array - x[0,:] = x0 # Initial condition gives solution at t=0. - for i in range(len(t)-1): - Dt = t[i+1]-t[i] - dxdt = array(f(x[i,:], t[i], *p)) - x[i+1,:] = x[i,:] + dxdt*Dt # Approximate solution at next value of x - if verbose: - print('Numerical integration of ODE using explicit first-order method (Euler / Runge-Kutta) was successful.') - return x - -def e2(f, x0, t, *p, verbose=False): - r"""Explicit second-order method / Runge-Kutta 2nd order method. - - :param f: the function to solve - :type f: function - :param x0: initial condition - :type x0: list - :param t: time - :type t: list - :param `*p`: parameters of the function (thickness, diameter, ...) - :param verbose: print information (default = False) - :type verbose: bool - """ - x = zeros((len(t), len(x0))) - x[0,:] = x0 # initial condition - for i in range(len(t)-1): # calculation loop - Dt = t[i+1]-t[i] - k_1 = array(f(x[i,:], t[i], *p)) - k_2 = array(f(x[i,:]+0.5*Dt*k_1, t[i]+0.5*Dt, *p)) - x[i+1,:] = x[i,:] + k_2*Dt # main equation - if verbose: - print('Numerical integration of ODE using explicit 2th-order method (Runge-Kutta) was successful.') - return x - -def e4(f, x0, t, *p, verbose=False): - r"""Explicit fourth-order method / Runge-Kutta 4th order method. - - :param f: the function to solve - :type f: function - :param x0: initial condition - :type x0: list - :param t: time - :type t: list - :param `*p`: parameters of the function (thickness, diameter, ...) - :param verbose: print information (default = False) - :type verbose: bool - """ - x = zeros((len(t), len(x0))) # Preallocate array - x[0,:] = x0 # Initial condition gives solution at t=0. - for i in range(len(t)-1): # calculation loop - Dt = t[i+1]-t[i] - k_1 = array(f(x[i,:], t[i], *p)) - k_2 = array(f(x[i,:]+0.5*Dt*k_1, t[i]+0.5*Dt, *p)) - k_3 = array(f(x[i,:]+0.5*Dt*k_2, t[i]+0.5*Dt, *p)) - k_4 = array(f(x[i,:]+k_3*Dt, t[i]+Dt, *p)) - x[i+1,:] = x[i,:] + 1./6*(k_1+2*k_2+2*k_3+k_4)*Dt # main equation - if verbose: - print('Numerical integration of ODE using explicit 4th-order method (Runge-Kutta) was successful.') - return x - -def i1(f, x0, t, *p, max_iterations=1000, tol=1e-9, verbose=False): - r"""Implicite first-order method / backward Euler method. - - :param f: the function to solve - :type f: function - :param x0: initial condition - :type x0: list - :param t: time - :type t: list - :param `*p`: parameters of the function (thickness, diameter, ...) - :param max_iterations: maximum number of iterations - :type max_iterations: int - :param tol: tolerance against residuum (default = 1e-9) - :type tol: float - :param verbose: print information (default = False) - :type verbose: bool - - The backward Euler method has order one and is A-stable. - """ - iterations = zeros((len(t), 1)) - x = zeros((len(t), len(x0))) # Preallocate array - x[0,:] = x0 # Initial condition gives solution at t=0. - for i in range(len(t)-1): - Dt = t[i+1]-t[i] - x1 = x[i,:] - for j in range(max_iterations): # fixed-point iteration - dxdt = array(f(x1, t[i+1], *p)) - x11 = x[i,:] + dxdt*Dt # Approximate solution at next value of x - residuum = norm(x11-x1)/norm(x11) - x1 = x11 - if residuum < tol: - break - iterations[i] = j+1 - x[i+1,:] = x1 - if verbose: - print('Numerical integration of ODE using implicite first-order method (Euler) was successful.') - return x, iterations - -def newmark_newtonraphson(f, x0, xp0, xpp0, t, *p, gamma=.5, beta=.25, max_iterations=1000, tol=1e-9, verbose=False): - r"""Newmark method. - - :param f: the function to solve - :type f: function - :param x0: initial condition - :type x0: list - :param xp0: initial condition - :type xp0: list - :param xpp0: initial condition - :type xpp0: list - :param t: time - :type t: list - :param `*p`: parameters of the function (thickness, diameter, ...) - :param gamma: newmark parameter for velocity (default = 0.5) - :type gamma: float - :param beta: newmark parameter for displacement (default = 0.25) - :type beta: float - :param max_iterations: maximum number of iterations - :type max_iterations: int - :param tol: tolerance against residuum (default = 1e-9) - :type tol: float - :param verbose: print information (default = False) - :type verbose: bool - """ - iterations = zeros((len(t), 1)) - x = zeros((len(t), len(x0))) # Preallocate array - xp = zeros((len(t), len(xp0))) # Preallocate array - xpp = zeros((len(t), len(xpp0))) # Preallocate array - x[0,:] = x0 # Initial condition gives solution at t=0. - xp[0,:] = xp0 # Initial condition gives solution at t=0. - xpp[0,:] = xpp0 # Initial condition gives solution at t=0. - for i in range(len(t)-1): - Dt = t[i+1]-t[i] - - xi = x[i,:].reshape(3,1) - xpi = xp[i,:].reshape(3,1) - xppi = xpp[i,:].reshape(3,1) - x1 = xi - xp1 = xpi - xpp1 = xppi - j = 0 - for j in range(max_iterations): # fixed-point iteration - #dxdt = array(f(t[i+1], x1, p)) - #x11 = x[i,:] + dxdt*Dt # Approximate solution at next value of x - - N, dN, dNp, dNpp = f(x1.reshape(-1,).tolist(), - xp1.reshape(-1,).tolist(), xpp1.reshape(-1,).tolist(), - t[i], *p) - if isnan(sum(dN)) or isnan(sum(dNp)) or isnan(sum(dNpp)): - print('divergiert') - break - - xpp11 = xpp1 - dot(inv(dNpp), (N + dot(dN, (x1-xi)) + dot(dNp, (xp1-xpi)))) - xp1 = xpi + Dt*( (1-gamma)*xppi + gamma*xpp11 ) - x1 = xi + Dt*xpi + Dt**2*( (.5-beta)*xppi + beta*xpp11 ) - - residuum = norm(xpp11-xpp1)/norm(xpp11) - xpp1 = xpp11 - if residuum < tol: - break - iterations[i] = j+1 - - xpp[i+1,:] = xpp1.reshape(-1,).tolist() - xp[i+1,:] = xp1.reshape(-1,).tolist() - x[i+1,:] = x1.reshape(-1,).tolist() - if verbose: - print('Numerical integration of ODE using explicite newmark method was successful.') - return x, xp, xpp, iterations - # x = concatenate((x, xp, xpp), axis=1) - -def newmark_newtonraphson_rdk(fnm, x0, xp0, xpp0, t, *p, gamma=.5, beta=.25, maxIterations=1000, tol=1e-9, verbose=False): - r"""Newmark method. - - :param f: the function to solve - :type f: function - :param x0: initial condition - :type x0: list - :param xp0: initial condition - :type xp0: list - :param xpp0: initial condition - :type xpp0: list - :param t: time - :type t: list - :param `*p`: parameters of the function (thickness, diameter, ...) - :param gamma: newmark parameter for velocity (default = 0.5) - :type gamma: float - :param beta: newmark parameter for displacement (default = 0.25) - :type beta: float - :param max_iterations: maximum number of iterations - :type max_iterations: int - :param tol: tolerance against residuum (default = 1e-9) - :type tol: float - :param verbose: print information (default = False) - :type verbose: bool - """ - iterations = zeros((len(t), 1)) - x = zeros((len(t), len(x0))) # Preallocate array - xp = zeros((len(t), len(xp0))) # Preallocate array - xpp = zeros((len(t), len(xpp0))) # Preallocate array - x[0,:] = x0 # Initial condition gives solution at t=0. - xp[0,:] = xp0 # Initial condition gives solution at t=0. - xpp[0,:] = xpp0 # Initial condition gives solution at t=0. - for i in range(len(t)-1): - Dt = t[i+1]-t[i] - - rm, rmx, rmxpp, rd, rdx, rdxp, rk, rkx, f = fnm(x[i,:], xp[i,:], xpp[i,:], t[i], *p) - - xi = x[i,:].reshape(3,1) - xpi = xp[i,:].reshape(3,1) - xppi = xpp[i,:].reshape(3,1) - x1 = xi - xp1 = xpi - xpp1 = xppi - j = 0 - for j in range(maxIterations): # fixed-point iteration - #dxdt = array(f(t[i+1], x1, p)) - #x11 = x[i,:] + dxdt*Dt # Approximate solution at next value of x - - r = (rmx+rdx+rkx)*Dt**2./4 + rdxp*Dt/2 + rmxpp - rp = f - (rm + dot(rmx, (Dt*xpi+Dt**2./4*xppi)) - dot(rmxpp, xppi) + \ - rd + dot(rdx, (Dt*xpi+Dt**2./4*xppi)) + dot(rdxp, Dt/2*xppi) + \ - rk + dot(rkx, (Dt*xpi+Dt**2./4*xppi)) ) - xpp11 = dot(inv(r), rp) - xp1 = xpi + Dt*( (1-gamma)*xppi + gamma*xpp11 ) - x1 = xi + Dt*xpi + Dt**2*( (.5-beta)*xppi + beta*xpp11 ) - - residuum = norm(xpp11-xpp1)/norm(xpp11) - xpp1 = xpp11 - if residuum < tol: - break - iterations[i] = j+1 - - xpp[i+1,:] = xpp1.reshape(-1,).tolist() - xp[i+1,:] = xp1.reshape(-1,).tolist() - x[i+1,:] = x1.reshape(-1,).tolist() - if verbose: - print('Numerical integration of ODE using explicite newmark method was successful.') - return x, xp, xpp, iterations - # x = concatenate((x, xp, xpp), axis=1) +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Numerical solver of ordinary differential equations. + +Solves the initial value problem for systems of first order ordinary differential +equations. + +:Date: 2015-09-21 + +.. module:: ode + :platform: *nix, Windows + :synopsis: Numerical solver. + +.. moduleauthor:: Daniel Weschke +""" + +from __future__ import division, print_function +from numpy import array, isnan, sum, zeros, dot +from numpy.linalg import norm, inv + +def e1(f, x0, t, *p, verbose=False): + r"""Explicit first-order method / + (standard, or forward) Euler method / + Runge-Kutta 1st order method. + + de: + Euler'sche Polygonzugverfahren / explizite Euler-Verfahren / + Euler-Cauchy-Verfahren / Euler-vorwärts-Verfahren + + :param f: the function to solve + :type f: function + :param x0: initial condition + :type x0: list + :param t: time + :type t: list + :param `*p`: parameters of the function (thickness, diameter, ...) + :param verbose: print information (default = False) + :type verbose: bool + + Approximate the solution of the initial value problem + + .. math :: + \dot{x} &= f(t,x) \\ + x(t_0) &= x_0 + + Choose a value h for the size of every step and set + + .. math :: + t_i = t_0 + i h ~,\quad i=1,2,\ldots,n + + The derivative of the solution is approximated as the forward difference + equation + + .. math :: + \dot{x}_i = f(t_i, x_i) = \frac{x_{i+1} - x_i}{t_{i+1}-t_i} + + Therefore one step :math:`h` of the Euler method from :math:`t_i` to + :math:`t_{i+1}` is + + .. math :: + x_{i+1} &= x_i + (t_{i+1}-t_i) f(t_i, x_i) \\ + x_{i+1} &= x_i + h f(t_i, x_i) \\ + + Example 1: + + .. math :: + m\ddot{u} + d\dot{u} + ku = f(t) \\ + \ddot{u} = m^{-1}(f(t) - d\dot{u} - ku) \\ + + with + + .. math :: + x_1 &= u &\quad \dot{x}_1 = \dot{u} = x_2 \\ + x_2 &= \dot{u} &\quad \dot{x}_2 = \ddot{u} \\ + + becomes + + .. math :: + \dot{x}_1 &= x_2 \\ + \dot{x}_2 &= m^{-1}(f(t) - d x_2 - k x_1) \\ + + or + + .. math :: + \dot{x} &= f(t,x) \\ + \begin{bmatrix} \dot{x}_1 \\ \dot{x}_2 \end{bmatrix} &= + \begin{bmatrix} x_2 \\ m^{-1}(f(t) - d x_2 - k x_1) \end{bmatrix} \\ + &= + \begin{bmatrix} 0 \\ m^{-1} f(t) \end{bmatrix} + + \begin{bmatrix} 0 & 1 \\ -m^{-1} k & -m^{-1} d \end{bmatrix} + \begin{bmatrix} x_1 \\ x_2 \end{bmatrix} + + Example 2: + + .. math :: + m(u)\ddot{u} + d(u,\dot{u})\dot{u} + k(u)u = f(t) \\ + \ddot{u} = m^{-1}(u)(f(t) - d(u,\dot{u})\dot{u} - k(u)u) \\ + + with + + .. math :: + x_1 &= u &\quad \dot{x}_1 = \dot{u} = x_2 \\ + x_2 &= \dot{u} &\quad \dot{x}_2 = \ddot{u} \\ + + becomes + + .. math :: + \dot{x}_1 &= x_2 \\ + \dot{x}_2 &= m^{-1}(x_1)(f(t) - d(x_1,x_2) x_2 - k(x_1) x_1) \\ + + or + + .. math :: + \dot{x} &= f(t,x) \\ + \begin{bmatrix} \dot{x}_1 \\ \dot{x}_2 \end{bmatrix} &= + \begin{bmatrix} x_2 \\ m^{-1}(x_1)(f(t) - d(x_1,x_2) x_2 - k(x_1) x_1) \end{bmatrix} \\ + &= + \begin{bmatrix} 0 \\ m^{-1}(x_1) f(t) \end{bmatrix} + + \begin{bmatrix} 0 & 1 \\ -m^{-1}(x_1) k(x_1) & -m^{-1} d(x_1,x_2) \end{bmatrix} + \begin{bmatrix} x_1 \\ x_2 \end{bmatrix} + + The Euler method is a first-order method, + which means that the local error (error per step) is proportional to the + square of the step size, and the global error (error at a given time) is + proportional to the step size. + """ + x = zeros((len(t), len(x0))) # Preallocate array + x[0,:] = x0 # Initial condition gives solution at first t + for i in range(len(t)-1): # Calculation loop + Dt = t[i+1]-t[i] + dxdt = array(f(x[i,:], t[i], *p)) + x[i+1,:] = x[i,:] + dxdt*Dt # Approximate solution at next value of x + if verbose: + print('Numerical integration of ODE using explicit first-order method (Euler / Runge-Kutta) was successful.') + return x + +def e2(f, x0, t, *p, verbose=False): + r"""Explicit second-order method / Runge-Kutta 2nd order method. + + :param f: the function to solve + :type f: function + :param x0: initial condition + :type x0: list + :param t: time + :type t: list + :param `*p`: parameters of the function (thickness, diameter, ...) + :param verbose: print information (default = False) + :type verbose: bool + """ + x = zeros((len(t), len(x0))) # Preallocate array + x[0,:] = x0 # Initial condition gives solution at first t + for i in range(len(t)-1): # Calculation loop + Dt = t[i+1]-t[i] + k_1 = array(f(x[i,:], t[i], *p)) + k_2 = array(f(x[i,:]+0.5*Dt*k_1, t[i]+0.5*Dt, *p)) + x[i+1,:] = x[i,:] + k_2*Dt # Approximate solution at next value of x + if verbose: + print('Numerical integration of ODE using explicit 2th-order method (Runge-Kutta) was successful.') + return x + +def e4(f, x0, t, *p, verbose=False): + r"""Explicit fourth-order method / Runge-Kutta 4th order method. + + :param f: the function to solve + :type f: function + :param x0: initial condition + :type x0: list + :param t: time + :type t: list + :param `*p`: parameters of the function (thickness, diameter, ...) + :param verbose: print information (default = False) + :type verbose: bool + """ + x = zeros((len(t), len(x0))) # Preallocate array + x[0,:] = x0 # Initial condition + for i in range(len(t)-1): # Calculation loop + Dt = t[i+1]-t[i] + k_1 = array(f(x[i,:], t[i], *p)) + k_2 = array(f(x[i,:]+0.5*Dt*k_1, t[i]+0.5*Dt, *p)) + k_3 = array(f(x[i,:]+0.5*Dt*k_2, t[i]+0.5*Dt, *p)) + k_4 = array(f(x[i,:]+k_3*Dt, t[i]+Dt, *p)) + x[i+1,:] = x[i,:] + 1./6*(k_1+2*k_2+2*k_3+k_4)*Dt # Approximate solution at next value of x + if verbose: + print('Numerical integration of ODE using explicit 4th-order method (Runge-Kutta) was successful.') + return x + +def dxdt_Dt(f, x, t, Dt, *p): + r""" + :param f: :math:`f = \dot{x}` + :type f: function + :param Dt: :math:`\Delta{t}` + + :returns: :math:`\Delta x = \dot{x} \Delta t` + """ + return array(dxdt(x, t, *p)) * Dt + +def fixed_point_iteration(f, xi, t, max_iterations=1000, tol=1e-9, verbose=False): + r""" + :param f: the function to iterate :math:`f = \Delta{x}(t)` + :type f: function + :param xi: initial condition :math:`x_i` + :type xi: list + :param t: time :math:`t` + :type t: float + :param `*p`: parameters of the function (thickness, diameter, ...) + :param max_iterations: maximum number of iterations + :type max_iterations: int + :param tol: tolerance against residuum (default = 1e-9) + :type tol: float + :param verbose: print information (default = False) + :type verbose: bool + + :returns: :math:`x_{i+1}` + + .. math :: + x_{i+1} = x_i + \Delta x + + .. seealso:: + :meth:`dxdt_Dt` for :math:`\Delta x` + """ + xi = x0 + for j in range(max_iterations): # Fixed-point iteration + Dx = array(f(xi, t, *p)) + xi1 = x0 + Dx # Approximate solution at next value of x + residuum = norm(xi1-xi)/norm(xi1) + xi = xi1 + if residuum < tol: + break + iterations = j+1 # number beginning with 1 therefore + 1 + return xi, iterations + +def i1n(f, x0, t, *p, max_iterations=1000, tol=1e-9, verbose=False): + iterations = zeros((len(t), 1)) + x = zeros((len(t), len(x0))) # Preallocate array + x[0,:] = x0 # Initial condition gives solution at first t + for i in range(len(t)-1): + Dt = t[i+1]-t[i] + xi = x[i,:] + Dx = dxdt_Dt(f, xi, t[i+1], Dt, *p) + x[i+1,:], iterations[i] = fixed_point_iteration(Dx, xi, t, max_iterations, tol, verbose) + if verbose: + print('Numerical integration of ODE using implicite first-order method (Euler) was successful.') + return x, iterations + +def i1(f, x0, t, *p, max_iterations=1000, tol=1e-9, verbose=False): + r"""Implicite first-order method / backward Euler method. + + :param f: the function to solve + :type f: function + :param x0: initial condition + :type x0: list + :param t: time + :type t: list + :param `*p`: parameters of the function (thickness, diameter, ...) + :param max_iterations: maximum number of iterations + :type max_iterations: int + :param tol: tolerance against residuum (default = 1e-9) + :type tol: float + :param verbose: print information (default = False) + :type verbose: bool + + The backward Euler method has order one and is A-stable. + """ + iterations = zeros((len(t), 1)) + x = zeros((len(t), len(x0))) # Preallocate array + x[0,:] = x0 # Initial condition gives solution at first t + for i in range(len(t)-1): + Dt = t[i+1]-t[i] + xi = x[i,:] + # x(i+1) = x(i) + f(x(i+1), t(i+1)), exact value of f(x(i+1), t(i+1)) is not + # available therefor using Newton-Raphson method + for j in range(max_iterations): # Fixed-point iteration + dxdt = array(f(xi, t[i+1], *p)) + xi1 = x[i,:] + dxdt*Dt # Approximate solution at next value of x + residuum = norm(xi1-xi)/norm(xi1) + xi = xi1 + if residuum < tol: + break + iterations[i] = j+1 + x[i+1,:] = xi + if verbose: + print('Numerical integration of ODE using implicite first-order method (Euler) was successful.') + return x, iterations + +def newmark_newtonraphson(f, x0, xp0, xpp0, t, *p, gamma=.5, beta=.25, max_iterations=1000, tol=1e-9, verbose=False): + r"""Newmark method. + + :param f: the function to solve + :type f: function + :param x0: initial condition + :type x0: list + :param xp0: initial condition + :type xp0: list + :param xpp0: initial condition + :type xpp0: list + :param t: time + :type t: list + :param `*p`: parameters of the function (thickness, diameter, ...) + :param gamma: newmark parameter for velocity (default = 0.5) + :type gamma: float + :param beta: newmark parameter for displacement (default = 0.25) + :type beta: float + :param max_iterations: maximum number of iterations + :type max_iterations: int + :param tol: tolerance against residuum (default = 1e-9) + :type tol: float + :param verbose: print information (default = False) + :type verbose: bool + """ + iterations = zeros((len(t), 1)) + x = zeros((len(t), len(x0))) # Preallocate array + xp = zeros((len(t), len(xp0))) # Preallocate array + xpp = zeros((len(t), len(xpp0))) # Preallocate array + x[0,:] = x0 # Initial condition gives solution at first t + xp[0,:] = xp0 # Initial condition gives solution at first t + xpp[0,:] = xpp0 # Initial condition gives solution at first t + for i in range(len(t)-1): + Dt = t[i+1]-t[i] + + xi = x[i,:].reshape(3,1) + xpi = xp[i,:].reshape(3,1) + xppi = xpp[i,:].reshape(3,1) + x1 = xi + xp1 = xpi + xpp1 = xppi + j = 0 + for j in range(max_iterations): # Fixed-point iteration + #dxdt = array(f(t[i+1], x1, p)) + #x11 = x[i,:] + dxdt*Dt # Approximate solution at next value of x + + N, dN, dNp, dNpp = f(x1.reshape(-1,).tolist(), + xp1.reshape(-1,).tolist(), xpp1.reshape(-1,).tolist(), + t[i], *p) + if isnan(sum(dN)) or isnan(sum(dNp)) or isnan(sum(dNpp)): + print('divergiert') + break + + xpp11 = xpp1 - dot(inv(dNpp), (N + dot(dN, (x1-xi)) + dot(dNp, (xp1-xpi)))) + xp1 = xpi + Dt*( (1-gamma)*xppi + gamma*xpp11 ) + x1 = xi + Dt*xpi + Dt**2*( (.5-beta)*xppi + beta*xpp11 ) + + residuum = norm(xpp11-xpp1)/norm(xpp11) + xpp1 = xpp11 + if residuum < tol: + break + iterations[i] = j+1 + + xpp[i+1,:] = xpp1.reshape(-1,).tolist() + xp[i+1,:] = xp1.reshape(-1,).tolist() + x[i+1,:] = x1.reshape(-1,).tolist() + if verbose: + print('Numerical integration of ODE using explicite newmark method was successful.') + return x, xp, xpp, iterations + # x = concatenate((x, xp, xpp), axis=1) + +def newmark_newtonraphson_rdk(fnm, x0, xp0, xpp0, t, *p, gamma=.5, beta=.25, maxIterations=1000, tol=1e-9, verbose=False): + r"""Newmark method. + + :param f: the function to solve + :type f: function + :param x0: initial condition + :type x0: list + :param xp0: initial condition + :type xp0: list + :param xpp0: initial condition + :type xpp0: list + :param t: time + :type t: list + :param `*p`: parameters of the function (thickness, diameter, ...) + :param gamma: newmark parameter for velocity (default = 0.5) + :type gamma: float + :param beta: newmark parameter for displacement (default = 0.25) + :type beta: float + :param max_iterations: maximum number of iterations + :type max_iterations: int + :param tol: tolerance against residuum (default = 1e-9) + :type tol: float + :param verbose: print information (default = False) + :type verbose: bool + """ + iterations = zeros((len(t), 1)) + x = zeros((len(t), len(x0))) # Preallocate array + xp = zeros((len(t), len(xp0))) # Preallocate array + xpp = zeros((len(t), len(xpp0))) # Preallocate array + x[0,:] = x0 # Initial condition gives solution at first t + xp[0,:] = xp0 # Initial condition gives solution at first t + xpp[0,:] = xpp0 # Initial condition gives solution at first t + for i in range(len(t)-1): + Dt = t[i+1]-t[i] + + rm, rmx, rmxpp, rd, rdx, rdxp, rk, rkx, f = fnm(x[i,:], xp[i,:], xpp[i,:], t[i], *p) + + xi = x[i,:].reshape(3,1) + xpi = xp[i,:].reshape(3,1) + xppi = xpp[i,:].reshape(3,1) + x1 = xi + xp1 = xpi + xpp1 = xppi + j = 0 + for j in range(maxIterations): # Fixed-point iteration + #dxdt = array(f(t[i+1], x1, p)) + #x11 = x[i,:] + dxdt*Dt # Approximate solution at next value of x + + r = (rmx+rdx+rkx)*Dt**2./4 + rdxp*Dt/2 + rmxpp + rp = f - (rm + dot(rmx, (Dt*xpi+Dt**2./4*xppi)) - dot(rmxpp, xppi) + \ + rd + dot(rdx, (Dt*xpi+Dt**2./4*xppi)) + dot(rdxp, Dt/2*xppi) + \ + rk + dot(rkx, (Dt*xpi+Dt**2./4*xppi)) ) + xpp11 = dot(inv(r), rp) + xp1 = xpi + Dt*( (1-gamma)*xppi + gamma*xpp11 ) + x1 = xi + Dt*xpi + Dt**2*( (.5-beta)*xppi + beta*xpp11 ) + + residuum = norm(xpp11-xpp1)/norm(xpp11) + xpp1 = xpp11 + if residuum < tol: + break + iterations[i] = j+1 + + xpp[i+1,:] = xpp1.reshape(-1,).tolist() + xp[i+1,:] = xp1.reshape(-1,).tolist() + x[i+1,:] = x1.reshape(-1,).tolist() + if verbose: + print('Numerical integration of ODE using explicite newmark method was successful.') + return x, xp, xpp, iterations + # x = concatenate((x, xp, xpp), axis=1) diff --git a/src/solver_model.py b/src/numerical/ode_model.py similarity index 95% rename from src/solver_model.py rename to src/numerical/ode_model.py index 8e76a6c..1a64be6 100644 --- a/src/solver_model.py +++ b/src/numerical/ode_model.py @@ -1,120 +1,120 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -"""Mathmatical models governed by ordinary differential equations. - -Describes initial value problems as systems of first order ordinary differential -equations. - -:Date: 2019-05-25 - -.. module:: solver_model - :platform: *nix, Windows - :synopsis: Mechanical models. - -.. moduleauthor:: Daniel Weschke -""" -from __future__ import division, print_function -from numpy import array, cos, sin, dot, square -from numpy.linalg import inv - -def disk(x, t, *p): - """Rotation of an eccentric disk. - - :param x: values of the function - :type x: list - :param t: time - :type t: list - :param `*p`: parameters of the function - - * diameter - * eccentricity - * torque - """ - qp1 = x[3] - qp2 = x[4] - qp3 = x[5] - M = array([[1, 0, cos(x[2])], [0, 1, -sin(x[2])], [0, 0, 1]]) - y = array([[-2*p[0]*x[3]+sin(x[2])*x[5]**2-2*p[0]*cos(x[2])*x[5]-x[0]], \ - [-2*p[0]*x[4]+cos(x[2])*x[5]**2-2*p[0]*sin(x[2])*x[5]-x[1]], \ - [p[2]-p[1]*x[1]*sin(x[2])+p[1]*x[0]*cos(x[2])]]) - qp46 = dot(inv(M), y) - qp4, qp5, qp6 = qp46.reshape(-1,).tolist() # 2d array to 1d array to list - return qp1, qp2, qp3, qp4, qp5, qp6 - -def disk_nm(xn, xpn, xppn, t, *p): - """Rotation of an eccentric disk. - - :param xn: values of the function - :type xn: list - :param xpn: first derivative values of the function - :type xpn: list - :param xppn: second derivative values of the function - :type xppn: list - :param t: time - :type t: list - :param `*p`: parameters of the function - - * diameter - * eccentricity - * torque - """ - N = array([[xppn[0]+cos(xn[2])*xppn[2]+2*p[0]*xpn[0]+2*p[0]*cos(xn[2])*xpn[2]-sin(xn[2])*square(xpn[2])+xn[0]], - [xppn[1]-sin(xn[2])*xppn[2]+2*p[0]*xpn[1]-2*p[0]*sin(xn[2])*xpn[2]-cos(xn[2])*square(xpn[2])+xn[1]], - [xppn[2]+p[1]*(-cos(xn[2])*xn[0]+sin(xn[2])*xn[1])-p[2]]]) - dN = array([[1, 0, -sin(xn[2]*xppn[2])-2*p[0]*sin(xn[2])*xpn[2]-cos(xn[2])*square(xpn[2])], - [0, 1, -cos(xn[2]*xppn[2])-2*p[0]*cos(xn[2])*xpn[2]+sin(xn[2])*square(xpn[2])], - [-p[1]*cos(xn[2]), p[1]*cos(xn[2]), p[1]*(sin(xn[2])*xn[0]+cos(xn[2])*xn[1])]]) - dNp = array([[2*p[0], 0, 2*p[0]*cos(xn[2])-2*sin(xn[2])*xpn[2]], - [0, 2*p[0], -2*p[0]*sin(xn[2])-2*cos(xn[2])*xpn[2]], - [0, 0, 0]]) - dNpp = array([[1, 0, cos(xn[2])], - [0, 1, -sin(xn[2])], - [0, 0, 1]]) - return N, dN, dNp, dNpp - -def disk_nmmdk(xn, xpn, xppn, t, *p): - """Rotation of an eccentric disk. - - :param xn: values of the function - :type xn: list - :param xpn: derivative values of the function - :type xpn: list - :param xppn: second derivative values of the function - :type xppn: list - :param t: time - :type t: list - :param `*p`: parameters of the function - - * diameter - * eccentricity - * torque - """ - rm = array([[xppn[0]+cos(xn[2])*xppn[2]], - [xppn[1]-sin(xn[2])*xppn[2]], - [xppn[2]]]) - rmx = array([[0, 0, -sin(xn[2]*xppn[2])], - [0, 0, -cos(xn[2]*xppn[2])], - [0, 0, 0]]) - rmxpp = array([[1, 0, cos(xn[2])], - [0, 1, -sin(xn[2])], - [0, 0, 1]]) - rd = array([[2*p[0]*xpn[0]+2*p[0]*cos(xn[2])*xpn[2]-sin(xn[2])*square(xpn[2])], - [2*p[0]*xpn[1]-2*p[0]*sin(xn[2])*xpn[2]-cos(xn[2])*square(xpn[2])], - [0]]) - rdx = array([[0, 0, -2*p[0]*sin(xn[2])*xpn[2]-cos(xn[2])*square(xpn[2])], - [0, 0, -2*p[0]*cos(xn[2])*xpn[2]+sin(xn[2])*square(xpn[2])], - [0, 0, 0]]) - rdxp = array([[2*p[0], 0, 2*p[0]*cos(xn[2])-2*sin(xn[2])*xpn[2]], - [0, 2*p[0], -2*p[0]*sin(xn[2])-2*cos(xn[2])*xpn[2]], - [0, 0, 0]]) - rk = array([[xn[0]], - [xn[1]], - [p[1]*(-cos(xn[2])*xn[0]+sin(xn[2])*xn[1])]]) - rkx = array([[ 1, 0, 0], - [ 0, 1, 0], - [-p[1]*cos(xn[2]), p[1]*cos(xn[2]), p[1]*(sin(xn[2])*xn[0]+cos(xn[2])*xn[1])]]) - f = array([[0], [0], [p[2]]]) - return rm, rmx, rmxpp, rd, rdx, rdxp, rk, rkx, f - -if __name__ == '__main__': - 0 +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Mathmatical models governed by ordinary differential equations. + +Describes initial value problems as systems of first order ordinary differential +equations. + +:Date: 2019-05-25 + +.. module:: ode_model + :platform: *nix, Windows + :synopsis: Models of ordinary differential equations. + +.. moduleauthor:: Daniel Weschke +""" +from __future__ import division, print_function +from numpy import array, cos, sin, dot, square +from numpy.linalg import inv + +def disk(x, t, *p): + """Rotation of an eccentric disk. + + :param x: values of the function + :type x: list + :param t: time + :type t: list + :param `*p`: parameters of the function + + * diameter + * eccentricity + * torque + """ + qp1 = x[3] + qp2 = x[4] + qp3 = x[5] + M = array([[1, 0, cos(x[2])], [0, 1, -sin(x[2])], [0, 0, 1]]) + y = array([[-2*p[0]*x[3]+sin(x[2])*x[5]**2-2*p[0]*cos(x[2])*x[5]-x[0]], \ + [-2*p[0]*x[4]+cos(x[2])*x[5]**2-2*p[0]*sin(x[2])*x[5]-x[1]], \ + [p[2]-p[1]*x[1]*sin(x[2])+p[1]*x[0]*cos(x[2])]]) + qp46 = dot(inv(M), y) + qp4, qp5, qp6 = qp46.reshape(-1,).tolist() # 2d array to 1d array to list + return qp1, qp2, qp3, qp4, qp5, qp6 + +def disk_nm(xn, xpn, xppn, t, *p): + """Rotation of an eccentric disk. + + :param xn: values of the function + :type xn: list + :param xpn: first derivative values of the function + :type xpn: list + :param xppn: second derivative values of the function + :type xppn: list + :param t: time + :type t: list + :param `*p`: parameters of the function + + * diameter + * eccentricity + * torque + """ + N = array([[xppn[0]+cos(xn[2])*xppn[2]+2*p[0]*xpn[0]+2*p[0]*cos(xn[2])*xpn[2]-sin(xn[2])*square(xpn[2])+xn[0]], + [xppn[1]-sin(xn[2])*xppn[2]+2*p[0]*xpn[1]-2*p[0]*sin(xn[2])*xpn[2]-cos(xn[2])*square(xpn[2])+xn[1]], + [xppn[2]+p[1]*(-cos(xn[2])*xn[0]+sin(xn[2])*xn[1])-p[2]]]) + dN = array([[1, 0, -sin(xn[2]*xppn[2])-2*p[0]*sin(xn[2])*xpn[2]-cos(xn[2])*square(xpn[2])], + [0, 1, -cos(xn[2]*xppn[2])-2*p[0]*cos(xn[2])*xpn[2]+sin(xn[2])*square(xpn[2])], + [-p[1]*cos(xn[2]), p[1]*cos(xn[2]), p[1]*(sin(xn[2])*xn[0]+cos(xn[2])*xn[1])]]) + dNp = array([[2*p[0], 0, 2*p[0]*cos(xn[2])-2*sin(xn[2])*xpn[2]], + [0, 2*p[0], -2*p[0]*sin(xn[2])-2*cos(xn[2])*xpn[2]], + [0, 0, 0]]) + dNpp = array([[1, 0, cos(xn[2])], + [0, 1, -sin(xn[2])], + [0, 0, 1]]) + return N, dN, dNp, dNpp + +def disk_nmmdk(xn, xpn, xppn, t, *p): + """Rotation of an eccentric disk. + + :param xn: values of the function + :type xn: list + :param xpn: derivative values of the function + :type xpn: list + :param xppn: second derivative values of the function + :type xppn: list + :param t: time + :type t: list + :param `*p`: parameters of the function + + * diameter + * eccentricity + * torque + """ + rm = array([[xppn[0]+cos(xn[2])*xppn[2]], + [xppn[1]-sin(xn[2])*xppn[2]], + [xppn[2]]]) + rmx = array([[0, 0, -sin(xn[2]*xppn[2])], + [0, 0, -cos(xn[2]*xppn[2])], + [0, 0, 0]]) + rmxpp = array([[1, 0, cos(xn[2])], + [0, 1, -sin(xn[2])], + [0, 0, 1]]) + rd = array([[2*p[0]*xpn[0]+2*p[0]*cos(xn[2])*xpn[2]-sin(xn[2])*square(xpn[2])], + [2*p[0]*xpn[1]-2*p[0]*sin(xn[2])*xpn[2]-cos(xn[2])*square(xpn[2])], + [0]]) + rdx = array([[0, 0, -2*p[0]*sin(xn[2])*xpn[2]-cos(xn[2])*square(xpn[2])], + [0, 0, -2*p[0]*cos(xn[2])*xpn[2]+sin(xn[2])*square(xpn[2])], + [0, 0, 0]]) + rdxp = array([[2*p[0], 0, 2*p[0]*cos(xn[2])-2*sin(xn[2])*xpn[2]], + [0, 2*p[0], -2*p[0]*sin(xn[2])-2*cos(xn[2])*xpn[2]], + [0, 0, 0]]) + rk = array([[xn[0]], + [xn[1]], + [p[1]*(-cos(xn[2])*xn[0]+sin(xn[2])*xn[1])]]) + rkx = array([[ 1, 0, 0], + [ 0, 1, 0], + [-p[1]*cos(xn[2]), p[1]*cos(xn[2]), p[1]*(sin(xn[2])*xn[0]+cos(xn[2])*xn[1])]]) + f = array([[0], [0], [p[2]]]) + return rm, rmx, rmxpp, rd, rdx, rdxp, rk, rkx, f + +if __name__ == '__main__': + True diff --git a/tests/test_fit.py b/tests/test_fit.py index fa7a7d0..6634b41 100644 --- a/tests/test_fit.py +++ b/tests/test_fit.py @@ -1,15 +1,53 @@ +"""Test of fit module. + +:Date: 2019-05-29 + +.. module:: test_fit + :platform: *nix, Windows + :synopsis: Test of fit module. + +.. moduleauthor:: Daniel Weschke +""" import unittest import os import sys +from pylab import array, argmax, subplot, plot, title, xlim, show, gradient, linspace sys.path.insert(0, os.path.abspath('../src')) -import fit +from data import data_read +from numerical.fit import gauss_fit class TestFit(unittest.TestCase): - def test_property(self): - self.assertEqual() + def test_gauss(self): + """test function""" + file_name = "test_fit.dat" + x, y = data_read(file_name, 3, 2) + + subplot(2,2,1) + plot(x, y, '.-') + + subplot(2,2,2) + dx = x[1] - x[0] + dydx = gradient(y, dx) # central differences + x_fit = linspace(x[0], x[-1], 150 if len(x) < 50 else len(x)*3) + y_fit, popt, FWHM = gauss_fit(list(reversed(x)), list(reversed(dydx)), x_fit=x_fit, verbose=True) # x must increase! + plot(x, dydx, '.-') + plot(x_fit, y_fit, 'r:') + title('FWHM: %f' % FWHM) + + subplot(2,2,3) + plot(x, y, '.-') + xlim(popt[1]-2*FWHM, popt[1]+2*FWHM) + + subplot(2,2,4) + plot(x, dydx, '.-') + plot(x_fit, y_fit, 'r:') + xlim(popt[1]-2*FWHM, popt[1]+2*FWHM) + + show() + self.assertEqual(FWHM, 0.12975107355013618) if __name__ == '__main__': diff --git a/tests/test_solver.py b/tests/test_ode.py similarity index 65% rename from tests/test_solver.py rename to tests/test_ode.py index fe41a83..038c0b5 100644 --- a/tests/test_solver.py +++ b/tests/test_ode.py @@ -1,201 +1,209 @@ -#!/usr/bin/env python -# -*- coding: utf-8 -*- -"""Numerical solver. - -:Date: 2019-05-25 - -.. module:: solver - :platform: *nix, Windows - :synopsis: Numerical solver. - -.. moduleauthor:: Daniel Weschke -""" -from __future__ import division, print_function -import unittest -import math -from numpy import linspace, allclose -from numpy.linalg import inv - -import os -import sys -sys.path.insert(0, os.path.abspath('../src')) -import solver -import solver_model - -#### Post processing -from matplotlib.pyplot import figure, subplots, plot, show -from numpy import sqrt, square, concatenate - -def plotx1rphi(x, t, title): - """Plot plane rotation (x, y, phi) - """ - x1 = x[:, 0] - x2 = x[:, 1] - x3 = x[:, 2] - xp1 = x[:, 3] - xp2 = x[:, 4] - xp3 = x[:, 5] - fig, ax1 = subplots() - ax1.set_title(title) - ax1.plot(t, x1, 'b-') - #ax1.plot(t, x3, 'b-') - ax1.set_xlabel('time t in s') - # Make the y-axis label and tick labels match the line color. - ax1.set_ylabel('x_1', color='b') - for tl in ax1.get_yticklabels(): - tl.set_color('b') - envelope = sqrt(square(x1)+square(x2)) - ax1.plot(t, envelope, 'b--', t, -envelope, 'b--') - ax2 = ax1.twinx() - ax2.plot(t, xp3, 'r') - ax2.set_ylabel('phi', color='r') - for tl in ax2.get_yticklabels(): - tl.set_color('r') - if max(xp3) < 2: - ax2.set_ylim([0,2]) - -f = solver_model.disk -fnm = solver_model.disk_nm -fnmmdk = solver_model.disk_nmmdk - - -class TestSolver(unittest.TestCase): - - Dt = .01 # Delta t - tend = .1 # t_end - #tend = 300 - nt = math.ceil(tend/Dt) # number of timesteps - t = linspace(0., tend, nt+1) # time vector - x0 = 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 # initial conditions - p = .01, .002, .015 # parameter of the model - - def test_e1(self): - xe1 = solver.e1(f, self.x0, self.t, *self.p) - #plotx1rphi(xe1, self.t, ("Euler (Runge-Kutta 1th order), increments: %d" % self.nt)) - #show() - self.assertTrue(allclose(xe1[:, 5], - [0., 0.00015, 0.0003, 0.00045, 0.0006, 0.00075, 0.0009, 0.00105, 0.0012, - 0.00135, 0.0015 ])) - - Dt_2 = Dt/5. - nt_2 = math.ceil(tend/Dt_2) - t_2 = linspace(0., tend, nt_2+1) - - def test_e1_2(self): - xe1_2 = solver.e1(f, self.x0, self.t_2, *self.p) - #plotx1rphi(xe1_2, self.t_2, ("Euler (Runge-Kutta 1th order), increments: %d" % self.nt_2)) - #show() - self.assertTrue(allclose(xe1_2[:, 5], -[0.00000000e+00, 3.00000000e-05, 6.00000000e-05, 8.99999998e-05, - 1.19999999e-04, 1.49999998e-04, 1.79999995e-04, 2.09999992e-04, - 2.39999987e-04, 2.69999980e-04, 2.99999971e-04, 3.29999960e-04, - 3.59999947e-04, 3.89999931e-04, 4.19999913e-04, 4.49999891e-04, - 4.79999866e-04, 5.09999837e-04, 5.39999804e-04, 5.69999767e-04, - 5.99999726e-04, 6.29999681e-04, 6.59999630e-04, 6.89999575e-04, - 7.19999514e-04, 7.49999448e-04, 7.79999376e-04, 8.09999298e-04, - 8.39999214e-04, 8.69999123e-04, 8.99999026e-04, 9.29998921e-04, - 9.59998810e-04, 9.89998691e-04, 1.01999856e-03, 1.04999843e-03, - 1.07999829e-03, 1.10999814e-03, 1.13999798e-03, 1.16999781e-03, - 1.19999763e-03, 1.22999744e-03, 1.25999725e-03, 1.28999704e-03, - 1.31999682e-03, 1.34999660e-03, 1.37999636e-03, 1.40999611e-03, - 1.43999585e-03, 1.46999558e-03, 1.49999530e-03] - )) - - maxIterations = 1000 - tol = 1e-9 # against residuum - - def test_e2(self): - xe2 = solver.e2(f, self.x0, self.t, *self.p) - #plotx1rphi(xe2, self.t, ("Runge-Kutta 2th order, increments: %d" % self.nt)) - #show() - self.assertTrue(allclose(xe2[:, 5], - [0., 0.00015, 0.0003, 0.00045, 0.0006, 0.00075, 0.0009, 0.00105, 0.0012, - 0.00135, 0.0015 ])) - - def test_e4(self): - xe4 = solver.e4(f, self.x0, self.t, *self.p) - #plotx1rphi(xe4, self.t, ("Runge-Kutta 4th order, increments: %d" % self.nt)) - #show() - self.assertTrue(allclose(xe4[:, 5], - [0., 0.00015, 0.0003, 0.00045, 0.0006, 0.00075, 0.0009, 0.00105, 0.0012, - 0.00135, 0.0015 ])) - - def test_i1(self): - xi1, iterations = solver.i1(f, self.x0, self.t, *self.p, self.maxIterations, self.tol) - #plotx1rphi(xi1, self.t, ("Backward Euler, increments: %d, iterations: %d" % (self.nt, sum(iterations)))) - #show() - self.assertTrue(allclose(xi1[:, 5], - [0., 0.00015, 0.0003, 0.00045, 0.0006, 0.00075, 0.0009, 0.00105, 0.0012, - 0.00135, 0.0015 ])) - - gamma = .5 # newmark parameter for velocity - beta = .25 # newmark parameter for displacement - - def test_nm(self): - xnm, xpnm, xppnm, iterations = solver.newmark_newtonraphson(fnm, - (0,0,0), (0,0,0), (0,0,0), self.t, *self.p, - self.gamma, self.beta, 1, self.tol) - #print(xnm) - #print(xpnm) - x = concatenate((xnm, xpnm), axis=1) - #plotx1rphi(x, self.t, ("Newmark, increments: %d, iterations: %d" % (self.nt, sum(iterations)))) - #show() - self.assertTrue(allclose(x[:, 5], -[0.00000000e+00, 7.49999925e-05, 2.24999951e-04, 3.74999839e-04, - 5.24999621e-04, 6.74999269e-04, 8.24998752e-04, 9.74998039e-04, - 1.12499710e-03, 1.27499591e-03, 1.42499444e-03] - )) - - def test_nm_2(self): - xnm, xpnm, xppnm, iterations = solver.newmark_newtonraphson(fnm, - (0,0,0), (0,0,0), (0,0,0), self.t, *self.p, - self.gamma, self.beta, self.maxIterations, self.tol) - #print(xnm) - #print(xpnm) - x = concatenate((xnm, xpnm), axis=1) - #plotx1rphi(x, self.t, ("Newmark, increments: %d, iterations: %d" % (self.nt, sum(iterations)))) - #show() - self.assertTrue(allclose(x[:, 5], -[0.00000000e+00, 7.49999925e-05, 2.24999951e-04, 3.74999839e-04, - 5.24999621e-04, 6.74999269e-04, 8.24998752e-04, 9.74998039e-04, - 1.12499710e-03, 1.27499591e-03, 1.42499444e-03] - )) - - def test_nmmdk(self): - xnm, xpnm, xppnm, iterations = solver.newmark_newtonraphson_rdk(fnmmdk, - (0,0,0), (0,0,0), (0,0,0), self.t, *self.p, - self.gamma, self.beta, 1, self.tol) - #print(xnm) - #print(xpnm) - x = concatenate((xnm, xpnm), axis=1) - #plotx1rphi(x, self.t, ("Newmark, increments: %d, iterations: %d" % (self.nt, sum(iterations)))) - #show() - self.assertTrue(allclose(x[:, 5], -[0.00000000e+00, 7.49999963e-05, 2.24999974e-04, 3.74999906e-04, - 5.24999764e-04, 6.74999516e-04, 8.24999134e-04, 9.74998586e-04, - 1.12499784e-03, 1.27499688e-03, 1.42499566e-03] - )) - - def test_nmmdk_2(self): - xnm, xpnm, xppnm, iterations = solver.newmark_newtonraphson_rdk(fnmmdk, - (0,0,0), (0,0,0), (0,0,0), self.t, *self.p, - self.gamma, self.beta, 100, self.tol) - #print(xnm) - #print(xpnm) - x = concatenate((xnm, xpnm), axis=1) - #plotx1rphi(x, self.t, ("Newmark, increments: %d, iterations: %d" % (self.nt, sum(iterations)))) - #show() - self.assertTrue(allclose(x[:, 5], -[0.00000000e+00, 7.49999963e-05, 2.24999974e-04, 3.74999906e-04, - 5.24999764e-04, 6.74999516e-04, 8.24999134e-04, 9.74998586e-04, - 1.12499784e-03, 1.27499688e-03, 1.42499566e-03] - )) - - #from scipy.integrate import odeint - #xode = odeint(solver_model.disk, x0, t, p, printmessg=True) - #plotx1rphi(xode, t, ("ODE, Inkremente: %d" % nt)) - #show() - - -if __name__ == '__main__': - unittest.main() +#!/usr/bin/env python +# -*- coding: utf-8 -*- +"""Test of numerical solver. + +:Date: 2019-05-25 + +.. module:: test_ode + :platform: *nix, Windows + :synopsis: Test of numerical solver. + +.. moduleauthor:: Daniel Weschke +""" +from __future__ import division, print_function +import unittest +import math +from numpy import linspace, allclose, sqrt, square, concatenate +from numpy.linalg import inv +from matplotlib.pyplot import figure, subplots, plot, show + +import os +import sys +sys.path.insert(0, os.path.abspath('../src')) +from numerical.ode import (e1, e2, e4, i1, newmark_newtonraphson, + newmark_newtonraphson_rdk) +from numerical.ode_model import disk, disk_nm, disk_nmmdk + +def plotx1rphi(x, t, title): + """Plot plane rotation (x, y, phi) + """ + x1 = x[:, 0] + x2 = x[:, 1] + x3 = x[:, 2] + xp1 = x[:, 3] + xp2 = x[:, 4] + xp3 = x[:, 5] + fig, ax1 = subplots() + ax1.set_title(title) + ax1.plot(t, x1, 'b-') + #ax1.plot(t, x3, 'b-') + ax1.set_xlabel('time t in s') + # Make the y-axis label and tick labels match the line color. + ax1.set_ylabel('x_1', color='b') + for tl in ax1.get_yticklabels(): + tl.set_color('b') + envelope = sqrt(square(x1)+square(x2)) + ax1.plot(t, envelope, 'b--', t, -envelope, 'b--') + ax2 = ax1.twinx() + ax2.plot(t, xp3, 'r') + ax2.set_ylabel('phi', color='r') + for tl in ax2.get_yticklabels(): + tl.set_color('r') + if max(xp3) < 2: + ax2.set_ylim([0,2]) + +f = disk +fnm = disk_nm +fnmmdk = disk_nmmdk + + +class TestODE(unittest.TestCase): + + Dt = .01 # Delta t + tend = .1 # t_end + #tend = 300 + nt = math.ceil(tend/Dt) # number of timesteps + t = linspace(0., tend, nt+1) # time vector + x0 = 0.0, 0.0, 0.0, 0.0, 0.0, 0.0 # initial conditions + p = .01, .002, .015 # parameter of the model + + def test_e1(self): + xe1 = e1(f, self.x0, self.t, *self.p) + #plotx1rphi(xe1, self.t, ("Euler (Runge-Kutta 1th order), + # increments: %d" % self.nt)) + #show() + self.assertTrue(allclose(xe1[:, 5], + [0., 0.00015, 0.0003, 0.00045, 0.0006, 0.00075, 0.0009, + 0.00105, 0.0012, 0.00135, 0.0015 ])) + + Dt_2 = Dt/5. + nt_2 = math.ceil(tend/Dt_2) + t_2 = linspace(0., tend, nt_2+1) + + def test_e1_2(self): + xe1_2 = e1(f, self.x0, self.t_2, *self.p) + #plotx1rphi(xe1_2, self.t_2, ("Euler (Runge-Kutta 1th order), + # increments: %d" % self.nt_2)) + #show() + self.assertTrue(allclose(xe1_2[:, 5], +[0.00000000e+00, 3.00000000e-05, 6.00000000e-05, 8.99999998e-05, + 1.19999999e-04, 1.49999998e-04, 1.79999995e-04, 2.09999992e-04, + 2.39999987e-04, 2.69999980e-04, 2.99999971e-04, 3.29999960e-04, + 3.59999947e-04, 3.89999931e-04, 4.19999913e-04, 4.49999891e-04, + 4.79999866e-04, 5.09999837e-04, 5.39999804e-04, 5.69999767e-04, + 5.99999726e-04, 6.29999681e-04, 6.59999630e-04, 6.89999575e-04, + 7.19999514e-04, 7.49999448e-04, 7.79999376e-04, 8.09999298e-04, + 8.39999214e-04, 8.69999123e-04, 8.99999026e-04, 9.29998921e-04, + 9.59998810e-04, 9.89998691e-04, 1.01999856e-03, 1.04999843e-03, + 1.07999829e-03, 1.10999814e-03, 1.13999798e-03, 1.16999781e-03, + 1.19999763e-03, 1.22999744e-03, 1.25999725e-03, 1.28999704e-03, + 1.31999682e-03, 1.34999660e-03, 1.37999636e-03, 1.40999611e-03, + 1.43999585e-03, 1.46999558e-03, 1.49999530e-03] + )) + + maxIterations = 1000 + tol = 1e-9 # against residuum + + def test_e2(self): + xe2 = e2(f, self.x0, self.t, *self.p) + #plotx1rphi(xe2, self.t, ("Runge-Kutta 2th order, + # increments: %d" % self.nt)) + #show() + self.assertTrue(allclose(xe2[:, 5], + [0., 0.00015, 0.0003, 0.00045, 0.0006, 0.00075, 0.0009, + 0.00105, 0.0012, 0.00135, 0.0015 ])) + + def test_e4(self): + xe4 = e4(f, self.x0, self.t, *self.p) + #plotx1rphi(xe4, self.t, ("Runge-Kutta 4th order, + # increments: %d" % self.nt)) + #show() + self.assertTrue(allclose(xe4[:, 5], + [0., 0.00015, 0.0003, 0.00045, 0.0006, 0.00075, 0.0009, + 0.00105, 0.0012, 0.00135, 0.0015 ])) + + def test_i1(self): + xi1, iterations = i1(f, self.x0, self.t, *self.p, + self.maxIterations, self.tol) + #plotx1rphi(xi1, self.t, ("Backward Euler, increments: %d, + # iterations: %d" % (self.nt, sum(iterations)))) + #show() + self.assertTrue(allclose(xi1[:, 5], + [0., 0.00015, 0.0003, 0.00045, 0.0006, 0.00075, 0.0009, + 0.00105, 0.0012, 0.00135, 0.0015 ])) + + gamma = .5 # newmark parameter for velocity + beta = .25 # newmark parameter for displacement + + def test_nm(self): + xnm, xpnm, xppnm, iterations = newmark_newtonraphson(fnm, + (0,0,0), (0,0,0), (0,0,0), self.t, *self.p, + self.gamma, self.beta, 1, self.tol) + #print(xnm) + #print(xpnm) + x = concatenate((xnm, xpnm), axis=1) + #plotx1rphi(x, self.t, ("Newmark, increments: %d, + # iterations: %d" % (self.nt, sum(iterations)))) + #show() + self.assertTrue(allclose(x[:, 5], +[0.00000000e+00, 7.49999925e-05, 2.24999951e-04, 3.74999839e-04, + 5.24999621e-04, 6.74999269e-04, 8.24998752e-04, 9.74998039e-04, + 1.12499710e-03, 1.27499591e-03, 1.42499444e-03] + )) + + def test_nm_2(self): + xnm, xpnm, xppnm, iterations = newmark_newtonraphson(fnm, + (0,0,0), (0,0,0), (0,0,0), self.t, *self.p, + self.gamma, self.beta, self.maxIterations, self.tol) + #print(xnm) + #print(xpnm) + x = concatenate((xnm, xpnm), axis=1) + #plotx1rphi(x, self.t, ("Newmark, increments: %d, + # iterations: %d" % (self.nt, sum(iterations)))) + #show() + self.assertTrue(allclose(x[:, 5], +[0.00000000e+00, 7.49999925e-05, 2.24999951e-04, 3.74999839e-04, + 5.24999621e-04, 6.74999269e-04, 8.24998752e-04, 9.74998039e-04, + 1.12499710e-03, 1.27499591e-03, 1.42499444e-03] + )) + + def test_nmmdk(self): + xnm, xpnm, xppnm, iterations = newmark_newtonraphson_rdk( + fnmmdk, (0,0,0), (0,0,0), (0,0,0), self.t, *self.p, + self.gamma, self.beta, 1, self.tol) + #print(xnm) + #print(xpnm) + x = concatenate((xnm, xpnm), axis=1) + #plotx1rphi(x, self.t, ("Newmark, increments: %d, + # iterations: %d" % (self.nt, sum(iterations)))) + #show() + self.assertTrue(allclose(x[:, 5], +[0.00000000e+00, 7.49999963e-05, 2.24999974e-04, 3.74999906e-04, + 5.24999764e-04, 6.74999516e-04, 8.24999134e-04, 9.74998586e-04, + 1.12499784e-03, 1.27499688e-03, 1.42499566e-03] + )) + + def test_nmmdk_2(self): + xnm, xpnm, xppnm, iterations = newmark_newtonraphson_rdk( + fnmmdk, (0,0,0), (0,0,0), (0,0,0), self.t, *self.p, + self.gamma, self.beta, 100, self.tol) + #print(xnm) + #print(xpnm) + x = concatenate((xnm, xpnm), axis=1) + #plotx1rphi(x, self.t, ("Newmark, increments: %d, + # iterations: %d" % (self.nt, sum(iterations)))) + #show() + self.assertTrue(allclose(x[:, 5], +[0.00000000e+00, 7.49999963e-05, 2.24999974e-04, 3.74999906e-04, + 5.24999764e-04, 6.74999516e-04, 8.24999134e-04, 9.74998586e-04, + 1.12499784e-03, 1.27499688e-03, 1.42499566e-03] + )) + + #from scipy.integrate import odeint + #xode = odeint(disk, x0, t, p, printmessg=True) + #plotx1rphi(xode, t, ("ODE, Inkremente: %d" % nt)) + #show() + + +if __name__ == '__main__': + unittest.main()