From 1de007a285ca9ad94fd10e56f3648ec14ab84b6f Mon Sep 17 00:00:00 2001 From: Daniel Weschke Date: Fri, 15 Nov 2019 16:05:54 +0100 Subject: [PATCH] add mathematical function to string function for braille and block characters --- docs/build/html/_modules/data.html | 15 +- docs/build/html/_modules/date.html | 2 +- docs/build/html/_modules/function.html | 166 +- docs/build/html/_modules/geometry.html | 2 +- docs/build/html/_modules/geometry_plot.html | 2 +- docs/build/html/_modules/index.html | 13 +- docs/build/html/_modules/mathematics.html | 2 +- docs/build/html/_modules/numerical/fit.html | 2 +- .../html/_modules/numerical/integration.html | 2 +- docs/build/html/_modules/numerical/ode.html | 2 +- .../html/_modules/numerical/ode_model.html | 2 +- docs/build/html/_modules/pylib/data.html | 305 ++++ docs/build/html/_modules/pylib/date.html | 221 +++ docs/build/html/_modules/pylib/function.html | 511 ++++++ docs/build/html/_modules/pylib/geometry.html | 610 +++++++ .../html/_modules/pylib/geometry_plot.html | 185 +++ .../html/_modules/pylib/mathematics.html | 116 ++ .../html/_modules/pylib/numerical/fit.html | 196 +++ .../_modules/pylib/numerical/integration.html | 250 +++ .../html/_modules/pylib/numerical/ode.html | 540 +++++++ .../_modules/pylib/numerical/ode_model.html | 219 +++ .../html/_modules/pylib/time_of_day.html | 253 +++ docs/build/html/_modules/time_of_day.html | 2 +- .../html/_sources/pylib.numerical.rst.txt | 46 + docs/build/html/_sources/pylib.rst.txt | 77 + docs/build/html/data.html | 2 +- docs/build/html/date.html | 2 +- docs/build/html/function.html | 135 +- docs/build/html/genindex.html | 340 +++- docs/build/html/geometry.html | 4 +- docs/build/html/geometry_plot.html | 2 +- docs/build/html/index.html | 2 +- docs/build/html/mathematics.html | 2 +- docs/build/html/modules.html | 2 +- docs/build/html/numerical.html | 2 +- docs/build/html/objects.inv | Bin 886 -> 1245 bytes docs/build/html/py-modindex.html | 98 +- docs/build/html/pylib.html | 1411 +++++++++++++++++ docs/build/html/pylib.numerical.html | 589 +++++++ docs/build/html/search.html | 2 +- docs/build/html/searchindex.js | 2 +- docs/build/html/time_of_day.html | 2 +- docs/source/pylib.numerical.rst | 46 + docs/source/pylib.rst | 77 + pylib/__init__.py | 12 + pylib/data.py | 13 + pylib/function.py | 166 +- vendor/drawille.py | 417 +++++ 48 files changed, 6987 insertions(+), 82 deletions(-) create mode 100644 docs/build/html/_modules/pylib/data.html create mode 100644 docs/build/html/_modules/pylib/date.html create mode 100644 docs/build/html/_modules/pylib/function.html create mode 100644 docs/build/html/_modules/pylib/geometry.html create mode 100644 docs/build/html/_modules/pylib/geometry_plot.html create mode 100644 docs/build/html/_modules/pylib/mathematics.html create mode 100644 docs/build/html/_modules/pylib/numerical/fit.html create mode 100644 docs/build/html/_modules/pylib/numerical/integration.html create mode 100644 docs/build/html/_modules/pylib/numerical/ode.html create mode 100644 docs/build/html/_modules/pylib/numerical/ode_model.html create mode 100644 docs/build/html/_modules/pylib/time_of_day.html create mode 100644 docs/build/html/_sources/pylib.numerical.rst.txt create mode 100644 docs/build/html/_sources/pylib.rst.txt create mode 100644 docs/build/html/pylib.html create mode 100644 docs/build/html/pylib.numerical.html create mode 100644 docs/source/pylib.numerical.rst create mode 100644 docs/source/pylib.rst create mode 100644 pylib/__init__.py create mode 100644 vendor/drawille.py diff --git a/docs/build/html/_modules/data.html b/docs/build/html/_modules/data.html index 3eb5069..c64a7a2 100644 --- a/docs/build/html/_modules/data.html +++ b/docs/build/html/_modules/data.html @@ -174,6 +174,19 @@ :returns: arithmetic bounded sequence :rtype: list """ + # example of seq(4, 0, -0.4) + # without round: + # [4.0, 3.6, 3.2, 2.8, 2.4, 2.0, 1.5999999999999996, + # 1.1999999999999997, 0.7999999999999998, 0.3999999999999999] + # with round: + # [4.0, 3.6, 3.2, 2.8, 2.4, 2.0, 1.6, 1.2, 0.8, 0.4] + # example of seq(4, 0, -0.41) + # without round: + # [4.0, 3.59, 3.18, 2.77, 2.3600000000000003, + # 1.9500000000000002, 1.54, 1.1300000000000003, + # 0.7200000000000002, 0.31000000000000005] + # with round: + # [4.0, 3.59, 3.18, 2.77, 2.36, 1.95, 1.54, 1.13, 0.72, 0.31] if stop is None: return seq(0, start, step) @@ -280,7 +293,7 @@ ©2019, Daniel Weschke. | - Powered by Sphinx 2.2.0 + Powered by Sphinx 2.2.1 & Alabaster 0.7.12 diff --git a/docs/build/html/_modules/date.html b/docs/build/html/_modules/date.html index a4598bc..9a842aa 100644 --- a/docs/build/html/_modules/date.html +++ b/docs/build/html/_modules/date.html @@ -209,7 +209,7 @@ ©2019, Daniel Weschke. | - Powered by Sphinx 2.2.0 + Powered by Sphinx 2.2.1 & Alabaster 0.7.12 diff --git a/docs/build/html/_modules/function.html b/docs/build/html/_modules/function.html index 1f35b3f..bf37352 100644 --- a/docs/build/html/_modules/function.html +++ b/docs/build/html/_modules/function.html @@ -147,7 +147,7 @@ linear speed. .. seealso:: - :meth:`function_cosine_wave_degree` + :meth:`cosine_wave` """ if degree: phi = math.radians(phi) @@ -179,7 +179,7 @@ time t .. seealso:: - :meth:`function_sine_wave_degree` + :meth:`sine_wave` """ if degree: phi = phi + 90 @@ -285,6 +285,166 @@ y = lambda theta: (R+r)*math.sin(theta) - d*math.sin((R+r)/r * theta) theta_end = 2*math.pi return x, y, theta_end + +
[docs]def to_str(f, x=None, x_0=0, x_1=1, t=None, h=10, w=80, density=1, char_set="line"): + """Represent functions as string frame with a specific character set. + which are normed to the range of [0, 1] to + + :param f: function or list of functions normed to the range of [0, 1] + :type f: function or list + :param h: number of chars in vertical direction + :type h: int + :param w: number of chars in horizontal direction + :type w: int + + :param char_set: either "braille" or "block". "braille" uses Unicode + Characters in the Braille Patterns Block (fisrt index U+2800, last + index U+28FF [CUDB]_) and the "block" uses part of the Unicode + Characters in the Block Elements Block (fisrt index U+2580, last + index U+259F [CUDB]_). Alias for braille is line and alias for + block is histogram + :type char_set: str + + Usage: + * case dependent arguments + + * 1 quasi line plot (braille characters) + f = lambda function (lambda x, t=0: ...) + x_1 = max x value + x_0 = min x value + t = time (animation) + * 2 histogram (block characters) + f = lambda function (lambda x, t=0: ...) + x_1 = max x value + x_0 = min x value + t = time (animation) + chart="histogram" + + * general arguments + w = window width in number of chars + density = number of data point per pixel (for line chart higher density makes thicker lines) + chart = either "line" or "histogram" + + + .. rubric:: Braille Patterns Block + + * Dots or pixels per character in vertical direction: 6 + * Dots or pixels per character in horizontal direction: 2 + + First dot (bottom left) is the zero (0) position of the + function. So, a function value of zero does not mean to have zero + dots but one. + Example of 3 columns and 3 rows (upside down view of 'normal' braille/drawille position) + + :: + + | ^ y axis + | | + | ,_____,,_____,,_____, + 7 + | * *|| * *|| * *| + 6 + | * *|| * *|| * *| + 5 + | * *|| * *|| * *| + 4 + | * *|| * *|| * *| + | ;=====;;=====;;=====; + 3 + | * *|| * *|| * *| + 2 + | * *|| * *|| * *| + 1 + | * *|| * *|| * *| + 0 + - | * *|| * *|| * *| ---> x axis + | ;=====;;=====;;=====; + -1 + | * *|| * *|| * *| + -2 + | * *|| * *|| * *| + -3 + | * *|| * *|| * *| + -4 + | * *|| * *|| * *| + | ````````````````````` + | | + `-----+--+---+--+---+--+------------- + -2 -1 0 1 2 3 + + + .. rubric:: Block Elements Block + + * Dots or pixels per character in vertical direction: 8 + * Dots or pixels per character in horizontal direction: 1 + + Example of 3 columns and 3 rows + + :: + + | ^ y axis + | | + | ,_____,,_____,,_____, + 15 + | --- || --- || --- | + 14 + | --- || --- || --- | + 13 + | --- || --- || --- | + 12 + | --- || --- || --- | + 11 + | --- || --- || --- | + 10 + | --- || --- || --- | + 9 + | --- || --- || --- | + 8 + | --- || --- || --- | + | ;=====;;=====;;=====; + 7 + | --- || --- || --- | + 6 + | --- || --- || --- | + 5 + | --- || --- || --- | + 4 + | --- || --- || --- | + 3 + | --- || --- || --- | + 2 + | --- || --- || --- | + 1 + | --- || --- || --- | + 0 + - | --- || --- || --- | ---> x axis + | ;=====;;=====;;=====; + -1 + | --- || --- || --- | + -2 + | --- || --- || --- | + -3 + | --- || --- || --- | + -4 + | --- || --- || --- | + -5 + | --- || --- || --- | + -6 + | --- || --- || --- | + -7 + | --- || --- || --- | + -8 + | --- || --- || --- | + | ````````````````````` + | | + `------+------+------+--------------- + -1 0 1 + + + .. rubric:: References + + .. [CUDB] `Unicode Database - Blocks <ftp://ftp.unicode.org/Public/UNIDATA/Blocks.txt>`_ + + + .. seealso:: + :meth:`pylib.function.transformation` + """ + # scale function to used chars and dots/pixel in y direction (4 for braille characters): from [0, 1] to [0, chars*4-1] + # negate the function because the y axis is pointing downwards: from [0, 1] to [-1, 0] or from [0, chars*4-1] to [-(chars*4-1), 0] + # and becasue of the negation shift the function by one dot/pixel, otherwise the function would need another char, because the 0 is on an another char on the "positive side". + # devide the time by the number of dots/pixel in x direction (2 for braille characters) + window_factor = w/(x_1-x_0) + frame = "" + if char_set in ["line", "braille"]: + pixels_horizontal = 2 + pixels_vertical = 4 + a = -(h*pixels_vertical-1) + b = 1/pixels_horizontal + f = transformation(f, a, b, 0, -1) + + canvas = drawille.Canvas() + # divide step width of the sequence by 2 (double density, 2 dots/pixel per char) + # multiplicate x by 2 (2 dots/pixel per char) + for x_i in seq(x_0*window_factor*pixels_horizontal, x_1*window_factor*pixels_horizontal, 1/density): + canvas.set(x_i, f(x_i, t)) + #frame = canvas.frame(min_x=a*pixel_per_char, min_y=1, max_x=b*pixel_per_char, max_y=21) + frame = canvas.frame() + elif char_set in ["histogram", "block"]: + pixels_horizontal = 1 + pixels_vertical = 8 + a = h*pixels_vertical-1 + f = transformation(f, a, 1, 0, 0) + + density = min(density, 1) # density max 1! + x = seq(x_0*window_factor, x_1*window_factor, 1/pixels_horizontal/density) + f = [f(xi, t) for xi in x] + frame = drawblock.histogram(f, x) + + return frame
@@ -339,7 +499,7 @@ ©2019, Daniel Weschke. | - Powered by Sphinx 2.2.0 + Powered by Sphinx 2.2.1 & Alabaster 0.7.12 diff --git a/docs/build/html/_modules/geometry.html b/docs/build/html/_modules/geometry.html index 8bfdf1f..fcc5e19 100644 --- a/docs/build/html/_modules/geometry.html +++ b/docs/build/html/_modules/geometry.html @@ -598,7 +598,7 @@ ©2019, Daniel Weschke. | - Powered by Sphinx 2.2.0 + Powered by Sphinx 2.2.1 & Alabaster 0.7.12 diff --git a/docs/build/html/_modules/geometry_plot.html b/docs/build/html/_modules/geometry_plot.html index 5340452..c81679a 100644 --- a/docs/build/html/_modules/geometry_plot.html +++ b/docs/build/html/_modules/geometry_plot.html @@ -173,7 +173,7 @@ ©2019, Daniel Weschke. | - Powered by Sphinx 2.2.0 + Powered by Sphinx 2.2.1 & Alabaster 0.7.12 diff --git a/docs/build/html/_modules/index.html b/docs/build/html/_modules/index.html index b525fb1..bd6a639 100644 --- a/docs/build/html/_modules/index.html +++ b/docs/build/html/_modules/index.html @@ -43,6 +43,17 @@
  • numerical.integration
  • numerical.ode
  • numerical.ode_model
  • +
  • pylib.data
  • +
  • pylib.date
  • +
  • pylib.function
  • +
  • pylib.geometry
  • +
  • pylib.geometry_plot
  • +
  • pylib.mathematics
  • +
  • pylib.numerical.fit
  • +
  • pylib.numerical.integration
  • +
  • pylib.numerical.ode
  • +
  • pylib.numerical.ode_model
  • +
  • pylib.time_of_day
  • time_of_day
  • @@ -96,7 +107,7 @@ ©2019, Daniel Weschke. | - Powered by Sphinx 2.2.0 + Powered by Sphinx 2.2.1 & Alabaster 0.7.12 diff --git a/docs/build/html/_modules/mathematics.html b/docs/build/html/_modules/mathematics.html index 2a2d031..cb74151 100644 --- a/docs/build/html/_modules/mathematics.html +++ b/docs/build/html/_modules/mathematics.html @@ -104,7 +104,7 @@ ©2019, Daniel Weschke. | - Powered by Sphinx 2.2.0 + Powered by Sphinx 2.2.1 & Alabaster 0.7.12 diff --git a/docs/build/html/_modules/numerical/fit.html b/docs/build/html/_modules/numerical/fit.html index 917d51e..6536972 100644 --- a/docs/build/html/_modules/numerical/fit.html +++ b/docs/build/html/_modules/numerical/fit.html @@ -184,7 +184,7 @@ ©2019, Daniel Weschke. | - Powered by Sphinx 2.2.0 + Powered by Sphinx 2.2.1 & Alabaster 0.7.12 diff --git a/docs/build/html/_modules/numerical/integration.html b/docs/build/html/_modules/numerical/integration.html index cb6b130..9e46b75 100644 --- a/docs/build/html/_modules/numerical/integration.html +++ b/docs/build/html/_modules/numerical/integration.html @@ -238,7 +238,7 @@ ©2019, Daniel Weschke. | - Powered by Sphinx 2.2.0 + Powered by Sphinx 2.2.1 & Alabaster 0.7.12 diff --git a/docs/build/html/_modules/numerical/ode.html b/docs/build/html/_modules/numerical/ode.html index 0dace0f..5387e63 100644 --- a/docs/build/html/_modules/numerical/ode.html +++ b/docs/build/html/_modules/numerical/ode.html @@ -528,7 +528,7 @@ ©2019, Daniel Weschke. | - Powered by Sphinx 2.2.0 + Powered by Sphinx 2.2.1 & Alabaster 0.7.12 diff --git a/docs/build/html/_modules/numerical/ode_model.html b/docs/build/html/_modules/numerical/ode_model.html index 67b23f7..14cc65d 100644 --- a/docs/build/html/_modules/numerical/ode_model.html +++ b/docs/build/html/_modules/numerical/ode_model.html @@ -207,7 +207,7 @@ ©2019, Daniel Weschke. | - Powered by Sphinx 2.2.0 + Powered by Sphinx 2.2.1 & Alabaster 0.7.12 diff --git a/docs/build/html/_modules/pylib/data.html b/docs/build/html/_modules/pylib/data.html new file mode 100644 index 0000000..6c1bef2 --- /dev/null +++ b/docs/build/html/_modules/pylib/data.html @@ -0,0 +1,305 @@ + + + + + + + pylib.data — pylib 2019.5.19 documentation + + + + + + + + + + + + + + + + + + + + +
    +
    +
    + + +
    + +

    Source code for pylib.data

    +#!/usr/bin/env python
    +# -*- coding: utf-8 -*-
    +"""Read and write data to or from file and manipulate data structures.
    +
    +:Date: 2019-10-11
    +
    +.. module:: data
    +  :platform: *nix, Windows
    +  :synopsis: Handle data files and structures.
    +
    +.. moduleauthor:: Daniel Weschke <daniel.weschke@directbox.de>
    +"""
    +import math
    +import pickle
    +
    +
    [docs]def read(file_name, x_column, y_column, default=None, verbose=False): + """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 + :param default: return object if data loading fails + :type default: object + :param verbose: verbose information (default = False) + :type verbose: bool + + :returns: x and y + :rtype: tuple(list, list) + """ + import re + + x = default + y = default + + if verbose: + print('check if data is available') + try: + file = open(file_name) + x = [] + y = [] + for row in file: + fields = re.split(r'\s+', row.strip()) + x.append(float(fields[x_column])) + y.append(float(fields[y_column])) + file.close() + except IOError: + if verbose: + print('data file not found') + return x, y
    + +
    [docs]def write(file_name, data): + """Write ascii file. + + :param file_name: file to write + :type file_name: str + :param data: data to write + :type data: str + """ + with open(file_name, 'w') as file: + file.write(data)
    + +
    [docs]def load(file_name, default=None, verbose=False): + """Load stored program objects from binary file. + + :param file_name: file to load + :type file_name: str + :param default: return object if data loading fails + :type default: object + :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: + # one load for every dump is needed to load all the data + object_data = pickle.load(input) + if verbose: + print('found:') + print(object_data) + except IOError: + object_data = default + if verbose: + print('no saved datas found') + return object_data
    + +
    [docs]def 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: + # every dump needs a load + pickle.dump(object_data, output, pickle.HIGHEST_PROTOCOL)
    + +
    [docs]def fold_list(lst, n): + """Convert one-dimensional kx1 array (list) to two-dimensional mxn + array. m = k / n + + :param lst: list to convert + :type lst: list + :param n: length of the second dimenson + :type n: int + + :returns: two-dimensional array (list of lists) + :rtype: list + """ + k = len(lst) + if k % n == 0: + length = int(k/n) + return [lst[i*n:i*n+n] for i in range(length)]
    + +
    [docs]def seq(start, stop=None, step=1): + r"""Create an arithmetic bounded sequence. + + The sequence is one of the following; + + - empty :math:`\{\}=\emptyset`, if start and stop are the same + - degenerate :math:`\{a\}`, if the sequence has only one element. + - left-close and right-open :math:`[a, b)` + + :param start: start of the sequence, the lower bound. If only start + is given than it is interpreted as stop and start will be 0. + :type start: int or float + :param stop: stop of sequence, the upper bound. + :type stop: int or float + :param step: step size, the common difference (constant difference + between consecutive terms). + :type step: int or float + :returns: arithmetic bounded sequence + :rtype: list + """ + # example of seq(4, 0, -0.4) + # without round: + # [4.0, 3.6, 3.2, 2.8, 2.4, 2.0, 1.5999999999999996, + # 1.1999999999999997, 0.7999999999999998, 0.3999999999999999] + # with round: + # [4.0, 3.6, 3.2, 2.8, 2.4, 2.0, 1.6, 1.2, 0.8, 0.4] + # example of seq(4, 0, -0.41) + # without round: + # [4.0, 3.59, 3.18, 2.77, 2.3600000000000003, + # 1.9500000000000002, 1.54, 1.1300000000000003, + # 0.7200000000000002, 0.31000000000000005] + # with round: + # [4.0, 3.59, 3.18, 2.77, 2.36, 1.95, 1.54, 1.13, 0.72, 0.31] + if stop is None: + return seq(0, start, step) + + start_str = str(start) + start_exp = 0 + if '.' in start_str: + start_exp = len(start_str.split('.')[1]) + + step_str = str(step) + step_exp = 0 + if '.' in step_str: + step_exp = len(step_str.split('.')[1]) + + exponent = max(start_exp, step_exp) # no stop because it is an open bound + + n = int(math.ceil((stop - start)/float(step))) + lst = [] + if n > 0: + lst = [round(start + step*i, exponent) for i in range(n)] + return lst
    + +
    [docs]def unique_ending(ids, n=1): + """From id list get list with unique ending. + + :param ids: ids + :type ids: list + :param n: minumum chars or ints + :type n: int + + :returns: unique ending of ids + :rtype: list + """ + if ids is not None: + x = [idi[-n:] for idi in ids] + if len(x) > len(set(x)): + return unique_ending(ids, n+1) + else: + return x
    + +
    [docs]def get_id(ids, uide): + """Get full id from unique id ending. + + :param ids: ids + :type ids: list + :param uide: unique id ending + :type uide: str + + :returns: full id + :rtype: str or int + """ + # take first element, because we know it is a unique ending + return [idi for idi in ids if idi.endswith(uide)][0]
    +
    + +
    + +
    +
    + +
    +
    + + + + + + + \ No newline at end of file diff --git a/docs/build/html/_modules/pylib/date.html b/docs/build/html/_modules/pylib/date.html new file mode 100644 index 0000000..9c6de39 --- /dev/null +++ b/docs/build/html/_modules/pylib/date.html @@ -0,0 +1,221 @@ + + + + + + + pylib.date — pylib 2019.5.19 documentation + + + + + + + + + + + + + + + + + + + + +
    +
    +
    + + +
    + +

    Source code for pylib.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>
    +"""
    +
    +
    [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/pylib/function.html b/docs/build/html/_modules/pylib/function.html new file mode 100644 index 0000000..27f9fa0 --- /dev/null +++ b/docs/build/html/_modules/pylib/function.html @@ -0,0 +1,511 @@ + + + + + + + pylib.function — pylib 2019.5.19 documentation + + + + + + + + + + + + + + + + + + + + +
    +
    +
    + + +
    + +

    Source code for pylib.function

    +#!/usr/bin/env python
    +# -*- coding: utf-8 -*-
    +"""Mathematical equations.
    +
    +:Date: 2019-11-04
    +
    +.. module:: function
    +  :platform: *nix, Windows
    +  :synopsis: Mathematical equations.
    +
    +.. moduleauthor:: Daniel Weschke <daniel.weschke@directbox.de>
    +"""
    +import math
    +from pylib.mathematics import lcm
    +
    +
    [docs]def transformation(f, scale_vertical=1, scale_horizontal=1, + shift_horizontal=0, shift_vertical=0): + r"""Transform functions. + + :param f: function or list of functions + :type f: function or list + :param scale_vertical: "a" scale factor in vertical direction (default + = 1) + :type height: float + :param scale_horizontal: "b" scale factor in horizontal direction + (default = 1) + :type height: float + :param shift_horizontal: "c" shift factor in horizontal direction + (default = 0) + :type height: float + :param shift_vertical: "d" shift factor in vertical direction (default + = 0) + :type height: float + + :returns: transformed function or list of transformed functions + :rtype: function or list + + .. math:: + y = a \, f(b\,(x-c)) + d + """ + # shorter variables + a = scale_vertical + b = scale_horizontal + c = shift_horizontal + d = shift_vertical + + # check if f is a function than put it in a list and return only + # the function, not the one element list + if callable(f): + return transformation( + [f], scale_vertical=a, scale_horizontal=b, shift_horizontal=c, shift_vertical=d)[0] + + # otherwise assume list of functions + if not f: # if f is empty. End of the recursive fucntion + return [] + return [lambda x, t: a*f[0](b*(x-c), t)+d] +\ + transformation( + f[1:], scale_vertical=a, scale_horizontal=b, shift_horizontal=c, shift_vertical=d)
    + +
    [docs]def sine_wave(A=1, k=1, f=1, phi=0, D=0, degree=False): + r"""A sine wave or sinusoid is a mathematical curve that describes a + smooth periodic oscillation. + + :param A: amplitude + :type A: float or int + :param k: (angular) wave number + :type k: float or int + :param f: ordinary frequency + :type f: float or int + :param phi: phase + :type phi: float or int + :param D: non-zero center amplitude + :type D: float or int + :param degree: boolean to switch between radians and degree. If + False phi is interpreted in radians and if True then phi is + interpreted in degrees. + :type degree: bool + + :results: sine wave function of spatial variable x and optional + time t + + In general, the function is: + + .. math:: + y(x,t) = A\sin(kx + 2\pi f t + \varphi) + D \\ + y(x,t) = A\sin(kx + \omega t + \varphi) + D + + where: + + * A, amplitude, the peak deviation of the function from zero. + * f, ordinary frequency, the number of oscillations (cycles) that + occur each second of time. + * ω = 2πf, angular frequency, the rate of change of the function + argument in units of radians per second. If ω < 0 the wave is + moving to the right, if ω > 0 the wave is moving to the left. + * φ, phase, specifies (in radians) where in its cycle the + oscillation is at t = 0. + * x, spatial variable that represents the position on the + dimension on which the wave propagates. + * k, characteristic parameter called wave number (or angular wave + number), which represents the proportionality between the + angular frequency ω and the linear speed (speed of propagation) + ν. + * D, non-zero center amplitude. + + The wavenumber is related to the angular frequency by: + + .. math:: + k={\omega \over v}={2\pi f \over v}={2\pi \over \lambda } + + where λ (lambda) is the wavelength, f is the frequency, and v is the + linear speed. + + .. seealso:: + :meth:`cosine_wave` + """ + if degree: + phi = math.radians(phi) + return lambda x, t=0: A*math.sin(k*x + 2*math.pi*f*t + phi) + D
    + +
    [docs]def cosine_wave(A=1, k=1, f=1, phi=0, D=0, degree=False): + r"""A cosine wave is said to be sinusoidal, because, + :math:`\cos(x) = \sin(x + \pi/2)`, which is also a sine wave with a + phase-shift of π/2 radians. Because of this head start, it is often + said that the cosine function leads the sine function or the sine + lags the cosine. + + :param A: amplitude + :type A: float or int + :param k: (angular) wave number + :type k: float or int + :param f: ordinary frequency + :type f: float or int + :param phi: phase + :type phi: float or int + :param D: non-zero center amplitude + :type D: float or int + :param degree: boolean to switch between radians and degree. If + False phi is interpreted in radians and if True then phi is + interpreted in degrees. + :type degree: bool + + :results: sine wave function of spatial variable x and optional + time t + + .. seealso:: + :meth:`sine_wave` + """ + if degree: + phi = phi + 90 + else: + phi = phi + math.pi/2 + return sine_wave(A=A, k=k, f=f, phi=phi, D=D, degree=degree)
    + + +# +# Parametric equations +# roulette +# + +
    [docs]def hypotrochoid(R, r, d): + r"""Hypotrochoid + + A point is attached with a distance d from the center of a circle + of radius r. The circle is rolling around the inside of a fixed + circle of radius R. + + :param R: radius of the fixed exterior circle + :type R: float + :param r: radius of the rolling circle inside of the fixed circle + :typre r: float + :param d: distance from the center of the interior circle + :type d: float + + :results: functions for x of theta and y of theta + :rtype: tuple + + .. math:: + x(\theta) = (R - r)\cos\theta + d\cos\left(\frac{R-r}{r}\theta\right) \\ + y(\theta) = (R - r)\sin\theta - d\sin\left(\frac{R-r}{r}\theta\right) \\ + \theta = \left[0, 2\pi\frac{\mathrm{lcm}(r, R)}{R}\right] + + :: + + * * * + * R * + * * + * * * * + * * r ** + * * .... * + * * d * + * * ** + * * * * + * * + * * + * * * + + >>> x, y = hyotrochoid(20, 6, 6)[:1] + >>> x, y, theta_end = hyotrochoid(20, 6, 6) + + .. seealso:: + :meth:`mathematics.lcm` + """ + x = lambda theta: (R-r)*math.cos(theta) + d*math.cos((R-r)/r * theta) + y = lambda theta: (R-r)*math.sin(theta) - d*math.sin((R-r)/r * theta) + theta_end = 2*math.pi*lcm(r, R)/R + return x, y, theta_end
    + +
    [docs]def epitrochoid(R, r, d): + r"""Epitrochoid + + A point is attached with a distance d from the center of a circle + of radius r. The circle is rolling around the outside of a fixed + circle of radius R. + + :param R: radius of the fixed interior circle + :type R: float + :param r: radius of the rolling circle outside of the fixed circle + :typre r: float + :param d: distance from the center of the exterior circle + :type d: float + + :results: functions for x of theta and y of theta + :rtype: tuple + + .. math:: + x(\theta) = (R + r)\cos\theta - d\cos\left(\frac{R+r}{r}\theta\right) \\ + y(\theta) = (R + r)\sin\theta - d\sin\left(\frac{R+r}{r}\theta\right) \\ + \theta = \left[0, 2\pi\right] + + :: + + * * * + * R * + * * + * * * * + * * * r * + * ** .... * + * ** d * + * * * * + * * * * + * * + * * + * * * + + >>> x, y = epitrochoid(3, 1, 0.5)[:1] + >>> x, y, theta_end = epitrochoid(3, 1, 0.5) + """ + x = lambda theta: (R+r)*math.cos(theta) - d*math.cos((R+r)/r * theta) + y = lambda theta: (R+r)*math.sin(theta) - d*math.sin((R+r)/r * theta) + theta_end = 2*math.pi + return x, y, theta_end
    + +
    [docs]def to_str(f, x=None, x_0=0, x_1=1, t=None, h=10, w=80, density=1, char_set="line"): + """Represent functions as string frame with a specific character set. + which are normed to the range of [0, 1] to + + :param f: function or list of functions normed to the range of [0, 1] + :type f: function or list + :param h: number of chars in vertical direction + :type h: int + :param w: number of chars in horizontal direction + :type w: int + + :param char_set: either "braille" or "block". "braille" uses Unicode + Characters in the Braille Patterns Block (fisrt index U+2800, last + index U+28FF [CUDB]_) and the "block" uses part of the Unicode + Characters in the Block Elements Block (fisrt index U+2580, last + index U+259F [CUDB]_). Alias for braille is line and alias for + block is histogram + :type char_set: str + + Usage: + * case dependent arguments + + * 1 quasi line plot (braille characters) + f = lambda function (lambda x, t=0: ...) + x_1 = max x value + x_0 = min x value + t = time (animation) + * 2 histogram (block characters) + f = lambda function (lambda x, t=0: ...) + x_1 = max x value + x_0 = min x value + t = time (animation) + chart="histogram" + + * general arguments + w = window width in number of chars + density = number of data point per pixel (for line chart higher density makes thicker lines) + chart = either "line" or "histogram" + + + .. rubric:: Braille Patterns Block + + * Dots or pixels per character in vertical direction: 6 + * Dots or pixels per character in horizontal direction: 2 + + First dot (bottom left) is the zero (0) position of the + function. So, a function value of zero does not mean to have zero + dots but one. + Example of 3 columns and 3 rows (upside down view of 'normal' braille/drawille position) + + :: + + | ^ y axis + | | + | ,_____,,_____,,_____, + 7 + | * *|| * *|| * *| + 6 + | * *|| * *|| * *| + 5 + | * *|| * *|| * *| + 4 + | * *|| * *|| * *| + | ;=====;;=====;;=====; + 3 + | * *|| * *|| * *| + 2 + | * *|| * *|| * *| + 1 + | * *|| * *|| * *| + 0 + - | * *|| * *|| * *| ---> x axis + | ;=====;;=====;;=====; + -1 + | * *|| * *|| * *| + -2 + | * *|| * *|| * *| + -3 + | * *|| * *|| * *| + -4 + | * *|| * *|| * *| + | ````````````````````` + | | + `-----+--+---+--+---+--+------------- + -2 -1 0 1 2 3 + + + .. rubric:: Block Elements Block + + * Dots or pixels per character in vertical direction: 8 + * Dots or pixels per character in horizontal direction: 1 + + Example of 3 columns and 3 rows + + :: + + | ^ y axis + | | + | ,_____,,_____,,_____, + 15 + | --- || --- || --- | + 14 + | --- || --- || --- | + 13 + | --- || --- || --- | + 12 + | --- || --- || --- | + 11 + | --- || --- || --- | + 10 + | --- || --- || --- | + 9 + | --- || --- || --- | + 8 + | --- || --- || --- | + | ;=====;;=====;;=====; + 7 + | --- || --- || --- | + 6 + | --- || --- || --- | + 5 + | --- || --- || --- | + 4 + | --- || --- || --- | + 3 + | --- || --- || --- | + 2 + | --- || --- || --- | + 1 + | --- || --- || --- | + 0 + - | --- || --- || --- | ---> x axis + | ;=====;;=====;;=====; + -1 + | --- || --- || --- | + -2 + | --- || --- || --- | + -3 + | --- || --- || --- | + -4 + | --- || --- || --- | + -5 + | --- || --- || --- | + -6 + | --- || --- || --- | + -7 + | --- || --- || --- | + -8 + | --- || --- || --- | + | ````````````````````` + | | + `------+------+------+--------------- + -1 0 1 + + + .. rubric:: References + + .. [CUDB] `Unicode Database - Blocks <ftp://ftp.unicode.org/Public/UNIDATA/Blocks.txt>`_ + + + .. seealso:: + :meth:`pylib.function.transformation` + """ + # scale function to used chars and dots/pixel in y direction (4 for braille characters): from [0, 1] to [0, chars*4-1] + # negate the function because the y axis is pointing downwards: from [0, 1] to [-1, 0] or from [0, chars*4-1] to [-(chars*4-1), 0] + # and becasue of the negation shift the function by one dot/pixel, otherwise the function would need another char, because the 0 is on an another char on the "positive side". + # devide the time by the number of dots/pixel in x direction (2 for braille characters) + window_factor = w/(x_1-x_0) + frame = "" + if char_set in ["line", "braille"]: + pixels_horizontal = 2 + pixels_vertical = 4 + a = -(h*pixels_vertical-1) + b = 1/pixels_horizontal + f = transformation(f, a, b, 0, -1) + + canvas = drawille.Canvas() + # divide step width of the sequence by 2 (double density, 2 dots/pixel per char) + # multiplicate x by 2 (2 dots/pixel per char) + for x_i in seq(x_0*window_factor*pixels_horizontal, x_1*window_factor*pixels_horizontal, 1/density): + canvas.set(x_i, f(x_i, t)) + #frame = canvas.frame(min_x=a*pixel_per_char, min_y=1, max_x=b*pixel_per_char, max_y=21) + frame = canvas.frame() + elif char_set in ["histogram", "block"]: + pixels_horizontal = 1 + pixels_vertical = 8 + a = h*pixels_vertical-1 + f = transformation(f, a, 1, 0, 0) + + density = min(density, 1) # density max 1! + x = seq(x_0*window_factor, x_1*window_factor, 1/pixels_horizontal/density) + f = [f(xi, t) for xi in x] + frame = drawblock.histogram(f, x) + + return frame
    +
    + +
    + +
    +
    + +
    +
    + + + + + + + \ No newline at end of file diff --git a/docs/build/html/_modules/pylib/geometry.html b/docs/build/html/_modules/pylib/geometry.html new file mode 100644 index 0000000..3787977 --- /dev/null +++ b/docs/build/html/_modules/pylib/geometry.html @@ -0,0 +1,610 @@ + + + + + + + pylib.geometry — pylib 2019.5.19 documentation + + + + + + + + + + + + + + + + + + + + +
    +
    +
    + + +
    + +

    Source code for pylib.geometry

    +#!/usr/bin/env python
    +# -*- coding: utf-8 -*-
    +"""2D geometry objects.
    +
    +:Date: 2019-08-28
    +
    +.. module:: geometry
    +  :platform: *nix, Windows
    +  :synopsis: Geometry objects.
    +
    +.. moduleauthor:: Daniel Weschke <daniel.weschke@directbox.de>
    +"""
    +import math
    +import numpy as np
    +
    +
    +
    [docs]def distance(point1, point2): + """Distance between two points (or length of a straight line). + + :param point1: first point (first end point of straight line) + :type point1: tuple + :param point2: second point (second end point of straight line) + :type point2: tuple + + :returns: distance between the two points + :rtype: float + """ + return math.sqrt((point2[0]-point1[0])**2 + (point2[1]-point1[1])**2)
    + + +
    [docs]def angle(point1, point2=None): + """Angle of point or between two points. + + :param point1: (first) point + :type point1: tuple + :param point2: second point (default = None) + :type point2: tuple + + :returns: angle of point or between two points + :rtype: float + """ + if point2 is None: + return math.atan2(point1[1], point1[0]) + return math.atan2(point2[1]-point1[1], point2[0]-point1[0])
    + + +
    [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 + + .. seealso:: + :meth:`translate_xy` + """ + vx, vy = vec + return tuple([(x+vx, y+vy) for (x, y) in pts])
    + + +
    [docs]def translate_xy(vec, x, y): + """Translate a point or polygon by a given vector. + + :param vec: translation vector + :type vec: tuple + :param x: points to translate + :type x: int or float or list + :param y: points to translate + :type y: int or float or list + + :returns: (x', y') + :rtype: tuple + + .. seealso:: + :meth:`translate` + """ + vx, vy = vec + + if not hasattr(x, "__len__"): + x = [x] + + if not hasattr(y, "__len__"): + y = [y] + + xp = [xi+vx for xi in x] + yp = [yi+vy for yi in y] + + # no list if it is only one value + if len(xp) == 1: + return xp[0], yp[0] + + return xp, yp
    + + +
    [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 + + .. seealso:: + :meth:`rotate_xy` + """ + ox, oy = origin + + # add first point to the end + if "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]) + + # no tuple in tuple if it is only one point + 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 rotate_xy(origin, angle, x, y, **kwargs): + """Rotate x and y coordinates 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 x: x coordinates + :type x: int or float or list + :param y: y coordinates + :type y: int or float or list + :param `**kwargs`: options + + .. seealso:: + :meth:`rotate` + """ + ox, oy = origin + + if not hasattr(x, "__len__"): + x = [x] + + if not hasattr(y, "__len__"): + y = [y] + + # add first point to the end + if "closed" in kwargs and kwargs["closed"] is True: + x.append(x[0]) + y.append(y[0]) + + x_result = [ox + math.cos(angle) * (xi - ox) - math.sin(angle) * (yi - oy) + for xi, yi in zip(x, y)] + + y_result = [oy + math.sin(angle) * (xi - ox) + math.cos(angle) * (yi - oy) + for xi, yi in zip(x, y)] + + # no list if it is only one value + if len(x_result) == 1: + return x_result[0], y_result[0] + + return x_result, y_result
    + + +
    [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)
    + + +
    [docs]def lines(pts, **kwargs): + """Lines defined by a list of end points. + + :param pts: list of points in absolute global coordinate system. If + keyword inc is given than the inc decides what the left and the + right end point of the line is, otherwise it is assumed that the + points build a solid line, that is lines between the given points + in given order. + :type pts: list + + :param `**kwargs`: options: + + * deformation -- list of points. Additional deformation + (translation) at point. + * factor -- factor of the deformation (default = 1). + * inc -- the incidence table, a list of 2 element lists. The inc + decides what the left and the right end point of the line is. + * index_offset -- starting index of lists (default = 0). + + :returns: list of endpoints for each line; + [((point1_x, point1_y), (point2_x, point2_y)), + (p1, p2), + ...] + :rtype: list + + .. seealso:: + :meth:`~geometry_plot.plot_lines` of the :mod:`geometry_plot` + module to plot the lines + """ + if 'index_offset' not in kwargs: + kwargs['index_offset'] = 0 + if 'deformation' in kwargs: + if 'factor' not in kwargs: + kwargs['factor'] = 1 + pts = [(p[0]+d[0]*kwargs['factor'], p[1]+d[1]*kwargs['factor']) for + p, d in zip(pts, kwargs['deformation'])] + if 'inc' in kwargs: + return [(pts[l-kwargs['index_offset']], + pts[r-kwargs['index_offset']]) for l, r in kwargs['inc']] + return list(zip(pts[:-1], pts[1:]))
    + + +
    [docs]def cubics(pts, **kwargs): + """Cubic lines defined by a list of two end points. The deformation + as displacement and rotation (radians) is defined element wise as + keyword argument deformation or global node wise as + global_deformation. The global coordinate system is xy. x in the + right direction and y in the top direction. + + :param pts: list of points in absolute global coordinate system. If + keyword inc is given than the inc decides what the left and the + right end point of the line is, otherwise it is assumed that the + points build a solid line, that is lines between the given points + in given order. + :type pts_rot: list + + :param `**kwargs`: options: + + * deformation -- list of deformation element wise. Additional + deformation (translation and rotation in radians) at element + left and right node. + * rotation_plane -- rotation plane of the element wise + deformation defined by a string; either 'xy' or 'xz' (default + = 'xy'). x in the right direction and y in the top direction + or z in the bottom direction. + * global_deformation -- list of deformation global node wise. + Additional deformation (horizontal translation, vertical + translation and rotation in radians) at node. + * factor -- factor of the derformation (default = 1). + * inc -- the incidence table, a list of 2 element lists. The inc + decides what the left and the right end point of the line is. + * index_offset -- starting index of lists (default = 0). + + :returns: list of endpoints for each line; + [(((point1_x, point1_y) angle1), ((point2_x, point2_y), angle2), + (p1, angle1, p2, angle2), + ...] + :rtype: list + """ + if 'index_offset' not in kwargs: + kwargs['index_offset'] = 0 + if 'deformation' in kwargs or 'global_deformation' in kwargs: + if 'factor' not in kwargs: + kwargs['factor'] = 1 + if 'inc' in kwargs: + if 'global_deformation' in kwargs: + lr = [(pts[l-kwargs['index_offset']], + pts[r-kwargs['index_offset']]) for l, r in kwargs['inc']] + ang = [angle(l, r) for l, r in lr] + # system deformation + U = kwargs['global_deformation'] + if 'rotation_plane' in kwargs and 'xz' == kwargs['rotation_plane']: + # system deformation left X Z RY right X Z RY element wise + # Z downwards -> convert to X Y RZ + Ue = [[ U[(l-kwargs['index_offset'])][0], + -U[(l-kwargs['index_offset'])][1], + U[(l-kwargs['index_offset'])][2], + U[(r-kwargs['index_offset'])][0], + -U[(r-kwargs['index_offset'])][1], + U[(r-kwargs['index_offset'])][2]] for l, r in kwargs['inc']] + else: + # system deformation left X Y RZ right X Y RZ element wise + Ue = [[U[(l-kwargs['index_offset'])][0], + U[(l-kwargs['index_offset'])][1], + U[(l-kwargs['index_offset'])][2], + U[(r-kwargs['index_offset'])][0], + U[(r-kwargs['index_offset'])][1], + U[(r-kwargs['index_offset'])][2]] for l, r in kwargs['inc']] + # element deformation, X Y RZ to x r rz + # back transformation T^T = [[c, s, 0], [-s, c, 0], [0, 0, 1]] + u = [[( math.cos(angi)*Uei[0]+math.sin(angi)*Uei[1])*kwargs['factor'], + (-math.sin(angi)*Uei[0]+math.cos(angi)*Uei[1])*kwargs['factor'], + Uei[2] *kwargs['factor'], + ( math.cos(angi)*Uei[3]+math.sin(angi)*Uei[4])*kwargs['factor'], + (-math.sin(angi)*Uei[3]+math.cos(angi)*Uei[4])*kwargs['factor'], + Uei[5] *kwargs['factor']] + for Uei, angi in zip(Ue, ang)] + else: # deformation + # the deformation is in element coordinate system, therefore the angle is needed + if 'rotation_plane' in kwargs and 'xz' == kwargs['rotation_plane']: + u = [[ ue[0]*kwargs['factor'], + -ue[1]*kwargs['factor'], + ue[2]*kwargs['factor'], + ue[3]*kwargs['factor'], + -ue[4]*kwargs['factor'], + ue[5]*kwargs['factor']] for ue in kwargs['deformation']] + else: + u = [[ui*kwargs['factor'] for ui in ue] for ue in kwargs['deformation']] + return [(pts[l-kwargs['index_offset']], + pts[r-kwargs['index_offset']], + d) for (l, r), d in zip(kwargs['inc'], u)] + return list(zip(pts[:-1], pts[1:]))
    + + +
    [docs]def interpolate_hermite(lvd, lr, rvd, rr, lhd=0, rhd=0, scale_x=1, scale_y=1, samples=10): + r"""Interpolate cubic line with hermite boundary conditions. + + :param lvd: left vertcal deflection + :type lvd: int or float + :param lr: left rotation + :type lr: int or float + :param rvd: right vertical deflection + :type rvd: int or float + :param rr: right rotation + :type rr: int or float + :param lhd: left horizontal deformation (default = 0) + :type lhd: int or float + :param rhd: right horizontal deformation (default = 0) + :type rhd: int or float + :param scale_x: length of element (default = 1) + :type scale_x: int or float + :param scale_y: factor of the deformation (default = 1). + This does not change the length. + :type scale_y: int or float + :param samples: number of sampling points (default = 10) + :type samples: int + + .. math:: + s = \frac{x - x_1}{L} \\ + x = s\,L + x_1 + + """ + L = scale_x + Lp = L + rhd - lhd + + # x=[0,1] in non-dimensional coordinates + x = np.linspace(0, 1, num=samples) + N1 = 1 - 3*x**2 + 2*x**3 + N2 = ( x - 2*x**2 + x**3)*Lp + N3 = 3*x**2 - 2*x**3 + N4 = ( - x**2 + x**3)*Lp + x = x*Lp + + + # x=[0,L] in global coordinates + x = np.linspace(0, Lp, num=samples) + N1 = 1 - 3*x**2/Lp**2 + 2*x**3/Lp**3 + N2 = x - 2*x**2/Lp + x**3/Lp**2 + N3 = 3*x**2/Lp**2 - 2*x**3/Lp**3 + N4 = - x**2/Lp + x**3/Lp**2 + + + v = N1*lvd + N2*lr + N3*rvd + N4*rr + x = x + lhd + y = v*scale_y + + return x, y
    + + +# +# matplotlib format, return lists for x and y +# + +
    [docs]def line(point1, point2, samples=2): + """Line defined by two end points. + + .. 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 (default = 2) + :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 + + :Example: + + >>> x, y = line((0, 0), (1, 0)) + >>> print(x, y) + ((0, 1), (0, 0)) + """ + p1x, p1y = point1 + p2x, p2y = point2 + + denominator = (p1x - p2x) + + if samples > 2 and denominator > 0: + x = np.linspace(p1x, p2x, samples) + 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=10): + """Cubic line defined by two end points and the rotation in radians + at the points. + + :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 (default = 10) + :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): + """Cubic line defined by two end points and the roation in degree + at the points. + + :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/pylib/geometry_plot.html b/docs/build/html/_modules/pylib/geometry_plot.html new file mode 100644 index 0000000..46e972c --- /dev/null +++ b/docs/build/html/_modules/pylib/geometry_plot.html @@ -0,0 +1,185 @@ + + + + + + + pylib.geometry_plot — pylib 2019.5.19 documentation + + + + + + + + + + + + + + + + + + + + +
    +
    +
    + + +
    + +

    Source code for pylib.geometry_plot

    +#!/usr/bin/env python
    +# -*- coding: utf-8 -*-
    +"""2D geometry plotter using  matplotlib (pylab).
    +
    +:Date: 2019-08-20
    +
    +.. module:: geometry_plot
    +  :platform: *nix, Windows
    +  :synopsis: Geometry plotting.
    +
    +.. moduleauthor:: Daniel Weschke <daniel.weschke@directbox.de>
    +"""
    +import math
    +import pylab
    +from geometry import (
    +  distance, angle, line, interpolate_hermite, rotate_xy, translate_xy
    +)
    +
    +pylab.style.use('dark_background')
    +pylab.rcParams['grid.color'] = 'gray'
    +
    +# The kwargs are Line2D properties:
    +# https://matplotlib.org/3.1.1/_modules/matplotlib/lines.html#Line2D
    +# https://matplotlib.org/devdocs/_modules/matplotlib/lines.html#Line2D
    +pylab_Line2D_properties = [
    +  'linewidth', 'linestyle', 'color',
    +  'marker', 'markersize', 'markeredgewidth', 'markeredgecolor',
    +  'markerfacecolor', 'markerfacecoloralt',
    +  'fillstyle', 'antialiased',
    +  'dash_capstyle', 'solid_capstyle',
    +  'dash_joinstyle', 'solid_joinstyle',
    +  'pickradius', 'drawstyle', 'markevery',
    +]
    +
    +
    +
    [docs]def plot_lines(lns, **kwargs): + if 'color' not in kwargs: + # Colors from "tab10" colormap + cmap = pylab.get_cmap("tab10") + kwargs['color'] = cmap(0) + + # Colors from color cycle + cycle = pylab.rcParams['axes.prop_cycle'].by_key()['color'] + kwargs['color'] = cycle[0] + + # Colors from CN notation (same as the first 10 colors from the color cycle) + kwargs['color'] = "C0" + + for ln in lns: + x, y = line(*ln) + pylab.plot(x, y, **kwargs)
    + + +
    [docs]def plot_cubic_lines(lns, **kwargs): + if 'color' not in kwargs: + # Colors from "tab10" colormap + cmap = pylab.get_cmap("tab10") + kwargs['color'] = cmap(0) + + # Colors from color cycle + cycle = pylab.rcParams['axes.prop_cycle'].by_key()['color'] + kwargs['color'] = cycle[0] + + # Colors from CN notation (same as the first 10 colors from the color cycle) + kwargs['color'] = "C0" + + factor = 1 + if 'factor' in kwargs: + factor = kwargs['factor'] + + samples = 10 + if 'samples' in kwargs: + samples = kwargs['samples'] + + kwargs = {k: v for k, v in kwargs.items() if k in pylab_Line2D_properties} + + for ln in lns: + l, r, d = ln + L = distance(l, r) + ang = angle(l, r) + x, y = interpolate_hermite(d[1], d[2], d[4], d[5], d[0], d[3], + scale_x=L, scale_y=factor, samples=samples) + x, y = rotate_xy((0, 0), ang, x, y) + x, y = translate_xy(l, x, y) + + pylab.plot(x, y, **kwargs)
    +
    + +
    + +
    +
    + +
    +
    + + + + + + + \ No newline at end of file diff --git a/docs/build/html/_modules/pylib/mathematics.html b/docs/build/html/_modules/pylib/mathematics.html new file mode 100644 index 0000000..a6ddbcf --- /dev/null +++ b/docs/build/html/_modules/pylib/mathematics.html @@ -0,0 +1,116 @@ + + + + + + + pylib.mathematics — pylib 2019.5.19 documentation + + + + + + + + + + + + + + + + + + + + +
    +
    +
    + + +
    + +

    Source code for pylib.mathematics

    +#!/usr/bin/env python
    +# -*- coding: utf-8 -*-
    +"""Mathematical functions.
    +
    +:Date: 2019-10-30
    +
    +.. module:: mathematics
    +  :platform: *nix, Windows
    +  :synopsis: Mathematical functions.
    +
    +.. moduleauthor:: Daniel Weschke <daniel.weschke@directbox.de>
    +"""
    +from math import gcd
    +
    +
    [docs]def lcm(a, b): + """Compute the lowest common multiple of a and b""" + return a/gcd(a, b)*b
    +
    + +
    + +
    +
    + +
    +
    + + + + + + + \ No newline at end of file diff --git a/docs/build/html/_modules/pylib/numerical/fit.html b/docs/build/html/_modules/pylib/numerical/fit.html new file mode 100644 index 0000000..82fe775 --- /dev/null +++ b/docs/build/html/_modules/pylib/numerical/fit.html @@ -0,0 +1,196 @@ + + + + + + + pylib.numerical.fit — pylib 2019.5.19 documentation + + + + + + + + + + + + + + + + + + + + +
    +
    +
    + + +
    + +

    Source code for pylib.numerical.fit

    +#!/usr/bin/env python
    +# -*- coding: utf-8 -*-
    +"""Function and approximation.
    +
    +:Date: 2019-10-15
    +
    +.. 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__": + pass +
    + +
    + +
    +
    + +
    +
    + + + + + + + \ No newline at end of file diff --git a/docs/build/html/_modules/pylib/numerical/integration.html b/docs/build/html/_modules/pylib/numerical/integration.html new file mode 100644 index 0000000..7e608ca --- /dev/null +++ b/docs/build/html/_modules/pylib/numerical/integration.html @@ -0,0 +1,250 @@ + + + + + + + pylib.numerical.integration — pylib 2019.5.19 documentation + + + + + + + + + + + + + + + + + + + + +
    +
    +
    + + +
    + +

    Source code for pylib.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 callable(f): + # 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/pylib/numerical/ode.html b/docs/build/html/_modules/pylib/numerical/ode.html new file mode 100644 index 0000000..ce1c09a --- /dev/null +++ b/docs/build/html/_modules/pylib/numerical/ode.html @@ -0,0 +1,540 @@ + + + + + + + pylib.numerical.ode — pylib 2019.5.19 documentation + + + + + + + + + + + + + + + + + + + + +
    +
    +
    + + +
    + +

    Source code for pylib.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)) + # Approximate solution at next value of x + x[i+1,:] = x[i,:] + dxdt*Dt + 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)) + # Approximate solution at next value of x + x[i+1,:] = x[i,:] + k_2*Dt + 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)) + # Approximate solution at next value of x + x[i+1,:] = x[i,:] + 1./6*(k_1+2*k_2+2*k_3+k_4)*Dt + if verbose: + print('Numerical integration of ODE using explicit ' + + '4th-order method (Runge-Kutta) was successful.') + return x
    + +
    [docs]def fpi(f, xi, ti, ti1, *p, max_iterations=1000, tol=1e-9, + verbose=False): + r"""Fixed-point iteration. + + :param f: the function to iterate :math:`f = \dot{x}(x,t)` + :type f: function + :param xi: initial condition :math:`x_i` + :type xi: list + :param ti: time :math:`t_i` + :type ti: float + :param ti1: time :math:`t_{i+1}` + :type ti1: 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 :math:`\varepsilon` + (default = 1e-9) + :type tol: float + :param verbose: print information (default = False) + :type verbose: bool + + :returns: :math:`x_{i}` + + .. math :: + x_{i,j=0} = x_{i} + + .. math :: + x_{i,j+1} = x_i + \dot{x}(x_{i,j}, t_{i+1})\cdot(t_{i+1}-t_i) + + .. math :: + \text{residuum} = \frac{\lVert x_{i,j+1}-x_{i,j}\rVert} + {\lVert x_{i,j+1} \rVert} < \varepsilon + + .. math :: + x_{i} = x_{i,j=\text{end}} + """ + xij = xi + for j in range(max_iterations): + dxdt = array(f(xij, ti1, *p)) + # Approximate solution at next value of x + xij1 = xi + dxdt * (ti1-ti) + residuum = norm(xij1-xij)/norm(xij1) + xij = xij1 + if residuum < tol: + break + iterations = j+1 # number beginning with 1 therefore + 1 + return xij, 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 + # 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 therefore using + # Newton-Raphson method + for i in range(len(t)-1): + Dt = t[i+1]-t[i] + xi = x[i,:] + xi, iteration = fpi(f, xi, t[i], t[i+1], *p, max_iterations, + tol, verbose) + x[i+1,:] = xi + iterations[i] = iteration + 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)) + # Approximate solution at next value of x + #x11 = x[i,:] + dxdt*Dt + + 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, 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] + + 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(max_iterations): # Fixed-point iteration + #dxdt = array(f(t[i+1], x1, p)) + # Approximate solution at next value of x + #x11 = x[i,:] + dxdt*Dt + + 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/pylib/numerical/ode_model.html b/docs/build/html/_modules/pylib/numerical/ode_model.html new file mode 100644 index 0000000..823f329 --- /dev/null +++ b/docs/build/html/_modules/pylib/numerical/ode_model.html @@ -0,0 +1,219 @@ + + + + + + + pylib.numerical.ode_model — pylib 2019.5.19 documentation + + + + + + + + + + + + + + + + + + + + +
    +
    +
    + + +
    + +

    Source code for pylib.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/_modules/pylib/time_of_day.html b/docs/build/html/_modules/pylib/time_of_day.html new file mode 100644 index 0000000..4f91c46 --- /dev/null +++ b/docs/build/html/_modules/pylib/time_of_day.html @@ -0,0 +1,253 @@ + + + + + + + pylib.time_of_day — pylib 2019.5.19 documentation + + + + + + + + + + + + + + + + + + + + +
    +
    +
    + + +
    + +

    Source code for pylib.time_of_day

    +#!/usr/bin/env python
    +# -*- coding: utf-8 -*-
    +"""Calculate time.
    +
    +:Date: 2019-06-01
    +
    +.. module:: time_of_day
    +  :platform: *nix, Windows
    +  :synopsis: Calculate time.
    +   
    +.. moduleauthor:: Daniel Weschke <daniel.weschke@directbox.de>
    +"""
    +from time import struct_time, mktime
    +
    +
    [docs]def in_seconds(time): + """If time is `time.struct_time` convert to float seconds. + + :param time: the time in seconds + :type time: float or `time.struct_time` + + :returns: the time in seconds + :rtype: float + """ + if isinstance(time, struct_time): + time = mktime(time) + return time
    + +
    [docs]def seconds(time): + """The seconds of the time. + + :param time: the time in seconds + :type time: float or `time.struct_time` + + :returns: seconds, range [0, 60] + :rtype: float + """ + return in_seconds(time)%60
    + +
    [docs]def seconds_norm(time): + """The seconds normalized to 60 seconds. + + :param time: the time in seconds + :type time: float or `time.struct_time` + + :returns: the normalized seconds, range [0, 1] + :rtype: float + """ + return seconds(time)/60
    + +
    [docs]def minutes(time): + """The minutes of the time. + + :param time: the time in seconds + :type time: float or `time.struct_time` + + :returns: minutes, range [0, 60] + :rtype: float + """ + return in_seconds(time)/60%60
    + +
    [docs]def minutes_norm(time): + """The minutes normalized to 60 minutes. + + :param time: the time in seconds + :type time: float or `time.struct_time` + + :returns: the normalized minutes, range [0, 1] + :rtype: float + """ + return minutes(time)/60
    + +
    [docs]def hours(time): + """The hours of the time. + + :param time: the time in seconds + :type time: float or `time.struct_time` + + :returns: hours, range [0, 24] + :rtype: float + """ + return in_seconds(time)/60/60%24
    + +
    [docs]def hours_norm(time): + """The hours normalized to 24 hours. + + :param time: the time in seconds + :type time: float or `time.struct_time` + + :returns: the normalized hours, range [0, 1] + :rtype: float + """ + return hours(time)/24
    + +
    [docs]def days(time): + """The days of the time (year). + + :param time: the time in seconds + :type time: float or `time.struct_time` + + :returns: hours, range [0, 365.2425] + :rtype: float + """ + return in_seconds(time)/60/60/24%365.2425
    + +
    [docs]def days_norm(time): + """The days normalized to 365.2425 (Gregorian, on average) days. + + :param time: the time in seconds + :type time: float or `time.struct_time` + + :returns: the normalized days, range [0, 1] + :rtype: float + """ + return days(time)/365.2425
    + +
    [docs]def transform(time_norm, length, offset=0): + """Transform normalized time value to new length. + + :param position_norm: the normalized time value to transform + :type position_norm: float + :param length: the transformation + :type length: float + :param offset: the offset (default = 0) + :type offset: float + + :returns: the transformation value + :rtype: float + """ + return time_norm*length + offset
    + +if __name__ == "__main__": + from time import time, gmtime, localtime + # time in seconds + t = time() + min = minutes(t) + h = hours(t) + min_norm = minutes_norm(t) + h_norm = hours_norm(t) + + print('min ', min) + print('h ', h) + print('min_norm ', min_norm) + print('h_norm ', h_norm) + + x_len = 30 + x_offset = -8 + x_pos = transform(min_norm, x_len, x_offset) + print('m[-8,22] ', x_pos) + + y_len = 20 + y_offset = -10 + y_pos = transform(h_norm, y_len, y_offset) + print('h[-10,10]', y_pos) + +
    + +
    + +
    +
    + +
    +
    + + + + + + + \ No newline at end of file diff --git a/docs/build/html/_modules/time_of_day.html b/docs/build/html/_modules/time_of_day.html index 7074044..588a48b 100644 --- a/docs/build/html/_modules/time_of_day.html +++ b/docs/build/html/_modules/time_of_day.html @@ -241,7 +241,7 @@ ©2019, Daniel Weschke. | - Powered by Sphinx 2.2.0 + Powered by Sphinx 2.2.1 & Alabaster 0.7.12 diff --git a/docs/build/html/_sources/pylib.numerical.rst.txt b/docs/build/html/_sources/pylib.numerical.rst.txt new file mode 100644 index 0000000..2222ee7 --- /dev/null +++ b/docs/build/html/_sources/pylib.numerical.rst.txt @@ -0,0 +1,46 @@ +pylib.numerical package +======================= + +Submodules +---------- + +pylib.numerical.fit module +-------------------------- + +.. automodule:: pylib.numerical.fit + :members: + :undoc-members: + :show-inheritance: + +pylib.numerical.integration module +---------------------------------- + +.. automodule:: pylib.numerical.integration + :members: + :undoc-members: + :show-inheritance: + +pylib.numerical.ode module +-------------------------- + +.. automodule:: pylib.numerical.ode + :members: + :undoc-members: + :show-inheritance: + +pylib.numerical.ode\_model module +--------------------------------- + +.. automodule:: pylib.numerical.ode_model + :members: + :undoc-members: + :show-inheritance: + + +Module contents +--------------- + +.. automodule:: pylib.numerical + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/build/html/_sources/pylib.rst.txt b/docs/build/html/_sources/pylib.rst.txt new file mode 100644 index 0000000..f891b10 --- /dev/null +++ b/docs/build/html/_sources/pylib.rst.txt @@ -0,0 +1,77 @@ +pylib package +============= + +Subpackages +----------- + +.. toctree:: + + pylib.numerical + +Submodules +---------- + +pylib.data module +----------------- + +.. automodule:: pylib.data + :members: + :undoc-members: + :show-inheritance: + +pylib.date module +----------------- + +.. automodule:: pylib.date + :members: + :undoc-members: + :show-inheritance: + +pylib.function module +--------------------- + +.. automodule:: pylib.function + :members: + :undoc-members: + :show-inheritance: + +pylib.geometry module +--------------------- + +.. automodule:: pylib.geometry + :members: + :undoc-members: + :show-inheritance: + +pylib.geometry\_plot module +--------------------------- + +.. automodule:: pylib.geometry_plot + :members: + :undoc-members: + :show-inheritance: + +pylib.mathematics module +------------------------ + +.. automodule:: pylib.mathematics + :members: + :undoc-members: + :show-inheritance: + +pylib.time\_of\_day module +-------------------------- + +.. automodule:: pylib.time_of_day + :members: + :undoc-members: + :show-inheritance: + + +Module contents +--------------- + +.. automodule:: pylib + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/build/html/data.html b/docs/build/html/data.html index bbc4ef0..6db51b2 100644 --- a/docs/build/html/data.html +++ b/docs/build/html/data.html @@ -255,7 +255,7 @@ between consecutive terms).

    ©2019, Daniel Weschke. | - Powered by Sphinx 2.2.0 + Powered by Sphinx 2.2.1 & Alabaster 0.7.12 | diff --git a/docs/build/html/date.html b/docs/build/html/date.html index 39eb77a..f1b456c 100644 --- a/docs/build/html/date.html +++ b/docs/build/html/date.html @@ -212,7 +212,7 @@ ©2019, Daniel Weschke. | - Powered by Sphinx 2.2.0 + Powered by Sphinx 2.2.1 & Alabaster 0.7.12 | diff --git a/docs/build/html/function.html b/docs/build/html/function.html index 047c986..49c1593 100644 --- a/docs/build/html/function.html +++ b/docs/build/html/function.html @@ -68,7 +68,7 @@ time t

    See also

    -

    function_sine_wave_degree()

    +

    sine_wave()

    @@ -228,7 +228,136 @@ angular frequency ω and the linear speed (speed of propagation) linear speed.

    See also

    -

    function_cosine_wave_degree()

    +

    cosine_wave()

    +
    + + +
    +
    +to_str(f, x=None, x_0=0, x_1=1, t=None, h=10, w=80, density=1, char_set='line')[source]
    +

    Represent functions as string frame with a specific character set. +which are normed to the range of [0, 1] to

    +
    +
    Parameters
    +
      +
    • f (function or list) – function or list of functions normed to the range of [0, 1]

    • +
    • h (int) – number of chars in vertical direction

    • +
    • w (int) – number of chars in horizontal direction

    • +
    • char_set (str) – either “braille” or “block”. “braille” uses Unicode +Characters in the Braille Patterns Block (fisrt index U+2800, last +index U+28FF [CUDB]) and the “block” uses part of the Unicode +Characters in the Block Elements Block (fisrt index U+2580, last +index U+259F [CUDB]). Alias for braille is line and alias for +block is histogram

    • +
    +
    +
    +
    +
    Usage:
      +
    • case dependent arguments

      +
        +
      • 1 quasi line plot (braille characters) +f = lambda function (lambda x, t=0: …) +x_1 = max x value +x_0 = min x value +t = time (animation)

      • +
      • 2 histogram (block characters) +f = lambda function (lambda x, t=0: …) +x_1 = max x value +x_0 = min x value +t = time (animation) +chart=”histogram”

      • +
      +
    • +
    • general arguments +w = window width in number of chars +density = number of data point per pixel (for line chart higher density makes thicker lines) +chart = either “line” or “histogram”

    • +
    +
    +
    +

    Braille Patterns Block

    +
      +
    • Dots or pixels per character in vertical direction: 6

    • +
    • Dots or pixels per character in horizontal direction: 2

    • +
    +

    First dot (bottom left) is the zero (0) position of the +function. So, a function value of zero does not mean to have zero +dots but one. +Example of 3 columns and 3 rows (upside down view of ‘normal’ braille/drawille position)

    +
       |            ^ y axis
    +   |            |
    +   |   ,_____,,_____,,_____,
    + 7 +   | *  *|| *  *|| *  *|
    + 6 +   | *  *|| *  *|| *  *|
    + 5 +   | *  *|| *  *|| *  *|
    + 4 +   | *  *|| *  *|| *  *|
    +   |   ;=====;;=====;;=====;
    + 3 +   | *  *|| *  *|| *  *|
    + 2 +   | *  *|| *  *|| *  *|
    + 1 +   | *  *|| *  *|| *  *|
    + 0 + - | *  *|| *  *|| *  *| ---> x axis
    +   |   ;=====;;=====;;=====;
    +-1 +   | *  *|| *  *|| *  *|
    +-2 +   | *  *|| *  *|| *  *|
    +-3 +   | *  *|| *  *|| *  *|
    +-4 +   | *  *|| *  *|| *  *|
    +   |   `````````````````````
    +   |            |
    +   `-----+--+---+--+---+--+-------------
    +        -2 -1   0  1   2  3
    +
    +
    +

    Block Elements Block

    +
      +
    • Dots or pixels per character in vertical direction: 8

    • +
    • Dots or pixels per character in horizontal direction: 1

    • +
    +

    Example of 3 columns and 3 rows

    +
       |             ^ y axis
    +   |             |
    +   |   ,_____,,_____,,_____,
    +15 +   | --- || --- || --- |
    +14 +   | --- || --- || --- |
    +13 +   | --- || --- || --- |
    +12 +   | --- || --- || --- |
    +11 +   | --- || --- || --- |
    +10 +   | --- || --- || --- |
    + 9 +   | --- || --- || --- |
    + 8 +   | --- || --- || --- |
    +   |   ;=====;;=====;;=====;
    + 7 +   | --- || --- || --- |
    + 6 +   | --- || --- || --- |
    + 5 +   | --- || --- || --- |
    + 4 +   | --- || --- || --- |
    + 3 +   | --- || --- || --- |
    + 2 +   | --- || --- || --- |
    + 1 +   | --- || --- || --- |
    + 0 + - | --- || --- || --- | ---> x axis
    +   |   ;=====;;=====;;=====;
    +-1 +   | --- || --- || --- |
    +-2 +   | --- || --- || --- |
    +-3 +   | --- || --- || --- |
    +-4 +   | --- || --- || --- |
    +-5 +   | --- || --- || --- |
    +-6 +   | --- || --- || --- |
    +-7 +   | --- || --- || --- |
    +-8 +   | --- || --- || --- |
    +   |   `````````````````````
    +   |             |
    +   `------+------+------+---------------
    +         -1      0      1
    +
    +
    +

    References

    +
    +
    CUDB(1,2)
    +

    Unicode Database - Blocks

    +
    +
    +
    @@ -314,7 +443,7 @@ linear speed.

    ©2019, Daniel Weschke. | - Powered by Sphinx 2.2.0 + Powered by Sphinx 2.2.1 & Alabaster 0.7.12 | diff --git a/docs/build/html/genindex.html b/docs/build/html/genindex.html index f4cb7ea..3fbdea8 100644 --- a/docs/build/html/genindex.html +++ b/docs/build/html/genindex.html @@ -61,11 +61,19 @@
    @@ -73,39 +81,79 @@

    D

    @@ -113,36 +161,72 @@

    F

    @@ -151,33 +235,61 @@

    H

    @@ -185,15 +297,27 @@
    @@ -201,29 +325,53 @@

    M

    @@ -231,13 +379,21 @@ + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + +
    - data (*nix, Windows) + data (*nix, Windows) Handle data files and structures.
    - date (*nix, Windows) + date (*nix, Windows) Special dates.
     
    @@ -73,12 +70,12 @@
    - fit (*nix, Windows) + fit (*nix, Windows) Function and approximation.
    - function (*nix, Windows) + function (*nix, Windows) Mathematical equations.
     
    @@ -86,12 +83,12 @@
    - geometry (*nix, Windows) + geometry (*nix, Windows) Geometry objects.
    - geometry_plot (*nix, Windows) + geometry_plot (*nix, Windows) Geometry plotting.
     
    @@ -99,7 +96,7 @@
    - integration (*nix, Windows) + integration (*nix, Windows) Numerical integration.
     
    @@ -107,7 +104,7 @@
    - mathematics (*nix, Windows) + mathematics (*nix, Windows) Mathematical functions.
     
    @@ -144,20 +141,89 @@
    - ode (*nix, Windows) + ode (*nix, Windows) Numerical solver.
    - ode_model (*nix, Windows) + ode_model (*nix, Windows) Models of ordinary differential equations.
     
    + p
    + pylib +
        + pylib.data +
        + pylib.date +
        + pylib.function +
        + pylib.geometry +
        + pylib.geometry_plot +
        + pylib.mathematics +
        + pylib.numerical +
        + pylib.numerical.fit +
        + pylib.numerical.integration +
        + pylib.numerical.ode +
        + pylib.numerical.ode_model +
        + pylib.time_of_day +
     
    t
    - time_of_day (*nix, Windows) + time_of_day (*nix, Windows) Calculate time.
    @@ -212,7 +278,7 @@ ©2019, Daniel Weschke. | - Powered by Sphinx 2.2.0 + Powered by Sphinx 2.2.1 & Alabaster 0.7.12 diff --git a/docs/build/html/pylib.html b/docs/build/html/pylib.html new file mode 100644 index 0000000..f0fffdd --- /dev/null +++ b/docs/build/html/pylib.html @@ -0,0 +1,1411 @@ + + + + + + + pylib package — pylib 2019.5.19 documentation + + + + + + + + + + + + + + + + + + + + +
    +
    +
    + + +
    + +
    +

    pylib package

    + +
    +

    Submodules

    +
    +
    +

    pylib.data module

    +

    Read and write data to or from file and manipulate data structures.

    +
    +
    Date
    +

    2019-10-11

    +
    +
    +
    +
    +fold_list(lst, n)[source]
    +

    Convert one-dimensional kx1 array (list) to two-dimensional mxn +array. m = k / n

    +
    +
    Parameters
    +
      +
    • lst (list) – list to convert

    • +
    • n (int) – length of the second dimenson

    • +
    +
    +
    Returns
    +

    two-dimensional array (list of lists)

    +
    +
    Return type
    +

    list

    +
    +
    +
    + +
    +
    +get_id(ids, uide)[source]
    +

    Get full id from unique id ending.

    +
    +
    Parameters
    +
      +
    • ids (list) – ids

    • +
    • uide (str) – unique id ending

    • +
    +
    +
    Returns
    +

    full id

    +
    +
    Return type
    +

    str or int

    +
    +
    +
    + +
    +
    +load(file_name, default=None, verbose=False)[source]
    +

    Load stored program objects from binary file.

    +
    +
    Parameters
    +
      +
    • file_name (str) – file to load

    • +
    • default (object) – return object if data loading fails

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

    • +
    +
    +
    Returns
    +

    loaded data

    +
    +
    Return type
    +

    object

    +
    +
    +
    + +
    +
    +read(file_name, x_column, y_column, default=None, verbose=False)[source]
    +

    Read ascii data file.

    +
    +
    Parameters
    +
      +
    • filename (str) – file to read

    • +
    • x_column (int) – column index for the x data (first column is 0)

    • +
    • y_column (int) – column index for the y data (first column is 0)

    • +
    • default (object) – return object if data loading fails

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

    • +
    +
    +
    Returns
    +

    x and y

    +
    +
    Return type
    +

    tuple(list, list)

    +
    +
    +
    + +
    +
    +seq(start, stop=None, step=1)[source]
    +

    Create an arithmetic bounded sequence.

    +

    The sequence is one of the following;

    +
      +
    • empty \(\{\}=\emptyset\), if start and stop are the same

    • +
    • degenerate \(\{a\}\), if the sequence has only one element.

    • +
    • left-close and right-open \([a, b)\)

    • +
    +
    +
    Parameters
    +
      +
    • start (int or float) – start of the sequence, the lower bound. If only start +is given than it is interpreted as stop and start will be 0.

    • +
    • stop (int or float) – stop of sequence, the upper bound.

    • +
    • step (int or float) – step size, the common difference (constant difference +between consecutive terms).

    • +
    +
    +
    Returns
    +

    arithmetic bounded sequence

    +
    +
    Return type
    +

    list

    +
    +
    +
    + +
    +
    +store(file_name, object_data)[source]
    +

    Store program objects to binary file.

    +
    +
    Parameters
    +
      +
    • file_name (str) – file to store

    • +
    • object_data (object) – data to store

    • +
    +
    +
    +
    + +
    +
    +unique_ending(ids, n=1)[source]
    +

    From id list get list with unique ending.

    +
    +
    Parameters
    +
      +
    • ids (list) – ids

    • +
    • n (int) – minumum chars or ints

    • +
    +
    +
    Returns
    +

    unique ending of ids

    +
    +
    Return type
    +

    list

    +
    +
    +
    + +
    +
    +write(file_name, data)[source]
    +

    Write ascii file.

    +
    +
    Parameters
    +
      +
    • file_name (str) – file to write

    • +
    • data (str) – data to write

    • +
    +
    +
    +
    + +
    +
    +

    pylib.date module

    +

    Calculate spacial dates.

    +
    +
    Date
    +

    2018-01-15

    +
    +
    +
    +
    +ascension_of_jesus(year)[source]
    +

    Ascension of Jesus.

    +
    +
    Parameters
    +

    year (int) – the year to calculate the ascension of Jesus

    +
    +
    Returns
    +

    the day of ascension of Jesus

    +
    +
    Return type
    +

    datetime.date

    +
    +
    +
    + +
    +
    +easter_friday(year)[source]
    +

    Easter Friday.

    +
    +
    Parameters
    +

    year (int) – the year to calculate the Easter Friday

    +
    +
    Returns
    +

    the day of Easter Friday

    +
    +
    Return type
    +

    datetime.date

    +
    +
    +
    + +
    +
    +easter_monday(year)[source]
    +

    Easter Monday.

    +
    +
    Parameters
    +

    year (int) – the year to calculate the Easter Monday

    +
    +
    Returns
    +

    the day of Easter Monday

    +
    +
    Return type
    +

    datetime.date

    +
    +
    +
    + +
    +
    +easter_sunday(year)[source]
    +

    Easter Sunday.

    +
    +
    Parameters
    +

    year (int) – the year to calculate the Easter Sunday

    +
    +
    Returns
    +

    the day of Easter Sunday

    +
    +
    Return type
    +

    datetime.date

    +
    +
    +
    + +
    +
    +gaußsche_osterformel(year)[source]
    +

    Gaußsche Osterformel.

    +
    +
    Parameters
    +

    year (int) – the year to calculate the Easter Sunday

    +
    +
    Returns
    +

    the day of Easter Sunday as a day in march.

    +
    +
    Return type
    +

    int

    +
    +
    Variables
    +
      +
    • X (int) – Das Jahr / year

    • +
    • K(X) (int) – Die Säkularzahl

    • +
    • M(X) (int) – Die säkulare Mondschaltung

    • +
    • S(K) (int) – Die säkulare Sonnenschaltung

    • +
    • A(X) (int) – Den Mondparameter

    • +
    • D(A,M) (int) – Den Keim für den ersten Vollmond im Frühling

    • +
    • R(D,A) (int) – Die kalendarische Korrekturgröße

    • +
    • OG(D,R) (int) – Die Ostergrenze

    • +
    • SZ(X,S) (int) – Den ersten Sonntag im März

    • +
    • OE(OG,SZ) (int) – Die Entfernung des Ostersonntags von der Ostergrenze (Osterentfernung in Tagen)

    • +
    • OS(OG,OE) (int) – Das Datum des Ostersonntags als Märzdatum (32. März = 1. April usw.)

    • +
    +
    +
    +

    Algorithmus gilt für den Gregorianischen Kalender.

    +

    source: https://de.wikipedia.org/wiki/Gau%C3%9Fsche_Osterformel

    +
    + +
    +
    +pentecost(year)[source]
    +

    Pentecost.

    +
    +
    Parameters
    +

    year (int) – the year to calculate the Pentecost

    +
    +
    Returns
    +

    the day of Pentecost

    +
    +
    Return type
    +

    datetime.date

    +
    +
    +
    + +
    +
    +

    pylib.function module

    +

    Mathematical equations.

    +
    +
    Date
    +

    2019-11-04

    +
    +
    +
    +
    +cosine_wave(A=1, k=1, f=1, phi=0, D=0, degree=False)[source]
    +

    A cosine wave is said to be sinusoidal, because, +\(\cos(x) = \sin(x + \pi/2)\), which is also a sine wave with a +phase-shift of π/2 radians. Because of this head start, it is often +said that the cosine function leads the sine function or the sine +lags the cosine.

    +
    +
    Parameters
    +
      +
    • A (float or int) – amplitude

    • +
    • k (float or int) – (angular) wave number

    • +
    • f (float or int) – ordinary frequency

    • +
    • phi (float or int) – phase

    • +
    • D (float or int) – non-zero center amplitude

    • +
    • degree (bool) – boolean to switch between radians and degree. If +False phi is interpreted in radians and if True then phi is +interpreted in degrees.

    • +
    +
    +
    Results
    +

    sine wave function of spatial variable x and optional +time t

    +
    +
    +
    +

    See also

    +

    sine_wave()

    +
    +
    + +
    +
    +epitrochoid(R, r, d)[source]
    +

    Epitrochoid

    +

    A point is attached with a distance d from the center of a circle +of radius r. The circle is rolling around the outside of a fixed +circle of radius R.

    +
    +
    Parameters
    +
      +
    • R (float) – radius of the fixed interior circle

    • +
    • r – radius of the rolling circle outside of the fixed circle

    • +
    • d (float) – distance from the center of the exterior circle

    • +
    +
    +
    Typre r
    +

    float

    +
    +
    Results
    +

    functions for x of theta and y of theta

    +
    +
    Return type
    +

    tuple

    +
    +
    +
    +\[\begin{split}x(\theta) = (R + r)\cos\theta - d\cos\left(\frac{R+r}{r}\theta\right) \\ +y(\theta) = (R + r)\sin\theta - d\sin\left(\frac{R+r}{r}\theta\right) \\ +\theta = \left[0, 2\pi\right]\end{split}\]
    +
           *  *  *
    +    * R         *
    +  *               *
    + *                 *     *  *
    +*                   * * r      *
    +*                   ** ....     *
    +*                   **   d      *
    +*                   * *        *
    + *                 *     *  *
    +  *               *
    +    *          *
    +       *  *  *
    +
    +
    +
    >>> x, y = epitrochoid(3, 1, 0.5)[:1]
    +>>> x, y, theta_end = epitrochoid(3, 1, 0.5)
    +
    +
    +
    + +
    +
    +hypotrochoid(R, r, d)[source]
    +

    Hypotrochoid

    +

    A point is attached with a distance d from the center of a circle +of radius r. The circle is rolling around the inside of a fixed +circle of radius R.

    +
    +
    Parameters
    +
      +
    • R (float) – radius of the fixed exterior circle

    • +
    • r – radius of the rolling circle inside of the fixed circle

    • +
    • d (float) – distance from the center of the interior circle

    • +
    +
    +
    Typre r
    +

    float

    +
    +
    Results
    +

    functions for x of theta and y of theta

    +
    +
    Return type
    +

    tuple

    +
    +
    +
    +\[\begin{split}x(\theta) = (R - r)\cos\theta + d\cos\left(\frac{R-r}{r}\theta\right) \\ +y(\theta) = (R - r)\sin\theta - d\sin\left(\frac{R-r}{r}\theta\right) \\ +\theta = \left[0, 2\pi\frac{\mathrm{lcm}(r, R)}{R}\right]\end{split}\]
    +
           *  *  *
    +    * R         *
    +  *               *
    + *           *  *  *
    +*         * r      **
    +*        *     .... *
    +*        *      d   *
    +*         *        **
    + *           *  *  *
    +  *               *
    +    *          *
    +       *  *  *
    +
    +
    +
    >>> x, y = hyotrochoid(20, 6, 6)[:1]
    +>>> x, y, theta_end = hyotrochoid(20, 6, 6)
    +
    +
    +
    +

    See also

    +

    mathematics.lcm()

    +
    +
    + +
    +
    +sine_wave(A=1, k=1, f=1, phi=0, D=0, degree=False)[source]
    +

    A sine wave or sinusoid is a mathematical curve that describes a +smooth periodic oscillation.

    +
    +
    Parameters
    +
      +
    • A (float or int) – amplitude

    • +
    • k (float or int) – (angular) wave number

    • +
    • f (float or int) – ordinary frequency

    • +
    • phi (float or int) – phase

    • +
    • D (float or int) – non-zero center amplitude

    • +
    • degree (bool) – boolean to switch between radians and degree. If +False phi is interpreted in radians and if True then phi is +interpreted in degrees.

    • +
    +
    +
    Results
    +

    sine wave function of spatial variable x and optional +time t

    +
    +
    +

    In general, the function is:

    +
    +\[\begin{split}y(x,t) = A\sin(kx + 2\pi f t + \varphi) + D \\ +y(x,t) = A\sin(kx + \omega t + \varphi) + D\end{split}\]
    +

    where:

    +
    +
      +
    • A, amplitude, the peak deviation of the function from zero.

    • +
    • f, ordinary frequency, the number of oscillations (cycles) that +occur each second of time.

    • +
    • ω = 2πf, angular frequency, the rate of change of the function +argument in units of radians per second. If ω < 0 the wave is +moving to the right, if ω > 0 the wave is moving to the left.

    • +
    • φ, phase, specifies (in radians) where in its cycle the +oscillation is at t = 0.

    • +
    • x, spatial variable that represents the position on the +dimension on which the wave propagates.

    • +
    • k, characteristic parameter called wave number (or angular wave +number), which represents the proportionality between the +angular frequency ω and the linear speed (speed of propagation) +ν.

    • +
    • D, non-zero center amplitude.

    • +
    +
    +

    The wavenumber is related to the angular frequency by:

    +
    +\[k={\omega \over v}={2\pi f \over v}={2\pi \over \lambda }\]
    +

    where λ (lambda) is the wavelength, f is the frequency, and v is the +linear speed.

    +
    +

    See also

    +

    cosine_wave()

    +
    +
    + +
    +
    +to_str(f, x=None, x_0=0, x_1=1, t=None, h=10, w=80, density=1, char_set='line')[source]
    +

    Represent functions as string frame with a specific character set. +which are normed to the range of [0, 1] to

    +
    +
    Parameters
    +
      +
    • f (function or list) – function or list of functions normed to the range of [0, 1]

    • +
    • h (int) – number of chars in vertical direction

    • +
    • w (int) – number of chars in horizontal direction

    • +
    • char_set (str) – either “braille” or “block”. “braille” uses Unicode +Characters in the Braille Patterns Block (fisrt index U+2800, last +index U+28FF [CUDB]) and the “block” uses part of the Unicode +Characters in the Block Elements Block (fisrt index U+2580, last +index U+259F [CUDB]). Alias for braille is line and alias for +block is histogram

    • +
    +
    +
    +
    +
    Usage:
      +
    • case dependent arguments

      +
        +
      • 1 quasi line plot (braille characters) +f = lambda function (lambda x, t=0: …) +x_1 = max x value +x_0 = min x value +t = time (animation)

      • +
      • 2 histogram (block characters) +f = lambda function (lambda x, t=0: …) +x_1 = max x value +x_0 = min x value +t = time (animation) +chart=”histogram”

      • +
      +
    • +
    • general arguments +w = window width in number of chars +density = number of data point per pixel (for line chart higher density makes thicker lines) +chart = either “line” or “histogram”

    • +
    +
    +
    +

    Braille Patterns Block

    +
      +
    • Dots or pixels per character in vertical direction: 6

    • +
    • Dots or pixels per character in horizontal direction: 2

    • +
    +

    First dot (bottom left) is the zero (0) position of the +function. So, a function value of zero does not mean to have zero +dots but one. +Example of 3 columns and 3 rows (upside down view of ‘normal’ braille/drawille position)

    +
       |            ^ y axis
    +   |            |
    +   |   ,_____,,_____,,_____,
    + 7 +   | *  *|| *  *|| *  *|
    + 6 +   | *  *|| *  *|| *  *|
    + 5 +   | *  *|| *  *|| *  *|
    + 4 +   | *  *|| *  *|| *  *|
    +   |   ;=====;;=====;;=====;
    + 3 +   | *  *|| *  *|| *  *|
    + 2 +   | *  *|| *  *|| *  *|
    + 1 +   | *  *|| *  *|| *  *|
    + 0 + - | *  *|| *  *|| *  *| ---> x axis
    +   |   ;=====;;=====;;=====;
    +-1 +   | *  *|| *  *|| *  *|
    +-2 +   | *  *|| *  *|| *  *|
    +-3 +   | *  *|| *  *|| *  *|
    +-4 +   | *  *|| *  *|| *  *|
    +   |   `````````````````````
    +   |            |
    +   `-----+--+---+--+---+--+-------------
    +        -2 -1   0  1   2  3
    +
    +
    +

    Block Elements Block

    +
      +
    • Dots or pixels per character in vertical direction: 8

    • +
    • Dots or pixels per character in horizontal direction: 1

    • +
    +

    Example of 3 columns and 3 rows

    +
       |             ^ y axis
    +   |             |
    +   |   ,_____,,_____,,_____,
    +15 +   | --- || --- || --- |
    +14 +   | --- || --- || --- |
    +13 +   | --- || --- || --- |
    +12 +   | --- || --- || --- |
    +11 +   | --- || --- || --- |
    +10 +   | --- || --- || --- |
    + 9 +   | --- || --- || --- |
    + 8 +   | --- || --- || --- |
    +   |   ;=====;;=====;;=====;
    + 7 +   | --- || --- || --- |
    + 6 +   | --- || --- || --- |
    + 5 +   | --- || --- || --- |
    + 4 +   | --- || --- || --- |
    + 3 +   | --- || --- || --- |
    + 2 +   | --- || --- || --- |
    + 1 +   | --- || --- || --- |
    + 0 + - | --- || --- || --- | ---> x axis
    +   |   ;=====;;=====;;=====;
    +-1 +   | --- || --- || --- |
    +-2 +   | --- || --- || --- |
    +-3 +   | --- || --- || --- |
    +-4 +   | --- || --- || --- |
    +-5 +   | --- || --- || --- |
    +-6 +   | --- || --- || --- |
    +-7 +   | --- || --- || --- |
    +-8 +   | --- || --- || --- |
    +   |   `````````````````````
    +   |             |
    +   `------+------+------+---------------
    +         -1      0      1
    +
    +
    +

    References

    +
    +
    CUDB(1,2)
    +

    Unicode Database - Blocks

    +
    +
    + +
    + +
    +
    +transformation(f, scale_vertical=1, scale_horizontal=1, shift_horizontal=0, shift_vertical=0)[source]
    +

    Transform functions.

    +
    +
    Parameters
    +
      +
    • f (function or list) – function or list of functions

    • +
    • scale_vertical – “a” scale factor in vertical direction (default += 1)

    • +
    • scale_horizontal – “b” scale factor in horizontal direction +(default = 1)

    • +
    • shift_horizontal – “c” shift factor in horizontal direction +(default = 0)

    • +
    • shift_vertical – “d” shift factor in vertical direction (default += 0)

    • +
    +
    +
    Returns
    +

    transformed function or list of transformed functions

    +
    +
    Return type
    +

    function or list

    +
    +
    +
    +\[y = a \, f(b\,(x-c)) + d\]
    +
    + +
    +
    +

    pylib.geometry module

    +

    2D geometry objects.

    +
    +
    Date
    +

    2019-08-28

    +
    +
    +
    +
    +angle(point1, point2=None)[source]
    +

    Angle of point or between two points.

    +
    +
    Parameters
    +
      +
    • point1 (tuple) – (first) point

    • +
    • point2 (tuple) – second point (default = None)

    • +
    +
    +
    Returns
    +

    angle of point or between two points

    +
    +
    Return type
    +

    float

    +
    +
    +
    + +
    +
    +cubic(point1, angle1, point2, angle2, samples=10)[source]
    +

    Cubic line defined by two end points and the rotation in radians +at the points.

    +
    +
    Parameters
    +
      +
    • point1 (tuple) – one end point

    • +
    • angle1 (int or float) – the slope at the one end point

    • +
    • point2 (tuple) – other end point

    • +
    • angle2 (int or float) – the slope at the other end point

    • +
    • samples (int) – number of sampling points (default = 10)

    • +
    +
    +
    Returns
    +

    ([sample_point1_x, sample_point2_x, …], +[sample_points1_y, sample_point2_y, …])

    +
    +
    Return type
    +

    tuple

    +
    +
    +
    + +
    +
    +cubic_deg(point1, angle1, point2, angle2)[source]
    +

    Cubic line defined by two end points and the roation in degree +at the points.

    +
    +
    Parameters
    +
      +
    • point1 (tuple) – one end point

    • +
    • angle1 (int or float) – the slope at the one end point

    • +
    • point2 (tuple) – other end point

    • +
    • angle2 (int or float) – the slope at the other end point

    • +
    +
    +
    Returns
    +

    ([sample_point1_x, sample_point2_x, …], +[sample_points1_y, sample_point2_y, …])

    +
    +
    Return type
    +

    tuple

    +
    +
    +
    +

    See also

    +

    cubic()

    +
    +
    + +
    +
    +cubics(pts, **kwargs)[source]
    +

    Cubic lines defined by a list of two end points. The deformation +as displacement and rotation (radians) is defined element wise as +keyword argument deformation or global node wise as +global_deformation. The global coordinate system is xy. x in the +right direction and y in the top direction.

    +
    +
    Parameters
    +
      +
    • pts – list of points in absolute global coordinate system. If +keyword inc is given than the inc decides what the left and the +right end point of the line is, otherwise it is assumed that the +points build a solid line, that is lines between the given points +in given order.

    • +
    • **kwargs

      options:

      +
        +
      • deformation – list of deformation element wise. Additional +deformation (translation and rotation in radians) at element +left and right node.

      • +
      • rotation_plane – rotation plane of the element wise +deformation defined by a string; either ‘xy’ or ‘xz’ (default += ‘xy’). x in the right direction and y in the top direction +or z in the bottom direction.

      • +
      • global_deformation – list of deformation global node wise. +Additional deformation (horizontal translation, vertical +translation and rotation in radians) at node.

      • +
      • factor – factor of the derformation (default = 1).

      • +
      • inc – the incidence table, a list of 2 element lists. The inc +decides what the left and the right end point of the line is.

      • +
      • index_offset – starting index of lists (default = 0).

      • +
      +

    • +
    +
    +
    Returns
    +

    list of endpoints for each line; +[(((point1_x, point1_y) angle1), ((point2_x, point2_y), angle2), +(p1, angle1, p2, angle2), +…]

    +
    +
    Return type
    +

    list

    +
    +
    +
    + +
    +
    +distance(point1, point2)[source]
    +

    Distance between two points (or length of a straight line).

    +
    +
    Parameters
    +
      +
    • point1 (tuple) – first point (first end point of straight line)

    • +
    • point2 (tuple) – second point (second end point of straight line)

    • +
    +
    +
    Returns
    +

    distance between the two points

    +
    +
    Return type
    +

    float

    +
    +
    +
    + +
    +
    +interpolate_hermite(lvd, lr, rvd, rr, lhd=0, rhd=0, scale_x=1, scale_y=1, samples=10)[source]
    +

    Interpolate cubic line with hermite boundary conditions.

    +
    +
    Parameters
    +
      +
    • lvd (int or float) – left vertcal deflection

    • +
    • lr (int or float) – left rotation

    • +
    • rvd (int or float) – right vertical deflection

    • +
    • rr (int or float) – right rotation

    • +
    • lhd (int or float) – left horizontal deformation (default = 0)

    • +
    • rhd (int or float) – right horizontal deformation (default = 0)

    • +
    • scale_x (int or float) – length of element (default = 1)

    • +
    • scale_y (int or float) – factor of the deformation (default = 1). +This does not change the length.

    • +
    • samples (int) – number of sampling points (default = 10)

    • +
    +
    +
    +
    +\[\begin{split}s = \frac{x - x_1}{L} \\ +x = s\,L + x_1\end{split}\]
    +
    + +
    +
    +line(point1, point2, samples=2)[source]
    +

    Line defined by two end points.

    +
    +\[y = \frac{y_2-y_1}{x_2-x_1}(x-x_1) + y_1\]
    +
    +
    Parameters
    +
      +
    • point1 (tuple) – one end point

    • +
    • point2 (tuple) – other end point

    • +
    • samples (int) – number of sampling points (default = 2)

    • +
    +
    +
    Returns
    +

    ((point1_x, point2_x), (points1_y, point2_y)) or +([sample_point1_x, sample_point2_x, …], +[sample_points1_y, sample_point2_y, …])

    +
    +
    Return type
    +

    tuple

    +
    +
    Example
    +

    +
    +
    >>> x, y = line((0, 0), (1, 0))
    +>>> print(x, y)
    +((0, 1), (0, 0))
    +
    +
    +
    + +
    +
    +lines(pts, **kwargs)[source]
    +

    Lines defined by a list of end points.

    +
    +
    Parameters
    +
      +
    • pts (list) – list of points in absolute global coordinate system. If +keyword inc is given than the inc decides what the left and the +right end point of the line is, otherwise it is assumed that the +points build a solid line, that is lines between the given points +in given order.

    • +
    • **kwargs

      options:

      +
        +
      • deformation – list of points. Additional deformation +(translation) at point.

      • +
      • factor – factor of the deformation (default = 1).

      • +
      • inc – the incidence table, a list of 2 element lists. The inc +decides what the left and the right end point of the line is.

      • +
      • index_offset – starting index of lists (default = 0).

      • +
      +

    • +
    +
    +
    Returns
    +

    list of endpoints for each line; +[((point1_x, point1_y), (point2_x, point2_y)), +(p1, p2), +…]

    +
    +
    Return type
    +

    list

    +
    +
    +
    +

    See also

    +

    plot_lines() of the geometry_plot +module to plot the lines

    +
    +
    + +
    +
    +rectangle(width, height)[source]
    +
    +
    Parameters
    +
      +
    • width (int or float) – the width of the rectangle

    • +
    • height (int or float) – the height of the rectangle

    • +
    +
    +
    Returns
    +

    (point1, point2, point3, point4)

    +
    +
    Return type
    +

    tuple

    +
    +
    +
    + +
    +
    +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.

    +
    +
    Parameters
    +
      +
    • origin (tuple) – the center of rotation

    • +
    • angle (int or float) – the rotation angle

    • +
    • *pts – points to rotate

    • +
    • **kwargs – options

    • +
    +
    +
    Returns
    +

    (point_x, point_y) or (point1, point2, …)

    +
    +
    Return type
    +

    tuple

    +
    +
    +
    +

    See also

    +

    rotate_xy()

    +
    +
    + +
    +
    +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.

    +
    +
    Parameters
    +
      +
    • origin (tuple) – the center of rotation

    • +
    • angle (int or float) – the rotation angle

    • +
    • *pts – points to rotate

    • +
    • **kwargs – options

    • +
    +
    +
    Returns
    +

    (point_x, point_y) or (point1, point2, …)

    +
    +
    Return type
    +

    tuple

    +
    +
    +
    +

    See also

    +

    rotate()

    +
    +
    + +
    +
    +rotate_xy(origin, angle, x, y, **kwargs)[source]
    +

    Rotate x and y coordinates counterclockwise by a given angle +around a given origin. The angle should be given in radians.

    +
    +
    Parameters
    +
      +
    • origin (tuple) – the center of rotation

    • +
    • angle (int or float) – the rotation angle

    • +
    • x (int or float or list) – x coordinates

    • +
    • y (int or float or list) – y coordinates

    • +
    • **kwargs – options

    • +
    +
    +
    +
    +

    See also

    +

    rotate()

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

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

    +
    +
    Returns
    +

    (point1, point2, point3, point4)

    +
    +
    Return type
    +

    tuple

    +
    +
    +
    +

    See also

    +

    rectangle()

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

    Translate a point or polygon by a given vector.

    +
    +
    Parameters
    +
      +
    • vec (tuple) – translation vector

    • +
    • *pts – points to translate

    • +
    +
    +
    Returns
    +

    (point_x, point_y) or (point1, point2, …)

    +
    +
    Return type
    +

    tuple

    +
    +
    +
    +

    See also

    +

    translate_xy()

    +
    +
    + +
    +
    +translate_xy(vec, x, y)[source]
    +

    Translate a point or polygon by a given vector.

    +
    +
    Parameters
    +
      +
    • vec (tuple) – translation vector

    • +
    • x (int or float or list) – points to translate

    • +
    • y (int or float or list) – points to translate

    • +
    +
    +
    Returns
    +

    (x’, y’)

    +
    +
    Return type
    +

    tuple

    +
    +
    +
    +

    See also

    +

    translate()

    +
    +
    + +
    +
    +

    pylib.geometry_plot module

    +

    2D geometry plotter using matplotlib (pylab).

    +
    +
    Date
    +

    2019-08-20

    +
    +
    +
    +
    +plot_cubic_lines(lns, **kwargs)[source]
    +
    + +
    +
    +plot_lines(lns, **kwargs)[source]
    +
    + +
    +
    +

    pylib.mathematics module

    +

    Mathematical functions.

    +
    +
    Date
    +

    2019-10-30

    +
    +
    +
    +
    +lcm(a, b)[source]
    +

    Compute the lowest common multiple of a and b

    +
    + +
    +
    +

    pylib.time_of_day module

    +

    Calculate time.

    +
    +
    Date
    +

    2019-06-01

    +
    +
    +
    +
    +days(time)[source]
    +

    The days of the time (year).

    +
    +
    Parameters
    +

    time (float or time.struct_time) – the time in seconds

    +
    +
    Returns
    +

    hours, range [0, 365.2425]

    +
    +
    Return type
    +

    float

    +
    +
    +
    + +
    +
    +days_norm(time)[source]
    +

    The days normalized to 365.2425 (Gregorian, on average) days.

    +
    +
    Parameters
    +

    time (float or time.struct_time) – the time in seconds

    +
    +
    Returns
    +

    the normalized days, range [0, 1]

    +
    +
    Return type
    +

    float

    +
    +
    +
    + +
    +
    +hours(time)[source]
    +

    The hours of the time.

    +
    +
    Parameters
    +

    time (float or time.struct_time) – the time in seconds

    +
    +
    Returns
    +

    hours, range [0, 24]

    +
    +
    Return type
    +

    float

    +
    +
    +
    + +
    +
    +hours_norm(time)[source]
    +

    The hours normalized to 24 hours.

    +
    +
    Parameters
    +

    time (float or time.struct_time) – the time in seconds

    +
    +
    Returns
    +

    the normalized hours, range [0, 1]

    +
    +
    Return type
    +

    float

    +
    +
    +
    + +
    +
    +in_seconds(time)[source]
    +

    If time is time.struct_time convert to float seconds.

    +
    +
    Parameters
    +

    time (float or time.struct_time) – the time in seconds

    +
    +
    Returns
    +

    the time in seconds

    +
    +
    Return type
    +

    float

    +
    +
    +
    + +
    +
    +minutes(time)[source]
    +

    The minutes of the time.

    +
    +
    Parameters
    +

    time (float or time.struct_time) – the time in seconds

    +
    +
    Returns
    +

    minutes, range [0, 60]

    +
    +
    Return type
    +

    float

    +
    +
    +
    + +
    +
    +minutes_norm(time)[source]
    +

    The minutes normalized to 60 minutes.

    +
    +
    Parameters
    +

    time (float or time.struct_time) – the time in seconds

    +
    +
    Returns
    +

    the normalized minutes, range [0, 1]

    +
    +
    Return type
    +

    float

    +
    +
    +
    + +
    +
    +seconds(time)[source]
    +

    The seconds of the time.

    +
    +
    Parameters
    +

    time (float or time.struct_time) – the time in seconds

    +
    +
    Returns
    +

    seconds, range [0, 60]

    +
    +
    Return type
    +

    float

    +
    +
    +
    + +
    +
    +seconds_norm(time)[source]
    +

    The seconds normalized to 60 seconds.

    +
    +
    Parameters
    +

    time (float or time.struct_time) – the time in seconds

    +
    +
    Returns
    +

    the normalized seconds, range [0, 1]

    +
    +
    Return type
    +

    float

    +
    +
    +
    + +
    +
    +transform(time_norm, length, offset=0)[source]
    +

    Transform normalized time value to new length.

    +
    +
    Parameters
    +
      +
    • position_norm (float) – the normalized time value to transform

    • +
    • length (float) – the transformation

    • +
    • offset (float) – the offset (default = 0)

    • +
    +
    +
    Returns
    +

    the transformation value

    +
    +
    Return type
    +

    float

    +
    +
    +
    + +
    +
    +

    Module contents

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

    pylib.numerical package

    +
    +

    Submodules

    +
    +
    +

    pylib.numerical.fit module

    +

    Function and approximation.

    +
    +
    Date
    +

    2019-10-15

    +
    +
    +
    +
    +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()

    +
    +
    + +
    +
    +

    pylib.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
    +
    +
    +
    + +
    +
    +

    pylib.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

    +
    +
    +
    +
    +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)

    • +
    +
    +
    +
    + +
    +
    +fpi(f, xi, ti, ti1, *p, max_iterations=1000, tol=1e-09, verbose=False)[source]
    +

    Fixed-point iteration.

    +
    +
    Parameters
    +
      +
    • f (function) – the function to iterate \(f = \dot{x}(x,t)\)

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

    • +
    • ti (float) – time \(t_i\)

    • +
    • ti1 (float) – time \(t_{i+1}\)

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

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

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

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

    • +
    +
    +
    Returns
    +

    \(x_{i}\)

    +
    +
    +
    +\[x_{i,j=0} = x_{i}\]
    +
    +\[x_{i,j+1} = x_i + \dot{x}(x_{i,j}, t_{i+1})\cdot(t_{i+1}-t_i)\]
    +
    +\[\text{residuum} = \frac{\lVert x_{i,j+1}-x_{i,j}\rVert} + {\lVert x_{i,j+1} \rVert} < \varepsilon\]
    +
    +\[x_{i} = x_{i,j=\text{end}}\]
    +
    + +
    +
    +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.

    +
    + +
    +
    +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, 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)

    • +
    +
    +
    +
    + +
    +
    +

    pylib.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/search.html b/docs/build/html/search.html index f048926..c56b910 100644 --- a/docs/build/html/search.html +++ b/docs/build/html/search.html @@ -101,7 +101,7 @@ ©2019, Daniel Weschke. | - Powered by Sphinx 2.2.0 + Powered by Sphinx 2.2.1 & Alabaster 0.7.12 diff --git a/docs/build/html/searchindex.js b/docs/build/html/searchindex.js index f3894d3..7f8efaf 100644 --- a/docs/build/html/searchindex.js +++ b/docs/build/html/searchindex.js @@ -1 +1 @@ -Search.setIndex({docnames:["data","date","function","geometry","geometry_plot","index","mathematics","modules","numerical","time_of_day"],envversion:{"sphinx.domains.c":1,"sphinx.domains.changeset":1,"sphinx.domains.citation":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","function.rst","geometry.rst","geometry_plot.rst","index.rst","mathematics.rst","modules.rst","numerical.rst","time_of_day.rst"],objects:{"":{"function":[2,0,0,"-"],data:[0,0,0,"-"],date:[1,0,0,"-"],fit:[8,0,0,"-"],geometry:[3,0,0,"-"],geometry_plot:[4,0,0,"-"],integration:[8,0,0,"-"],mathematics:[6,0,0,"-"],numerical:[8,0,0,"-"],ode:[8,0,0,"-"],ode_model:[8,0,0,"-"],time_of_day:[9,0,0,"-"]},"function":{cosine_wave:[2,1,1,""],epitrochoid:[2,1,1,""],hypotrochoid:[2,1,1,""],sine_wave:[2,1,1,""],transformation:[2,1,1,""]},"numerical.fit":{gauss:[8,1,1,""],gauss_fit:[8,1,1,""]},"numerical.integration":{trapez:[8,1,1,""]},"numerical.ode":{e1:[8,1,1,""],e2:[8,1,1,""],e4:[8,1,1,""],fpi:[8,1,1,""],i1:[8,1,1,""],newmark_newtonraphson:[8,1,1,""],newmark_newtonraphson_rdk:[8,1,1,""]},"numerical.ode_model":{disk:[8,1,1,""],disk_nm:[8,1,1,""],disk_nmmdk:[8,1,1,""]},data:{fold_list:[0,1,1,""],get_id:[0,1,1,""],load:[0,1,1,""],read:[0,1,1,""],seq:[0,1,1,""],store:[0,1,1,""],unique_ending:[0,1,1,""],write:[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:{angle:[3,1,1,""],cubic:[3,1,1,""],cubic_deg:[3,1,1,""],cubics:[3,1,1,""],distance:[3,1,1,""],interpolate_hermite:[3,1,1,""],line:[3,1,1,""],lines:[3,1,1,""],rectangle:[3,1,1,""],rotate:[3,1,1,""],rotate_deg:[3,1,1,""],rotate_xy:[3,1,1,""],square:[3,1,1,""],translate:[3,1,1,""],translate_xy:[3,1,1,""]},geometry_plot:{plot_cubic_lines:[4,1,1,""],plot_lines:[4,1,1,""]},mathematics:{lcm:[6,1,1,""]},numerical:{fit:[8,0,0,"-"],integration:[8,0,0,"-"],ode:[8,0,0,"-"],ode_model:[8,0,0,"-"]},time_of_day:{days:[9,1,1,""],days_norm:[9,1,1,""],hours:[9,1,1,""],hours_norm:[9,1,1,""],in_seconds:[9,1,1,""],minutes:[9,1,1,""],minutes_norm:[9,1,1,""],seconds:[9,1,1,""],seconds_norm:[9,1,1,""],transform:[9,1,1,""]}},objnames:{"0":["py","module","Python module"],"1":["py","function","Python function"]},objtypes:{"0":"py:module","1":"py:function"},terms:{"1st":8,"2\u03c0f":2,"2nd":8,"4th":8,"9fsche_osterformel":1,"\u03bb":2,"\u03bd":2,"\u03c0":2,"\u03c6":2,"\u03c9":2,"boolean":2,"case":8,"char":0,"default":[0,2,3,8,9],"f\u00fcr":1,"float":[0,2,3,8,9],"fr\u00fchling":1,"function":[6,7,8],"gau\u00dfsch":1,"gau\u00dfsche_osterformel":1,"int":[0,1,2,3,8],"korrekturgr\u00f6\u00df":1,"m\u00e4rz":1,"m\u00e4rzdatum":1,"new":9,"return":[0,1,2,3,8,9],"s\u00e4kular":1,"s\u00e4kularzahl":1,"switch":2,"true":2,"vorw\u00e4rt":8,Das:1,The:[0,2,3,8,9],absolut:3,addit:3,against:8,algorithmu:1,als:1,also:2,amplitud:[2,8],analyt:8,angl:3,angle1:3,angle2:3,angular:2,approx:8,approxim:8,april:1,area:8,argument:[2,3],arithmet:0,around:[2,3],arrai:0,ascens:1,ascension_of_jesu:1,ascii:0,assum:3,attach:2,averag:9,backward:8,base:8,becaus:2,becom:8,begin:8,beta:8,between:[0,2,3],binari:0,bmatrix:8,bool:[0,2,8],bottom:3,bound:0,boundari:3,build:3,calcul:[1,8,9],call:2,cauchi:8,cdot:8,center:[2,3],chang:[2,3],characterist:2,choos:8,circl:2,close:0,column:0,common:[0,6],composit:8,comput:6,condit:[3,8],consecut:0,constant:0,content:7,convert:[0,9],coordin:3,cos:2,cosin:2,cosine_wav:2,counterclockwis:3,creat:0,cubic:3,cubic_deg:3,curv:2,cycl:2,dai:[1,9],data:[7,8],date:[0,2,3,4,6,7,8,9],datetim:1,datum:1,days_norm:9,ddot:8,decid:3,defin:3,definit:8,deflect:3,deform:3,degener:0,degre:[2,3],den:1,der:1,derform:3,deriv:8,des:1,describ:[2,8],deviat:[2,8],diamet:8,die:1,differ:[0,8],differenti:8,dimens:2,dimension:0,dimenson:0,direct:[2,3],disk:8,disk_nm:8,disk_nmmdk:8,displac:[3,8],distanc:[2,3],distribut:8,divid:8,doe:3,dot:8,each:[2,3],easter:1,easter_fridai:1,easter_mondai:1,easter_sundai:1,eccentr:8,edg:3,either:3,element:[0,3],empti:0,emptyset:0,end:[0,3,8],endpoint:3,entfernung:1,epitrochoid:2,equal:8,equalii:8,equat:[2,8],error:8,ersten:1,euler:8,everi:8,exampl:[3,8],expect:8,explicit:8,explizit:8,exterior:2,f_n:8,factor:[2,3],fail:0,fals:[0,2,8],fassregel:8,file:0,file_nam:0,filenam:0,first:[0,3,8],fit:7,fix:[2,8],float64:8,fnm:8,fold_list:0,follow:0,foral:8,forward:8,fourth:8,fpi:8,frac:[2,3,8],frequenc:2,fridai:1,from:[0,2,8],full:[0,8],function_cosine_wave_degre:2,function_sine_wave_degre:2,fwhm:8,gamma:8,gau:1,gauss:8,gauss_fit:8,gener:2,geometri:[4,7],geometry_plot:[3,7],get:0,get_id:0,gilt:1,given:[0,3,8],global:[3,8],global_deform:3,govern:8,gregorian:9,gregorianischen:1,half:8,has:[0,8],head:2,height:3,hermit:3,horizont:[2,3],hour:9,hours_norm:9,http:1,hyotrochoid:2,hypotrochoid:2,ids:0,implicit:8,in_second:9,inc:3,incid:3,index:[0,3,5],index_offset:3,inform:[0,8],initi:8,insid:2,integr:7,integrand:8,interior:2,interpol:3,interpolate_hermit:3,interpret:[0,2],interv:8,iter:8,its:2,jahr:1,jesu:1,johann:8,kalend:1,kalendarisch:1,keim:1,kepler:8,keplersch:8,keyword:3,kutta:8,kwarg:[3,4],kx1:0,lag:2,lambda:[2,8],lcm:[2,6],ldot:8,lead:2,left:[0,2,3,8],leftrightarrow:8,length:[0,3,9],leq:8,lhd:3,limit:8,limits_:8,limits_a:8,line:3,linear:2,list:[0,2,3,8],lns:4,load:0,local:8,lower:[0,8],lowest:6,lst:0,lvd:3,lvert:8,manipul:0,march:1,mathemat:[2,7],mathmat:8,mathrm:[2,8],matplotlib:4,max_iter:8,maximum:8,mean:8,method:8,minumum:0,minut:9,minutes_norm:9,model:8,modul:[5,7],mondai:1,mondparamet:1,mondschaltung:1,move:2,multipl:6,mxn:0,ndarrai:8,necessari:8,necessarili:8,newmark:8,newmark_newtonraphson:8,newmark_newtonraphson_rdk:8,node:3,non:2,none:[0,3,8],normal:9,number:[2,3,8],numer:7,numerisch:8,numpi:8,object:[0,3],object_data:0,occur:2,ode:7,ode_model:7,offset:[8,9],often:2,omega:2,one:[0,3,8],onli:0,open:0,option:[2,3],order:[3,8],ordinari:[2,8],org:1,origin:3,oscil:2,osterentfernung:1,osterformel:1,ostergrenz:1,ostersonntag:1,other:3,otherwis:3,outsid:2,over:2,packag:7,page:5,paramet:[0,1,2,3,8,9],peak:2,pentecost:1,per:[2,8],period:2,phase:2,phi:2,plane:3,plot:3,plot_cubic_lin:4,plot_lin:[3,4],plotter:4,point1:3,point1_i:3,point1_x:3,point2:3,point2_i:3,point2_x:3,point3:3,point4:3,point:[2,3,8],point_i:3,point_x:3,points1_i:3,polygon:3,polygonzugverfahren:8,popt:8,posit:[2,8],position_norm:9,print:[3,8],problem:8,program:0,propag:2,proport:8,proportion:2,pts:3,pylab:4,pylib:[],quad:8,quadratur:8,radian:[2,3],radiu:2,rang:9,rate:2,read:0,rectangl:3,relat:2,repres:2,residuum:8,result:2,rhd:3,right:[0,2,3,8],roation:3,roll:2,rotat:[3,8],rotate_deg:3,rotate_xi:3,rotation_plan:3,rule:8,rung:8,rvd:3,rvert:8,said:2,same:0,sampl:3,sample_point1_x:3,sample_point2_i:3,sample_point2_x:3,sample_points1_i:3,save_valu:8,scale:2,scale_horizont:2,scale_i:3,scale_vert:2,scale_x:3,sche:8,search:5,second:[0,2,3,8,9],seconds_norm:9,segment:8,seq:0,sequenc:0,set:8,shift:2,shift_horizont:2,shift_vert:2,should:3,side:8,sigma:8,simpson:8,simpsonregel:8,sin:2,sine:2,sine_wav:2,sinusoid:2,size:[0,3,8],slope:3,smooth:2,solid:3,solut:8,solv:8,solver:8,sonnenschaltung:1,sonntag:1,sourc:[0,1,2,3,4,6,8,9],space:8,spacial:1,spatial:2,special:8,specifi:[2,8],speed:2,sqrt:8,squar:[3,8],stabl:8,standard:8,start:[0,2,3],step:[0,8],stop:0,store:0,str:0,straight:3,string:3,struct_tim:9,structur:0,subinterv:8,submodul:7,sum:8,sundai:1,system:[3,8],t_0:8,t_i:8,tabl:3,tagen:1,term:0,text:8,than:[0,3],theata:[],therefor:8,theta:2,theta_end:2,thi:[2,3],thick:8,thoma:8,ti1:8,time:[2,8,9],time_norm:9,time_of_dai:7,tol:8,toler:8,top:3,torqu:8,transform:[2,9],translat:3,translate_xi:3,trapez:8,trapezium:8,trapezoid:8,trapezregel:8,tupl:[0,2,3,8],two:[0,3,8],type:[0,1,2,3,8,9],typr:2,uid:0,uniqu:0,unique_end:0,unit:2,upper:[0,8],used:8,using:[4,8],usw:1,valu:[8,9],varepsilon:8,variabl:[1,2,8],varianc:8,varphi:2,vec:3,vector:3,veloc:8,verbos:[0,8],verfahren:8,vert_0:8,vert_a:8,vertcal:3,vertic:[2,3,8],vollmond:1,von:1,wave:2,wavelength:2,wavenumb:2,what:3,where:[2,8],which:[2,8],width:[3,8],wiki:1,wikipedia:1,wise:3,write:0,x_0:8,x_1:[3,8],x_2:[3,8],x_column:0,x_fit:8,x_i:8,x_n:8,xp0:8,xpn:8,xpp0:8,xppn:8,y_1:3,y_2:3,y_column:0,y_fit:8,year:[1,9],zero:2},titles:["data module","date module","function module","geometry module","geometry_plot module","Welcome to pylib\u2019s documentation!","mathematics module","pylib","numerical package","time_of_day module"],titleterms:{"function":2,content:8,data:0,date:1,document:5,fit:8,geometri:3,geometry_plot:4,indic:5,integr:8,mathemat:6,modul:[0,1,2,3,4,6,8,9],numer:8,ode:8,ode_model:8,packag:8,pylib:[5,7],submodul:8,tabl:5,time_of_dai:9,welcom:5}}) \ No newline at end of file +Search.setIndex({docnames:["data","date","function","geometry","geometry_plot","index","mathematics","modules","numerical","pylib","pylib.numerical","time_of_day"],envversion:{"sphinx.domains.c":1,"sphinx.domains.changeset":1,"sphinx.domains.citation":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","function.rst","geometry.rst","geometry_plot.rst","index.rst","mathematics.rst","modules.rst","numerical.rst","pylib.rst","pylib.numerical.rst","time_of_day.rst"],objects:{"":{"function":[9,0,0,"-"],data:[9,0,0,"-"],date:[9,0,0,"-"],fit:[10,0,0,"-"],geometry:[9,0,0,"-"],geometry_plot:[9,0,0,"-"],integration:[10,0,0,"-"],mathematics:[9,0,0,"-"],numerical:[8,0,0,"-"],ode:[10,0,0,"-"],ode_model:[10,0,0,"-"],pylib:[9,0,0,"-"],time_of_day:[9,0,0,"-"]},"function":{cosine_wave:[2,1,1,""],epitrochoid:[2,1,1,""],hypotrochoid:[2,1,1,""],sine_wave:[2,1,1,""],to_str:[2,1,1,""],transformation:[2,1,1,""]},"numerical.fit":{gauss:[8,1,1,""],gauss_fit:[8,1,1,""]},"numerical.integration":{trapez:[8,1,1,""]},"numerical.ode":{e1:[8,1,1,""],e2:[8,1,1,""],e4:[8,1,1,""],fpi:[8,1,1,""],i1:[8,1,1,""],newmark_newtonraphson:[8,1,1,""],newmark_newtonraphson_rdk:[8,1,1,""]},"numerical.ode_model":{disk:[8,1,1,""],disk_nm:[8,1,1,""],disk_nmmdk:[8,1,1,""]},"pylib.data":{fold_list:[9,1,1,""],get_id:[9,1,1,""],load:[9,1,1,""],read:[9,1,1,""],seq:[9,1,1,""],store:[9,1,1,""],unique_ending:[9,1,1,""],write:[9,1,1,""]},"pylib.date":{"gau\u00dfsche_osterformel":[9,1,1,""],ascension_of_jesus:[9,1,1,""],easter_friday:[9,1,1,""],easter_monday:[9,1,1,""],easter_sunday:[9,1,1,""],pentecost:[9,1,1,""]},"pylib.function":{cosine_wave:[9,1,1,""],epitrochoid:[9,1,1,""],hypotrochoid:[9,1,1,""],sine_wave:[9,1,1,""],to_str:[9,1,1,""],transformation:[9,1,1,""]},"pylib.geometry":{angle:[9,1,1,""],cubic:[9,1,1,""],cubic_deg:[9,1,1,""],cubics:[9,1,1,""],distance:[9,1,1,""],interpolate_hermite:[9,1,1,""],line:[9,1,1,""],lines:[9,1,1,""],rectangle:[9,1,1,""],rotate:[9,1,1,""],rotate_deg:[9,1,1,""],rotate_xy:[9,1,1,""],square:[9,1,1,""],translate:[9,1,1,""],translate_xy:[9,1,1,""]},"pylib.geometry_plot":{plot_cubic_lines:[9,1,1,""],plot_lines:[9,1,1,""]},"pylib.mathematics":{lcm:[9,1,1,""]},"pylib.numerical":{fit:[10,0,0,"-"],integration:[10,0,0,"-"],ode:[10,0,0,"-"],ode_model:[10,0,0,"-"]},"pylib.numerical.fit":{gauss:[10,1,1,""],gauss_fit:[10,1,1,""]},"pylib.numerical.integration":{trapez:[10,1,1,""]},"pylib.numerical.ode":{e1:[10,1,1,""],e2:[10,1,1,""],e4:[10,1,1,""],fpi:[10,1,1,""],i1:[10,1,1,""],newmark_newtonraphson:[10,1,1,""],newmark_newtonraphson_rdk:[10,1,1,""]},"pylib.numerical.ode_model":{disk:[10,1,1,""],disk_nm:[10,1,1,""],disk_nmmdk:[10,1,1,""]},"pylib.time_of_day":{days:[9,1,1,""],days_norm:[9,1,1,""],hours:[9,1,1,""],hours_norm:[9,1,1,""],in_seconds:[9,1,1,""],minutes:[9,1,1,""],minutes_norm:[9,1,1,""],seconds:[9,1,1,""],seconds_norm:[9,1,1,""],transform:[9,1,1,""]},data:{fold_list:[0,1,1,""],get_id:[0,1,1,""],load:[0,1,1,""],read:[0,1,1,""],seq:[0,1,1,""],store:[0,1,1,""],unique_ending:[0,1,1,""],write:[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:{angle:[3,1,1,""],cubic:[3,1,1,""],cubic_deg:[3,1,1,""],cubics:[3,1,1,""],distance:[3,1,1,""],interpolate_hermite:[3,1,1,""],line:[3,1,1,""],lines:[3,1,1,""],rectangle:[3,1,1,""],rotate:[3,1,1,""],rotate_deg:[3,1,1,""],rotate_xy:[3,1,1,""],square:[3,1,1,""],translate:[3,1,1,""],translate_xy:[3,1,1,""]},geometry_plot:{plot_cubic_lines:[4,1,1,""],plot_lines:[4,1,1,""]},mathematics:{lcm:[6,1,1,""]},numerical:{fit:[8,0,0,"-"],integration:[8,0,0,"-"],ode:[8,0,0,"-"],ode_model:[8,0,0,"-"]},pylib:{"function":[9,0,0,"-"],data:[9,0,0,"-"],date:[9,0,0,"-"],geometry:[9,0,0,"-"],geometry_plot:[9,0,0,"-"],mathematics:[9,0,0,"-"],numerical:[10,0,0,"-"],time_of_day:[9,0,0,"-"]},time_of_day:{days:[11,1,1,""],days_norm:[11,1,1,""],hours:[11,1,1,""],hours_norm:[11,1,1,""],in_seconds:[11,1,1,""],minutes:[11,1,1,""],minutes_norm:[11,1,1,""],seconds:[11,1,1,""],seconds_norm:[11,1,1,""],transform:[11,1,1,""]}},objnames:{"0":["py","module","Python module"],"1":["py","function","Python function"]},objtypes:{"0":"py:module","1":"py:function"},terms:{"1st":[8,10],"259f":[2,9],"28ff":[2,9],"2\u03c0f":[2,9],"2nd":[8,10],"4th":[8,10],"9fsche_osterformel":[1,9],"\u03bb":[2,9],"\u03bd":[2,9],"\u03c0":[2,9],"\u03c6":[2,9],"\u03c9":[2,9],"boolean":[2,9],"case":[2,8,9,10],"char":[0,2,9],"default":[0,2,3,8,9,10,11],"f\u00fcr":[1,9],"float":[0,2,3,8,9,10,11],"fr\u00fchling":[1,9],"function":[6,7,8,10],"gau\u00dfsch":[1,9],"gau\u00dfsche_osterformel":[1,9],"int":[0,1,2,3,8,9,10],"korrekturgr\u00f6\u00df":[1,9],"m\u00e4rz":[1,9],"m\u00e4rzdatum":[1,9],"new":[9,11],"return":[0,1,2,3,8,9,10,11],"s\u00e4kular":[1,9],"s\u00e4kularzahl":[1,9],"switch":[2,9],"true":[2,9],"vorw\u00e4rt":[8,10],Das:[1,9],The:[0,2,3,8,9,10,11],_____:[2,9],absolut:[3,9],addit:[3,9],against:[8,10],algorithmu:[1,9],alia:[2,9],als:[1,9],also:[2,9],amplitud:[2,8,9,10],analyt:[8,10],angl:[3,9],angle1:[3,9],angle2:[3,9],angular:[2,9],anim:[2,9],approx:[8,10],approxim:[8,10],april:[1,9],area:[8,10],argument:[2,3,9],arithmet:[0,9],around:[2,3,9],arrai:[0,9],ascens:[1,9],ascension_of_jesu:[1,9],ascii:[0,9],assum:[3,9],attach:[2,9],averag:[9,11],axi:[2,9],backward:[8,10],base:[8,10],becaus:[2,9],becom:[8,10],begin:[8,10],beta:[8,10],between:[0,2,3,9],binari:[0,9],block:[2,9],bmatrix:[8,10],bool:[0,2,8,9,10],bottom:[2,3,9],bound:[0,9],boundari:[3,9],braill:[2,9],build:[3,9],calcul:[1,8,9,10,11],call:[2,9],cauchi:[8,10],cdot:[8,10],center:[2,3,9],chang:[2,3,9],char_set:[2,9],charact:[2,9],characterist:[2,9],chart:[2,9],choos:[8,10],circl:[2,9],close:[0,9],column:[0,2,9],common:[0,6,9],composit:[8,10],comput:[6,9],condit:[3,8,9,10],consecut:[0,9],constant:[0,9],content:7,convert:[0,9,11],coordin:[3,9],cos:[2,9],cosin:[2,9],cosine_wav:[2,9],cosine_wave_degre:[],counterclockwis:[3,9],creat:[0,9],cubic:[3,9],cubic_deg:[3,9],cudb:[2,9],curv:[2,9],cycl:[2,9],dai:[1,9,11],data:[2,7,8,10],databas:[2,9],date:[0,2,3,4,6,7,8,10,11],datetim:[1,9],datum:[1,9],days_norm:[9,11],ddot:[8,10],decid:[3,9],defin:[3,9],definit:[8,10],deflect:[3,9],deform:[3,9],degener:[0,9],degre:[2,3,9],den:[1,9],densiti:[2,9],depend:[2,9],der:[1,9],derform:[3,9],deriv:[8,10],des:[1,9],describ:[2,8,9,10],deviat:[2,8,9,10],diamet:[8,10],die:[1,9],differ:[0,8,9,10],differenti:[8,10],dimens:[2,9],dimension:[0,9],dimenson:[0,9],direct:[2,3,9],disk:[8,10],disk_nm:[8,10],disk_nmmdk:[8,10],displac:[3,8,9,10],distanc:[2,3,9],distribut:[8,10],divid:[8,10],doe:[2,3,9],dot:[2,8,9,10],down:[2,9],drawil:[2,9],each:[2,3,9],easter:[1,9],easter_fridai:[1,9],easter_mondai:[1,9],easter_sundai:[1,9],eccentr:[8,10],edg:[3,9],either:[2,3,9],element:[0,2,3,9],empti:[0,9],emptyset:[0,9],end:[0,3,8,9,10],endpoint:[3,9],entfernung:[1,9],epitrochoid:[2,9],equal:[8,10],equalii:[8,10],equat:[2,8,9,10],error:[8,10],ersten:[1,9],euler:[8,10],everi:[8,10],exampl:[2,3,8,9,10],expect:[8,10],explicit:[8,10],explizit:[8,10],exterior:[2,9],f_n:[8,10],factor:[2,3,9],fail:[0,9],fals:[0,2,8,9,10],fassregel:[8,10],file:[0,9],file_nam:[0,9],filenam:[0,9],first:[0,2,3,8,9,10],fisrt:[2,9],fit:[7,9],fix:[2,8,9,10],float64:[8,10],fnm:[8,10],fold_list:[0,9],follow:[0,9],foral:[8,10],forward:[8,10],fourth:[8,10],fpi:[8,10],frac:[2,3,8,9,10],frame:[2,9],frequenc:[2,9],fridai:[1,9],from:[0,2,8,9,10],full:[0,8,9,10],function_cosine_wave_degre:[],function_sine_wave_degre:[],fwhm:[8,10],gamma:[8,10],gau:[1,9],gauss:[8,10],gauss_fit:[8,10],gener:[2,9],geometri:[4,7],geometry_plot:[3,7],get:[0,9],get_id:[0,9],gilt:[1,9],given:[0,3,8,9,10],global:[3,8,9,10],global_deform:[3,9],govern:[8,10],gregorian:[9,11],gregorianischen:[1,9],half:[8,10],has:[0,8,9,10],have:[2,9],head:[2,9],height:[3,9],hermit:[3,9],higher:[2,9],histogram:[2,9],horizont:[2,3,9],hour:[9,11],hours_norm:[9,11],http:[1,9],hyotrochoid:[2,9],hypotrochoid:[2,9],ids:[0,9],implicit:[8,10],in_second:[9,11],inc:[3,9],incid:[3,9],index:[0,2,3,5,9],index_offset:[3,9],inform:[0,8,9,10],initi:[8,10],insid:[2,9],integr:[7,9],integrand:[8,10],interior:[2,9],interpol:[3,9],interpolate_hermit:[3,9],interpret:[0,2,9],interv:[8,10],iter:[8,10],its:[2,9],jahr:[1,9],jesu:[1,9],johann:[8,10],kalend:[1,9],kalendarisch:[1,9],keim:[1,9],kepler:[8,10],keplersch:[8,10],keyword:[3,9],kutta:[8,10],kwarg:[3,4,9],kx1:[0,9],lag:[2,9],lambda:[2,8,9,10],last:[2,9],lcm:[2,6,9],ldot:[8,10],lead:[2,9],left:[0,2,3,8,9,10],leftrightarrow:[8,10],length:[0,3,9,11],leq:[8,10],lhd:[3,9],limit:[8,10],limits_:[8,10],limits_a:[8,10],line:[2,3,9],linear:[2,9],list:[0,2,3,8,9,10],lns:[4,9],load:[0,9],local:[8,10],lower:[0,8,9,10],lowest:[6,9],lst:[0,9],lvd:[3,9],lvert:[8,10],make:[2,9],manipul:[0,9],march:[1,9],mathemat:[2,7],mathmat:[8,10],mathrm:[2,8,9,10],matplotlib:[4,9],max:[2,9],max_iter:[8,10],maximum:[8,10],mean:[2,8,9,10],method:[8,10],min:[2,9],minumum:[0,9],minut:[9,11],minutes_norm:[9,11],model:[8,10],modul:[5,7],mondai:[1,9],mondparamet:[1,9],mondschaltung:[1,9],move:[2,9],multipl:[6,9],mxn:[0,9],ndarrai:[8,10],necessari:[8,10],necessarili:[8,10],newmark:[8,10],newmark_newtonraphson:[8,10],newmark_newtonraphson_rdk:[8,10],node:[3,9],non:[2,9],none:[0,2,3,8,9,10],norm:[2,9],normal:[2,9,11],number:[2,3,8,9,10],numer:[7,9],numerisch:[8,10],numpi:[8,10],object:[0,3,9],object_data:[0,9],occur:[2,9],ode:[7,9],ode_model:[7,9],offset:[8,9,10,11],often:[2,9],omega:[2,9],one:[0,2,3,8,9,10],onli:[0,9],open:[0,9],option:[2,3,9],order:[3,8,9,10],ordinari:[2,8,9,10],org:[1,9],origin:[3,9],oscil:[2,9],osterentfernung:[1,9],osterformel:[1,9],ostergrenz:[1,9],ostersonntag:[1,9],other:[3,9],otherwis:[3,9],outsid:[2,9],over:[2,9],packag:7,page:5,paramet:[0,1,2,3,8,9,10,11],part:[2,9],pattern:[2,9],peak:[2,9],pentecost:[1,9],per:[2,8,9,10],period:[2,9],phase:[2,9],phi:[2,9],pixel:[2,9],plane:[3,9],plot:[2,3,9],plot_cubic_lin:[4,9],plot_lin:[3,4,9],plotter:[4,9],point1:[3,9],point1_i:[3,9],point1_x:[3,9],point2:[3,9],point2_i:[3,9],point2_x:[3,9],point3:[3,9],point4:[3,9],point:[2,3,8,9,10],point_i:[3,9],point_x:[3,9],points1_i:[3,9],polygon:[3,9],polygonzugverfahren:[8,10],popt:[8,10],posit:[2,8,9,10],position_norm:[9,11],print:[3,8,9,10],problem:[8,10],program:[0,9],propag:[2,9],proport:[8,10],proportion:[2,9],pts:[3,9],pylab:[4,9],pylib:2,quad:[8,10],quadratur:[8,10],quasi:[2,9],radian:[2,3,9],radiu:[2,9],rang:[2,9,11],rate:[2,9],read:[0,9],rectangl:[3,9],refer:[2,9],relat:[2,9],repres:[2,9],residuum:[8,10],result:[2,9],rhd:[3,9],right:[0,2,3,8,9,10],roation:[3,9],roll:[2,9],rotat:[3,8,9,10],rotate_deg:[3,9],rotate_xi:[3,9],rotation_plan:[3,9],row:[2,9],rule:[8,10],rung:[8,10],rvd:[3,9],rvert:[8,10],said:[2,9],same:[0,9],sampl:[3,9],sample_point1_x:[3,9],sample_point2_i:[3,9],sample_point2_x:[3,9],sample_points1_i:[3,9],save_valu:[8,10],scale:[2,9],scale_horizont:[2,9],scale_i:[3,9],scale_vert:[2,9],scale_x:[3,9],sche:[8,10],search:5,second:[0,2,3,8,9,10,11],seconds_norm:[9,11],segment:[8,10],seq:[0,9],sequenc:[0,9],set:[2,8,9,10],shift:[2,9],shift_horizont:[2,9],shift_vert:[2,9],should:[3,9],side:[8,10],sigma:[8,10],simpson:[8,10],simpsonregel:[8,10],sin:[2,9],sine:[2,9],sine_wav:[2,9],sine_wave_degre:[],sinusoid:[2,9],size:[0,3,8,9,10],slope:[3,9],smooth:[2,9],solid:[3,9],solut:[8,10],solv:[8,10],solver:[8,10],sonnenschaltung:[1,9],sonntag:[1,9],sourc:[0,1,2,3,4,6,8,9,10,11],space:[8,10],spacial:[1,9],spatial:[2,9],special:[8,10],specif:[2,9],specifi:[2,8,9,10],speed:[2,9],sqrt:[8,10],squar:[3,8,9,10],stabl:[8,10],standard:[8,10],start:[0,2,3,9],step:[0,8,9,10],stop:[0,9],store:[0,9],str:[0,2,9],straight:[3,9],string:[2,3,9],struct_tim:[9,11],structur:[0,9],subinterv:[8,10],submodul:7,subpackag:[],sum:[8,10],sundai:[1,9],system:[3,8,9,10],t_0:[8,10],t_i:[8,10],tabl:[3,9],tagen:[1,9],term:[0,9],text:[8,10],than:[0,3,9],theata:[],therefor:[8,10],theta:[2,9],theta_end:[2,9],thi:[2,3,9],thick:[8,10],thicker:[2,9],thoma:[8,10],ti1:[8,10],time:[2,8,9,10,11],time_norm:[9,11],time_of_dai:7,to_str:[2,9],tol:[8,10],toler:[8,10],top:[3,9],torqu:[8,10],transform:[2,9,11],translat:[3,9],translate_xi:[3,9],trapez:[8,10],trapezium:[8,10],trapezoid:[8,10],trapezregel:[8,10],tupl:[0,2,3,8,9,10],two:[0,3,8,9,10],type:[0,1,2,3,8,9,10,11],typr:[2,9],uid:[0,9],unicod:[2,9],uniqu:[0,9],unique_end:[0,9],unit:[2,9],upper:[0,8,9,10],upsid:[2,9],usag:[2,9],used:[8,10],uses:[2,9],using:[4,8,9,10],usw:[1,9],valu:[2,8,9,10,11],varepsilon:[8,10],variabl:[1,2,8,9,10],varianc:[8,10],varphi:[2,9],vec:[3,9],vector:[3,9],veloc:[8,10],verbos:[0,8,9,10],verfahren:[8,10],vert_0:[8,10],vert_a:[8,10],vertcal:[3,9],vertic:[2,3,8,9,10],view:[2,9],vollmond:[1,9],von:[1,9],wave:[2,9],wavelength:[2,9],wavenumb:[2,9],what:[3,9],where:[2,8,9,10],which:[2,8,9,10],width:[2,3,8,9,10],wiki:[1,9],wikipedia:[1,9],window:[2,9],wise:[3,9],write:[0,9],x_0:[2,8,9,10],x_1:[2,3,8,9,10],x_2:[3,8,9,10],x_column:[0,9],x_fit:[8,10],x_i:[8,10],x_n:[8,10],xp0:[8,10],xpn:[8,10],xpp0:[8,10],xppn:[8,10],y_1:[3,9],y_2:[3,9],y_column:[0,9],y_fit:[8,10],year:[1,9,11],zero:[2,9]},titles:["data module","date module","function module","geometry module","geometry_plot module","Welcome to pylib\u2019s documentation!","mathematics module","pylib","numerical package","pylib package","pylib.numerical package","time_of_day module"],titleterms:{"function":[2,9],content:[8,9,10],data:[0,9],date:[1,9],document:5,fit:[8,10],geometri:[3,9],geometry_plot:[4,9],indic:5,integr:[8,10],mathemat:[6,9],modul:[0,1,2,3,4,6,8,9,10,11],numer:[8,10],ode:[8,10],ode_model:[8,10],packag:[8,9,10],pylib:[5,7,9,10],submodul:[8,9,10],subpackag:9,tabl:5,time_of_dai:[9,11],welcom:5}}) \ No newline at end of file diff --git a/docs/build/html/time_of_day.html b/docs/build/html/time_of_day.html index 166de45..2a512ed 100644 --- a/docs/build/html/time_of_day.html +++ b/docs/build/html/time_of_day.html @@ -267,7 +267,7 @@ ©2019, Daniel Weschke. | - Powered by Sphinx 2.2.0 + Powered by Sphinx 2.2.1 & Alabaster 0.7.12 | diff --git a/docs/source/pylib.numerical.rst b/docs/source/pylib.numerical.rst new file mode 100644 index 0000000..2222ee7 --- /dev/null +++ b/docs/source/pylib.numerical.rst @@ -0,0 +1,46 @@ +pylib.numerical package +======================= + +Submodules +---------- + +pylib.numerical.fit module +-------------------------- + +.. automodule:: pylib.numerical.fit + :members: + :undoc-members: + :show-inheritance: + +pylib.numerical.integration module +---------------------------------- + +.. automodule:: pylib.numerical.integration + :members: + :undoc-members: + :show-inheritance: + +pylib.numerical.ode module +-------------------------- + +.. automodule:: pylib.numerical.ode + :members: + :undoc-members: + :show-inheritance: + +pylib.numerical.ode\_model module +--------------------------------- + +.. automodule:: pylib.numerical.ode_model + :members: + :undoc-members: + :show-inheritance: + + +Module contents +--------------- + +.. automodule:: pylib.numerical + :members: + :undoc-members: + :show-inheritance: diff --git a/docs/source/pylib.rst b/docs/source/pylib.rst new file mode 100644 index 0000000..f891b10 --- /dev/null +++ b/docs/source/pylib.rst @@ -0,0 +1,77 @@ +pylib package +============= + +Subpackages +----------- + +.. toctree:: + + pylib.numerical + +Submodules +---------- + +pylib.data module +----------------- + +.. automodule:: pylib.data + :members: + :undoc-members: + :show-inheritance: + +pylib.date module +----------------- + +.. automodule:: pylib.date + :members: + :undoc-members: + :show-inheritance: + +pylib.function module +--------------------- + +.. automodule:: pylib.function + :members: + :undoc-members: + :show-inheritance: + +pylib.geometry module +--------------------- + +.. automodule:: pylib.geometry + :members: + :undoc-members: + :show-inheritance: + +pylib.geometry\_plot module +--------------------------- + +.. automodule:: pylib.geometry_plot + :members: + :undoc-members: + :show-inheritance: + +pylib.mathematics module +------------------------ + +.. automodule:: pylib.mathematics + :members: + :undoc-members: + :show-inheritance: + +pylib.time\_of\_day module +-------------------------- + +.. automodule:: pylib.time_of_day + :members: + :undoc-members: + :show-inheritance: + + +Module contents +--------------- + +.. automodule:: pylib + :members: + :undoc-members: + :show-inheritance: diff --git a/pylib/__init__.py b/pylib/__init__.py new file mode 100644 index 0000000..84f9702 --- /dev/null +++ b/pylib/__init__.py @@ -0,0 +1,12 @@ +import os +import sys + +# Add vendor directory to module search path +project_dir = os.path.abspath(os.path.dirname(__file__)) +parent_dir = os.path.dirname(project_dir) +vendor_dir = os.path.join(parent_dir, 'vendor') + +sys.path.append(vendor_dir) + +# Now you can import any library located in the "vendor" folder! +# import drawille diff --git a/pylib/data.py b/pylib/data.py index be9e261..7f3e694 100644 --- a/pylib/data.py +++ b/pylib/data.py @@ -139,6 +139,19 @@ def seq(start, stop=None, step=1): :returns: arithmetic bounded sequence :rtype: list """ + # example of seq(4, 0, -0.4) + # without round: + # [4.0, 3.6, 3.2, 2.8, 2.4, 2.0, 1.5999999999999996, + # 1.1999999999999997, 0.7999999999999998, 0.3999999999999999] + # with round: + # [4.0, 3.6, 3.2, 2.8, 2.4, 2.0, 1.6, 1.2, 0.8, 0.4] + # example of seq(4, 0, -0.41) + # without round: + # [4.0, 3.59, 3.18, 2.77, 2.3600000000000003, + # 1.9500000000000002, 1.54, 1.1300000000000003, + # 0.7200000000000002, 0.31000000000000005] + # with round: + # [4.0, 3.59, 3.18, 2.77, 2.36, 1.95, 1.54, 1.13, 0.72, 0.31] if stop is None: return seq(0, start, step) diff --git a/pylib/function.py b/pylib/function.py index 2b330ba..7b09dfa 100644 --- a/pylib/function.py +++ b/pylib/function.py @@ -2,7 +2,7 @@ # -*- coding: utf-8 -*- """Mathematical equations. -:Date: 2019-11-04 +:Date: 2019-11-15 .. module:: function :platform: *nix, Windows @@ -112,7 +112,7 @@ def sine_wave(A=1, k=1, f=1, phi=0, D=0, degree=False): linear speed. .. seealso:: - :meth:`function_cosine_wave_degree` + :meth:`cosine_wave` """ if degree: phi = math.radians(phi) @@ -144,7 +144,7 @@ def cosine_wave(A=1, k=1, f=1, phi=0, D=0, degree=False): time t .. seealso:: - :meth:`function_sine_wave_degree` + :meth:`sine_wave` """ if degree: phi = phi + 90 @@ -250,3 +250,163 @@ def epitrochoid(R, r, d): y = lambda theta: (R+r)*math.sin(theta) - d*math.sin((R+r)/r * theta) theta_end = 2*math.pi return x, y, theta_end + +def to_str(f, x=None, x_0=0, x_1=1, t=None, h=10, w=80, density=1, char_set="line"): + """Represent functions as string frame with a specific character set. + which are normed to the range of [0, 1] to + + :param f: function or list of functions normed to the range of [0, 1] + :type f: function or list + :param h: number of chars in vertical direction + :type h: int + :param w: number of chars in horizontal direction + :type w: int + + :param char_set: either "braille" or "block". "braille" uses Unicode + Characters in the Braille Patterns Block (fisrt index U+2800, last + index U+28FF [CUDB]_) and the "block" uses part of the Unicode + Characters in the Block Elements Block (fisrt index U+2580, last + index U+259F [CUDB]_). Alias for braille is line and alias for + block is histogram + :type char_set: str + + Usage: + * case dependent arguments + + * 1 quasi line plot (braille characters) + f = lambda function (lambda x, t=0: ...) + x_1 = max x value + x_0 = min x value + t = time (animation) + * 2 histogram (block characters) + f = lambda function (lambda x, t=0: ...) + x_1 = max x value + x_0 = min x value + t = time (animation) + chart="histogram" + + * general arguments + w = window width in number of chars + density = number of data point per pixel (for line chart higher density makes thicker lines) + chart = either "line" or "histogram" + + + .. rubric:: Braille Patterns Block + + * Dots or pixels per character in vertical direction: 6 + * Dots or pixels per character in horizontal direction: 2 + + First dot (bottom left) is the zero (0) position of the + function. So, a function value of zero does not mean to have zero + dots but one. + Example of 3 columns and 3 rows (upside down view of 'normal' braille/drawille position) + + :: + + | ^ y axis + | | + | ,_____,,_____,,_____, + 7 + | * *|| * *|| * *| + 6 + | * *|| * *|| * *| + 5 + | * *|| * *|| * *| + 4 + | * *|| * *|| * *| + | ;=====;;=====;;=====; + 3 + | * *|| * *|| * *| + 2 + | * *|| * *|| * *| + 1 + | * *|| * *|| * *| + 0 + - | * *|| * *|| * *| ---> x axis + | ;=====;;=====;;=====; + -1 + | * *|| * *|| * *| + -2 + | * *|| * *|| * *| + -3 + | * *|| * *|| * *| + -4 + | * *|| * *|| * *| + | ````````````````````` + | | + `-----+--+---+--+---+--+------------- + -2 -1 0 1 2 3 + + + .. rubric:: Block Elements Block + + * Dots or pixels per character in vertical direction: 8 + * Dots or pixels per character in horizontal direction: 1 + + Example of 3 columns and 3 rows + + :: + + | ^ y axis + | | + | ,_____,,_____,,_____, + 15 + | --- || --- || --- | + 14 + | --- || --- || --- | + 13 + | --- || --- || --- | + 12 + | --- || --- || --- | + 11 + | --- || --- || --- | + 10 + | --- || --- || --- | + 9 + | --- || --- || --- | + 8 + | --- || --- || --- | + | ;=====;;=====;;=====; + 7 + | --- || --- || --- | + 6 + | --- || --- || --- | + 5 + | --- || --- || --- | + 4 + | --- || --- || --- | + 3 + | --- || --- || --- | + 2 + | --- || --- || --- | + 1 + | --- || --- || --- | + 0 + - | --- || --- || --- | ---> x axis + | ;=====;;=====;;=====; + -1 + | --- || --- || --- | + -2 + | --- || --- || --- | + -3 + | --- || --- || --- | + -4 + | --- || --- || --- | + -5 + | --- || --- || --- | + -6 + | --- || --- || --- | + -7 + | --- || --- || --- | + -8 + | --- || --- || --- | + | ````````````````````` + | | + `------+------+------+--------------- + -1 0 1 + + + .. rubric:: References + + .. [CUDB] `Unicode Database - Blocks `_ + + + .. seealso:: + :meth:`pylib.function.transformation` + """ + # scale function to used chars and dots/pixel in y direction (4 for braille characters): from [0, 1] to [0, chars*4-1] + # negate the function because the y axis is pointing downwards: from [0, 1] to [-1, 0] or from [0, chars*4-1] to [-(chars*4-1), 0] + # and becasue of the negation shift the function by one dot/pixel, otherwise the function would need another char, because the 0 is on an another char on the "positive side". + # devide the time by the number of dots/pixel in x direction (2 for braille characters) + window_factor = w/(x_1-x_0) + frame = "" + if char_set in ["line", "braille"]: + pixels_horizontal = 2 + pixels_vertical = 4 + a = -(h*pixels_vertical-1) + b = 1/pixels_horizontal + f = transformation(f, a, b, 0, -1) + + canvas = drawille.Canvas() + # divide step width of the sequence by 2 (double density, 2 dots/pixel per char) + # multiplicate x by 2 (2 dots/pixel per char) + for x_i in seq(x_0*window_factor*pixels_horizontal, x_1*window_factor*pixels_horizontal, 1/density): + canvas.set(x_i, f(x_i, t)) + #frame = canvas.frame(min_x=a*pixel_per_char, min_y=1, max_x=b*pixel_per_char, max_y=21) + frame = canvas.frame() + elif char_set in ["histogram", "block"]: + pixels_horizontal = 1 + pixels_vertical = 8 + a = h*pixels_vertical-1 + f = transformation(f, a, 1, 0, 0) + + density = min(density, 1) # density max 1! + x = seq(x_0*window_factor, x_1*window_factor, 1/pixels_horizontal/density) + f = [f(xi, t) for xi in x] + frame = drawblock.histogram(f, x) + + return frame diff --git a/vendor/drawille.py b/vendor/drawille.py new file mode 100644 index 0000000..7969d06 --- /dev/null +++ b/vendor/drawille.py @@ -0,0 +1,417 @@ +# -*- coding: utf-8 -*- + +# drawille is free software: you can redistribute it and/or modify +# it under the terms of the GNU Affero General Public License as published by +# the Free Software Foundation, either version 3 of the License, or +# (at your option) any later version. +# +# drawille is distributed in the hope that it will be useful, +# but WITHOUT ANY WARRANTY; without even the implied warranty of +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +# GNU Affero General Public License for more details. +# +# You should have received a copy of the GNU Affero General Public License +# along with drawille. If not, see < http://www.gnu.org/licenses/ >. +# +# (C) 2014- by Adam Tauber, + +import math +import os +from sys import version_info +from collections import defaultdict +from time import sleep +import curses + +IS_PY3 = version_info[0] == 3 + +if IS_PY3: + unichr = chr + +""" + +http://www.alanwood.net/unicode/braille_patterns.html + +dots: + ,___, + |1 4| + |2 5| + |3 6| + |7 8| + ````` +""" + +pixel_map = ((0x01, 0x08), + (0x02, 0x10), + (0x04, 0x20), + (0x40, 0x80)) + +# braille unicode characters starts at 0x2800 +braille_char_offset = 0x2800 + + +# http://stackoverflow.com/questions/566746/how-to-get-console-window-width-in-python +def getTerminalSize(): + """Returns terminal width, height + """ + env = os.environ + + def ioctl_GWINSZ(fd): + try: + import fcntl, termios, struct + cr = struct.unpack('hh', fcntl.ioctl(fd, termios.TIOCGWINSZ, '1234')) + except: + return + return cr + + cr = ioctl_GWINSZ(0) or ioctl_GWINSZ(1) or ioctl_GWINSZ(2) + + if not cr: + try: + fd = os.open(os.ctermid(), os.O_RDONLY) + cr = ioctl_GWINSZ(fd) + os.close(fd) + except: + pass + + if not cr: + cr = (env.get('LINES', 25), env.get('COLUMNS', 80)) + + return int(cr[1]), int(cr[0]) + + +def normalize(coord): + coord_type = type(coord) + + if coord_type == int: + return coord + elif coord_type == float: + return int(round(coord)) + else: + raise TypeError("Unsupported coordinate type <{0}>".format(type(coord))) + + +def intdefaultdict(): + return defaultdict(int) + + +def get_pos(x, y): + """Convert x, y to cols, rows""" + return normalize(x) // 2, normalize(y) // 4 + + +class Canvas(object): + """This class implements the pixel surface.""" + + def __init__(self, line_ending=os.linesep): + super(Canvas, self).__init__() + self.clear() + self.line_ending = line_ending + + + def clear(self): + """Remove all pixels from the :class:`Canvas` object.""" + self.chars = defaultdict(intdefaultdict) + + + def set(self, x, y): + """Set a pixel of the :class:`Canvas` object. + + :param x: x coordinate of the pixel + :param y: y coordinate of the pixel + """ + x = normalize(x) + y = normalize(y) + col, row = get_pos(x, y) + + if type(self.chars[row][col]) != int: + return + + self.chars[row][col] |= pixel_map[y % 4][x % 2] + + + def unset(self, x, y): + """Unset a pixel of the :class:`Canvas` object. + + :param x: x coordinate of the pixel + :param y: y coordinate of the pixel + """ + x = normalize(x) + y = normalize(y) + col, row = get_pos(x, y) + + if type(self.chars[row][col]) == int: + self.chars[row][col] &= ~pixel_map[y % 4][x % 2] + + if type(self.chars[row][col]) != int or self.chars[row][col] == 0: + del(self.chars[row][col]) + + if not self.chars.get(row): + del(self.chars[row]) + + + def toggle(self, x, y): + """Toggle a pixel of the :class:`Canvas` object. + + :param x: x coordinate of the pixel + :param y: y coordinate of the pixel + """ + x = normalize(x) + y = normalize(y) + col, row = get_pos(x, y) + + if type(self.chars[row][col]) != int or self.chars[row][col] & pixel_map[y % 4][x % 2]: + self.unset(x, y) + else: + self.set(x, y) + + + def set_text(self, x, y, text): + """Set text to the given coords. + + :param x: x coordinate of the text start position + :param y: y coordinate of the text start position + """ + col, row = get_pos(x, y) + + for i,c in enumerate(text): + self.chars[row][col+i] = c + + + def get(self, x, y): + """Get the state of a pixel. Returns bool. + + :param x: x coordinate of the pixel + :param y: y coordinate of the pixel + """ + x = normalize(x) + y = normalize(y) + dot_index = pixel_map[y % 4][x % 2] + col, row = get_pos(x, y) + char = self.chars.get(row, {}).get(col) + + if not char: + return False + + if type(char) != int: + return True + + return bool(char & dot_index) + + + def rows(self, min_x=None, min_y=None, max_x=None, max_y=None): + """Returns a list of the current :class:`Canvas` object lines. + + :param min_x: (optional) minimum x coordinate of the canvas + :param min_y: (optional) minimum y coordinate of the canvas + :param max_x: (optional) maximum x coordinate of the canvas + :param max_y: (optional) maximum y coordinate of the canvas + """ + + if not self.chars.keys(): + return [] + + minrow = min_y // 4 if min_y != None else min(self.chars.keys()) + maxrow = (max_y - 1) // 4 if max_y != None else max(self.chars.keys()) + mincol = min_x // 2 if min_x != None else min(min(x.keys()) for x in self.chars.values()) + maxcol = (max_x - 1) // 2 if max_x != None else max(max(x.keys()) for x in self.chars.values()) + ret = [] + + for rownum in range(minrow, maxrow+1): + if not rownum in self.chars: + ret.append('') + continue + + maxcol = (max_x - 1) // 2 if max_x != None else max(self.chars[rownum].keys()) + row = [] + + for x in range(mincol, maxcol+1): + char = self.chars[rownum].get(x) + + if not char: + row.append(unichr(braille_char_offset)) + elif type(char) != int: + row.append(char) + else: + row.append(unichr(braille_char_offset+char)) + + ret.append(''.join(row)) + + return ret + + + def frame(self, min_x=None, min_y=None, max_x=None, max_y=None): + """String representation of the current :class:`Canvas` object pixels. + + :param min_x: (optional) minimum x coordinate of the canvas + :param min_y: (optional) minimum y coordinate of the canvas + :param max_x: (optional) maximum x coordinate of the canvas + :param max_y: (optional) maximum y coordinate of the canvas + """ + ret = self.line_ending.join(self.rows(min_x, min_y, max_x, max_y)) + + if IS_PY3: + return ret + + return ret.encode('utf-8') + + +def line(x1, y1, x2, y2): + """Returns the coords of the line between (x1, y1), (x2, y2) + + :param x1: x coordinate of the startpoint + :param y1: y coordinate of the startpoint + :param x2: x coordinate of the endpoint + :param y2: y coordinate of the endpoint + """ + + x1 = normalize(x1) + y1 = normalize(y1) + x2 = normalize(x2) + y2 = normalize(y2) + + xdiff = max(x1, x2) - min(x1, x2) + ydiff = max(y1, y2) - min(y1, y2) + xdir = 1 if x1 <= x2 else -1 + ydir = 1 if y1 <= y2 else -1 + + r = max(xdiff, ydiff) + + for i in range(r+1): + x = x1 + y = y1 + + if ydiff: + y += (float(i) * ydiff) / r * ydir + if xdiff: + x += (float(i) * xdiff) / r * xdir + + yield (x, y) + + +def polygon(center_x=0, center_y=0, sides=4, radius=4): + degree = float(360) / sides + + for n in range(sides): + a = n * degree + b = (n + 1) * degree + x1 = (center_x + math.cos(math.radians(a))) * (radius + 1) / 2 + y1 = (center_y + math.sin(math.radians(a))) * (radius + 1) / 2 + x2 = (center_x + math.cos(math.radians(b))) * (radius + 1) / 2 + y2 = (center_y + math.sin(math.radians(b))) * (radius + 1) / 2 + + for x, y in line(x1, y1, x2, y2): + yield x, y + + +class Turtle(Canvas): + """Turtle graphics interface + http://en.wikipedia.org/wiki/Turtle_graphics + """ + + def __init__(self, pos_x=0, pos_y=0): + self.pos_x = pos_x + self.pos_y = pos_y + self.rotation = 0 + self.brush_on = True + super(Turtle, self).__init__() + + + def up(self): + """Pull the brush up.""" + self.brush_on = False + + + def down(self): + """Push the brush down.""" + self.brush_on = True + + + def forward(self, step): + """Move the turtle forward. + + :param step: Integer. Distance to move forward. + """ + x = self.pos_x + math.cos(math.radians(self.rotation)) * step + y = self.pos_y + math.sin(math.radians(self.rotation)) * step + prev_brush_state = self.brush_on + self.brush_on = True + self.move(x, y) + self.brush_on = prev_brush_state + + + def move(self, x, y): + """Move the turtle to a coordinate. + + :param x: x coordinate + :param y: y coordinate + """ + if self.brush_on: + for lx, ly in line(self.pos_x, self.pos_y, x, y): + self.set(lx, ly) + + self.pos_x = x + self.pos_y = y + + + def right(self, angle): + """Rotate the turtle (positive direction). + + :param angle: Integer. Rotation angle in degrees. + """ + self.rotation += angle + + + def left(self, angle): + """Rotate the turtle (negative direction). + + :param angle: Integer. Rotation angle in degrees. + """ + self.rotation -= angle + + + def back(self, step): + """Move the turtle backwards. + + :param step: Integer. Distance to move backwards. + """ + self.forward(-step) + + + # aliases + pu = up + pd = down + fd = forward + mv = move + rt = right + lt = left + bk = back + + +def animate(canvas, fn, delay=1./24, *args, **kwargs): + """Animation automatition function + + :param canvas: :class:`Canvas` object + :param fn: Callable. Frame coord generator + :param delay: Float. Delay between frames. + :param *args, **kwargs: optional fn parameters + """ + + # python2 unicode curses fix + if not IS_PY3: + import locale + locale.setlocale(locale.LC_ALL, "") + + def animation(stdscr): + + for frame in fn(*args, **kwargs): + for x,y in frame: + canvas.set(x,y) + + f = canvas.frame() + stdscr.addstr(0, 0, '{0}\n'.format(f)) + stdscr.refresh() + if delay: + sleep(delay) + canvas.clear() + + curses.wrapper(animation)