├── src ├── __init__.py ├── utils │ ├── __init__.py │ ├── calculator.py │ ├── parser.py │ └── drawer.py ├── attractors │ ├── __init__.py │ ├── wang.py │ ├── nose_hoover.py │ ├── rikitake.py │ ├── lotka_volterra.py │ ├── lorenz.py │ ├── chua.py │ ├── rossler.py │ ├── attractor.py │ └── duffing.py └── dynamic_system.py ├── img ├── Wang_3D.png ├── Chua1_3D.png ├── Chua2_3D.png ├── Duffing_3D.png ├── Lorenz_3D.png ├── Lorenz_3d.gif ├── Lotka_3D.png ├── Rossler_3D.png ├── Rikitake_3D.png ├── Lorenz_Spectrum.png └── Nose_Hoover_3D.png ├── requirements.txt ├── Dockerfile ├── run.py ├── tests ├── test_drawer.py ├── test_attractor.py ├── test_chua.py └── conftest.py ├── pyproject.toml ├── .pre-commit-config.yaml ├── .gitignore ├── README.rst └── LICENSE /src/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/utils/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/attractors/__init__.py: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /img/Wang_3D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hukenovs/chaospy/HEAD/img/Wang_3D.png -------------------------------------------------------------------------------- /img/Chua1_3D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hukenovs/chaospy/HEAD/img/Chua1_3D.png -------------------------------------------------------------------------------- /img/Chua2_3D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hukenovs/chaospy/HEAD/img/Chua2_3D.png -------------------------------------------------------------------------------- /img/Duffing_3D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hukenovs/chaospy/HEAD/img/Duffing_3D.png -------------------------------------------------------------------------------- /img/Lorenz_3D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hukenovs/chaospy/HEAD/img/Lorenz_3D.png -------------------------------------------------------------------------------- /img/Lorenz_3d.gif: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hukenovs/chaospy/HEAD/img/Lorenz_3d.gif -------------------------------------------------------------------------------- /img/Lotka_3D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hukenovs/chaospy/HEAD/img/Lotka_3D.png -------------------------------------------------------------------------------- /img/Rossler_3D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hukenovs/chaospy/HEAD/img/Rossler_3D.png -------------------------------------------------------------------------------- /img/Rikitake_3D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hukenovs/chaospy/HEAD/img/Rikitake_3D.png -------------------------------------------------------------------------------- /img/Lorenz_Spectrum.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hukenovs/chaospy/HEAD/img/Lorenz_Spectrum.png -------------------------------------------------------------------------------- /img/Nose_Hoover_3D.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/hukenovs/chaospy/HEAD/img/Nose_Hoover_3D.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | matplotlib==3.5.1 2 | numpy==1.22.0 3 | pandas==1.3.4 4 | pre-commit==2.16.0 5 | pytest==6.2.5 6 | scipy==1.10.0 7 | -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3 2 | WORKDIR /app 3 | COPY . /app 4 | 5 | RUN pip install --upgrade pip && \ 6 | pip install --no-cache-dir -r requirements.txt 7 | 8 | CMD python -m src.dynamic_system 9 | -------------------------------------------------------------------------------- /run.py: -------------------------------------------------------------------------------- 1 | r"""Main function to run chaotic model 2 | 3 | """ 4 | 5 | from src.dynamic_system import DynamicSystem 6 | 7 | 8 | if __name__ == '__main__': 9 | chaotic_system = DynamicSystem(input_args=None, show_log=True) 10 | chaotic_system.run() 11 | -------------------------------------------------------------------------------- /tests/test_drawer.py: -------------------------------------------------------------------------------- 1 | """Testing for Drawer 2 | """ 3 | 4 | import matplotlib.pyplot as plt 5 | import numpy as np 6 | import pytest 7 | from src.utils.drawer import PlotDrawer 8 | 9 | 10 | @pytest.fixture(name="drawer") 11 | def drawer(): 12 | """Return PlotDrawer object with default parameters.""" 13 | return PlotDrawer(save_plots=False, show_plots=False) 14 | 15 | 16 | @pytest.mark.parametrize( 17 | "coordinates", 18 | [ 19 | np.random.randn(10, 3), 20 | np.zeros(15).reshape(5, 3), 21 | np.ones((3, 7)).T, 22 | np.array([[0, 1, 2], [3, 4, 5], [0, 0, 0], [7, 7, 7]]), 23 | np.array([ii for ii in range(30)]).reshape(-1, 3), 24 | np.array([[0, 1, 2]] * 10), 25 | ], 26 | ) 27 | def test_shapes_of_coordinates(drawer, coordinates): 28 | """Test input coordinates from iterable sources. Shape[1] shoud be 3""" 29 | drawer.show_time_plots(coordinates) 30 | plt.close() # disable matplotlib warnings 31 | drawer.show_3d_plots(coordinates) 32 | plt.close() # disable matplotlib warnings 33 | assert coordinates.shape[1] == 3, f"[FAIL]: Expected shape of vector coordinates is 3!" 34 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | # Example configuration for Black. 2 | 3 | # NOTE: you have to use single-quoted strings in TOML for regular expressions. 4 | # It's the equivalent of r-strings in Python. Multiline strings are treated as 5 | # verbose regular expressions by Black. Use [ ] to denote a significant space 6 | # character. 7 | 8 | # TODO 2020/06/02: Check Flake8 9 | [tool.flake8] 10 | ignore = ['E203', 'E266', 'E501', 'W503', 'F403', 'F401'] 11 | max-line-length = 120 12 | max-complexity = 12 13 | select = ['B','C','E','F','W','T4','B9'] 14 | 15 | [tool.isort] 16 | known_third_party = ["matplotlib", "mpl_toolkits", "numpy", "pandas", "pytest", "scipy", "src"] 17 | multi_line_output = 3 18 | include_trailing_comma = true 19 | force_grid_wrap = 0 20 | use_parentheses = true 21 | line_length = 120 22 | 23 | [tool.black] 24 | line-length = 120 25 | target-version = ['py39'] 26 | exclude = ''' 27 | /( 28 | \.eggs 29 | | \.git 30 | | \.hg 31 | | \.mypy_cache 32 | | \.tox 33 | | \.venv 34 | | _build 35 | | buck-out 36 | | build 37 | | dist 38 | # The following are specific to Black, you probably don't want those. 39 | | blib2to3 40 | | tests/data 41 | | profiling 42 | )/ 43 | ''' 44 | -------------------------------------------------------------------------------- /tests/test_attractor.py: -------------------------------------------------------------------------------- 1 | """Testing for Chua system. 2 | """ 3 | 4 | import pytest 5 | from src.attractors.attractor import BaseAttractor 6 | 7 | 8 | @pytest.fixture 9 | def chaotic_system(): 10 | return BaseAttractor 11 | 12 | 13 | @pytest.mark.parametrize("num_points, length", [(-10, 0), (0, 0), (10, 10)]) 14 | def test_initialized_coordinates(num_points, length): 15 | model = BaseAttractor(num_points=num_points) 16 | assert len(model) == length, f"[FAIL]: Expected len is {length} for positive integers only!" 17 | 18 | 19 | def test_check_reset_coordinates(): 20 | model = BaseAttractor(num_points=100) 21 | assert model._coordinates is None, f"[FAIL]: Coordinates should be None!" 22 | assert len(model) == 100, f"[FAIL]: Expected len is {model.num_points} for positive integers only!" 23 | del model.coordinates 24 | assert model._coordinates is None, f"[FAIL]: Coordinates should be None!" 25 | 26 | 27 | @pytest.mark.parametrize( 28 | "num_points, initial_points, result", [(1, (0, 0, 0), None), (1, (0, 0, 0), None),], 29 | ) 30 | def test_math_moments(num_points, initial_points, result, assert_moments): 31 | assert_moments(num_points, initial_points, result) 32 | -------------------------------------------------------------------------------- /.pre-commit-config.yaml: -------------------------------------------------------------------------------- 1 | exclude: '^$' 2 | fail_fast: false 3 | default_language_version: 4 | python: python3.9 5 | repos: 6 | - repo: https://github.com/pre-commit/pre-commit-hooks 7 | rev: v2.5.0 8 | hooks: 9 | - id: check-docstring-first 10 | - id: check-merge-conflict 11 | - id: check-yaml 12 | - id: trailing-whitespace 13 | - id: end-of-file-fixer 14 | - id: requirements-txt-fixer 15 | 16 | - repo: https://github.com/humitos/mirrors-autoflake.git 17 | rev: v1.3 18 | hooks: 19 | - id: autoflake 20 | args: ['-r', '--in-place', 21 | '--remove-all-unused-imports', 22 | '--ignore-init-module-imports', 23 | '--remove-unused-variables', 24 | '--remove-duplicate-keys' 25 | ] 26 | 27 | - repo: https://github.com/asottile/seed-isort-config 28 | rev: v2.1.0 29 | hooks: 30 | - id: seed-isort-config 31 | args: ['--application-directories=src'] 32 | 33 | - repo: https://github.com/pre-commit/mirrors-isort 34 | rev: v4.3.21 35 | hooks: 36 | - id: isort 37 | args: ['-y'] 38 | 39 | - repo: https://github.com/ambv/black 40 | rev: stable 41 | hooks: 42 | - id: black 43 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # User added 2 | .idea/ 3 | .pytest_cache/ 4 | 5 | # Byte-compiled / optimized / DLL files 6 | __pycache__/ 7 | *.py[cod] 8 | *$py.class 9 | 10 | # C extensions 11 | *.so 12 | 13 | # Distribution / packaging 14 | .Python 15 | build/ 16 | develop-eggs/ 17 | dist/ 18 | downloads/ 19 | eggs/ 20 | .eggs/ 21 | lib/ 22 | lib64/ 23 | parts/ 24 | sdist/ 25 | var/ 26 | wheels/ 27 | *.egg-info/ 28 | .installed.cfg 29 | *.egg 30 | MANIFEST 31 | 32 | # PyInstaller 33 | # Usually these files are written by a python script from a template 34 | # before PyInstaller builds the exe, so as to inject date/other infos into it. 35 | *.manifest 36 | *.spec 37 | 38 | # Installer logs 39 | pip-log.txt 40 | pip-delete-this-directory.txt 41 | 42 | # Unit test / coverage reports 43 | htmlcov/ 44 | .tox/ 45 | .coverage 46 | .coverage.* 47 | .cache 48 | nosetests.xml 49 | coverage.xml 50 | *.cover 51 | .hypothesis/ 52 | .pytest_cache/ 53 | 54 | # Translations 55 | *.mo 56 | *.pot 57 | 58 | # Django stuff: 59 | *.log 60 | local_settings.py 61 | db.sqlite3 62 | 63 | # Flask stuff: 64 | instance/ 65 | .webassets-cache 66 | 67 | # Scrapy stuff: 68 | .scrapy 69 | 70 | # Sphinx documentation 71 | docs/_build/ 72 | 73 | # PyBuilder 74 | target/ 75 | 76 | # Jupyter Notebook 77 | .ipynb_checkpoints 78 | 79 | # pyenv 80 | .python-version 81 | 82 | # celery beat schedule file 83 | celerybeat-schedule 84 | 85 | # SageMath parsed files 86 | *.sage.py 87 | 88 | # Environments 89 | .env 90 | .venv 91 | env/ 92 | venv/ 93 | ENV/ 94 | env.bak/ 95 | venv.bak/ 96 | 97 | # Spyder project settings 98 | .spyderproject 99 | .spyproject 100 | 101 | # Rope project settings 102 | .ropeproject 103 | 104 | # mkdocs documentation 105 | /site 106 | 107 | # mypy 108 | .mypy_cache/ 109 | -------------------------------------------------------------------------------- /tests/test_chua.py: -------------------------------------------------------------------------------- 1 | """Testing for Chua system.""" 2 | 3 | import pytest 4 | from src.attractors.chua import Chua 5 | 6 | 7 | @pytest.fixture 8 | def chaotic_system(): 9 | return Chua 10 | 11 | 12 | @pytest.fixture(scope="module") 13 | def model(): 14 | chua = Chua(num_points=100) 15 | return chua.attractor 16 | 17 | 18 | @pytest.mark.parametrize( 19 | "inputs, outputs", 20 | [ 21 | ((0, 0, 0), (0, 0, 0)), 22 | ((0, 0, 1), (0, 1, 0)), 23 | ((0, 1, 0), (15.6, -1, -28)), 24 | ((1, 0, 0), (2.2308, 1, 0)), 25 | ((1e-3, 1e-4, 1e-5), (3.7908e-03, 9.1e-04, -2.8e-03)), 26 | ((1.0, 2.0, 3.0), (33.4308, 2.0, -56.0)), 27 | ((-1000, 2000, -3000), (35654.9076, -6000, -56000)), 28 | ((1000000, 2000000, 3000000), (26738406.6924, 2000000, -56000000)), 29 | ], 30 | ) 31 | def test_chua_with_default_kwargs(model, inputs, outputs, assert_threshold): 32 | xi, yi, zi = inputs 33 | xo, yo, zo = model(xi, yi, zi) 34 | 35 | assert_threshold((xo, yo, zo), outputs) 36 | 37 | 38 | @pytest.mark.parametrize( 39 | "inputs, outputs, kwargs", 40 | [ 41 | ((1, 2, 3), (25.3, 2, -86), {"alpha": 11, "beta": 43, "mu0": -1.3, "mu1": -0.9}), 42 | ((1, 2, 3), (12.0, 2, -34), {"alpha": 4, "beta": 17, "mu0": -2, "mu1": -3}), 43 | ((1, 2, 3), (0.0, 2.00001, 0), {"alpha": 0, "beta": 0, "mu0": 0, "mu1": 0}), 44 | ((-0.01, 0.2, 100), (2.167, 99.79, -8.6), {"alpha": 11, "beta": 43, "mu0": -1.3, "mu1": -0.9}), 45 | ], 46 | ) 47 | def test_chua_with_kwargs(model, inputs, outputs, kwargs, assert_threshold): 48 | xi, yi, zi = inputs 49 | xo, yo, zo = model(xi, yi, zi, **kwargs) 50 | 51 | assert_threshold((xo, yo, zo), outputs) 52 | 53 | 54 | def test_output_length(model): 55 | outputs = model(0, 0, 0) 56 | assert len(outputs) == 3, "Should return 3 values as a tuple" 57 | -------------------------------------------------------------------------------- /tests/conftest.py: -------------------------------------------------------------------------------- 1 | import pytest 2 | 3 | 4 | @pytest.fixture 5 | def error_threshold(): 6 | return 10e-8 7 | 8 | 9 | @pytest.fixture 10 | def assert_threshold(error_threshold, calc_absolute_error): 11 | def wrapper(inputs, outputs): 12 | err_sum = calc_absolute_error(inputs, outputs) 13 | assert err_sum < error_threshold, f"Outputs: {outputs}, Error: {err_sum :.5f}" 14 | 15 | return wrapper 16 | 17 | 18 | @pytest.fixture 19 | def calc_absolute_error(): 20 | def wrapper(test: tuple = None, pred: tuple = None) -> float: 21 | """Calculate absolute error for test checking. 22 | 23 | Parameters 24 | ---------- 25 | test : tuple 26 | coordinates array of theoretical values. 27 | pred : tuple 28 | coordinates array of calculated values. 29 | 30 | Returns 31 | ------- 32 | err: float 33 | Absolute error: sum[(Xi - Yi) / Xi] / 3. 34 | 35 | """ 36 | err_sum = 0 37 | for e1, e2 in zip(test, pred): 38 | div = e2 if e1 == 0 else e1 39 | try: 40 | err_sum += (e1 - e2) ** 2 / div ** 2 41 | except ZeroDivisionError: 42 | pass 43 | return err_sum / 3 44 | 45 | return wrapper 46 | 47 | 48 | # TODO: 2020/07/23: Fix this 49 | # @pytest.mark.parametrize( 50 | # "num_points, initial_points, result", 51 | # [ 52 | # (1, (0, 0, 0), None), 53 | # (1, (0, 0, 0), None), 54 | # ], 55 | # ) 56 | # def assert_moments(num_points, initial_points, result): 57 | # def wrapper(chaotic_system): 58 | # chaos = chaotic_system(num_points, initial_points) 59 | # moments = chaos.check_moments() 60 | # assert result == moments, f"Outputs: {moments :5f}, Golden data: {result :.5f}" 61 | # return wrapper 62 | 63 | 64 | @pytest.fixture 65 | def assert_moments(chaotic_system): 66 | def wrapper(num_points, initial_points, result): 67 | chaos = chaotic_system(num_points, initial_points) 68 | moments = chaos.check_moments() 69 | assert result == moments, f"Outputs: {moments}, Golden data: {result}" 70 | 71 | return wrapper 72 | -------------------------------------------------------------------------------- /src/attractors/wang.py: -------------------------------------------------------------------------------- 1 | r"""Wang 3D attractor system. It also has 4D realization. 2 | 3 | Description : 4 | Wang system (improved Lorenz model) as classic chaotic attractor 5 | 6 | Wang equations are: 7 | dx/dt = x - y*z 8 | dy/dt = x - y + x*z 9 | dz/dt = -3*z + x*y 10 | 11 | ------------------------------------------------------------------------ 12 | 13 | GNU GENERAL PUBLIC LICENSE 14 | Version 3, 29 June 2007 15 | 16 | Copyright (c) 2019 Kapitanov Alexander 17 | 18 | This program is free software: you can redistribute it and/or modify 19 | it under the terms of the GNU General Public License as published by 20 | the Free Software Foundation, either version 3 of the License, or 21 | (at your option) any later version. 22 | 23 | You should have received a copy of the GNU General Public License 24 | along with this program. If not, see . 25 | 26 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 27 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 28 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT 29 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT 30 | NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 31 | FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND 32 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 33 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR 34 | OR CORRECTION. 35 | 36 | ------------------------------------------------------------------------ 37 | """ 38 | 39 | # Authors : Alexander Kapitanov 40 | # ... 41 | # Contacts : 42 | # ... 43 | # Release Date : 2019/05/31 44 | # License : GNU GENERAL PUBLIC LICENSE 45 | 46 | from typing import Tuple 47 | 48 | from src.attractors.attractor import BaseAttractor 49 | 50 | 51 | class Wang(BaseAttractor): 52 | """Wang attractor (it is improved version of Lorenz model).""" 53 | 54 | def attractor(self, x: float, y: float, z: float, **kwargs) -> Tuple[float, float, float]: 55 | r"""Calculate the next coordinate X, Y, Z for 3rd-order Wang system 56 | 57 | Parameters 58 | ---------- 59 | x, y, z : float 60 | Input coordinates X, Y, Z respectively. 61 | 62 | Examples 63 | -------- 64 | >>> from src.attractors.wang import Wang 65 | >>> coordinates = (0, 1, -1) 66 | >>> model = Wang(num_points=1) 67 | >>> output = model.attractor(*coordinates) 68 | >>> print(output) 69 | (1, -1, 3) 70 | >>> model = Wang(num_points=10, init_point=(0.1, 0, -0.1), step=100) 71 | >>> print(model.get_coordinates()) 72 | [[ 0.1 0. -0.1 ] 73 | [ 0.101 0.0009 -0.097 ] 74 | [ 0.10201087 0.00180303 -0.09408909] 75 | [ 0.10303268 0.00270913 -0.09126458] 76 | [ 0.10406548 0.00361833 -0.08852385] 77 | [ 0.10510934 0.00453068 -0.08586437] 78 | [ 0.10616432 0.00544621 -0.08328368] 79 | [ 0.1072305 0.00636498 -0.08077938] 80 | [ 0.10830794 0.00728701 -0.07834918] 81 | [ 0.10939673 0.00821236 -0.07599081]] 82 | 83 | See Also 84 | ----- 85 | No links. 86 | """ 87 | x_out = x - y * z 88 | y_out = x - y + x * z 89 | z_out = -3 * z + x * y 90 | return x_out, y_out, z_out 91 | 92 | 93 | if __name__ == "__main__": 94 | import doctest 95 | 96 | doctest.testmod(verbose=True) 97 | -------------------------------------------------------------------------------- /src/attractors/nose_hoover.py: -------------------------------------------------------------------------------- 1 | r"""Nose-Hoover attractor system. 2 | 3 | Description: 4 | The Nose–Hoover thermostat is a deterministic algorithm for 5 | constant-temperature molecular dynamics simulations. It was originally 6 | developed by Nose and was improved further by Hoover. 7 | 8 | Nose–Hoover oscillator is ordinary differential equation (ODE) of 9 | 3rd order system. 10 | Nose–Hoover system has only five terms and two quadratic 11 | nonlinearities. 12 | 13 | Nose–Hoover equations are: 14 | dx/dt = y 15 | dy/dt = y * z - x 16 | dz/dt = 1 - y * y 17 | 18 | Nose–Hoover system doesn't have any system parameters. 19 | 20 | ------------------------------------------------------------------------ 21 | 22 | GNU GENERAL PUBLIC LICENSE 23 | Version 3, 29 June 2007 24 | 25 | Copyright (c) 2019 Kapitanov Alexander 26 | 27 | This program is free software: you can redistribute it and/or modify 28 | it under the terms of the GNU General Public License as published by 29 | the Free Software Foundation, either version 3 of the License, or 30 | (at your option) any later version. 31 | 32 | You should have received a copy of the GNU General Public License 33 | along with this program. If not, see . 34 | 35 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 36 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 37 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT 38 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT 39 | NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 40 | FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND 41 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 42 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR 43 | OR CORRECTION. 44 | 45 | ------------------------------------------------------------------------ 46 | """ 47 | 48 | # Authors : Alexander Kapitanov 49 | # ... 50 | # Contacts : 51 | # ... 52 | # Release Date : 2020/07/29 53 | # License : GNU GENERAL PUBLIC LICENSE 54 | 55 | from typing import Tuple 56 | 57 | from src.attractors.attractor import BaseAttractor 58 | 59 | 60 | class NoseHoover(BaseAttractor): 61 | """Nose Hoover attractor.""" 62 | 63 | def attractor(self, x: float, y: float, z: float, **kwargs) -> Tuple[float, float, float]: 64 | r"""Calculate the next coordinate X, Y, Z for 3rd-order Nose Hoover system 65 | 66 | Parameters 67 | ---------- 68 | x, y, z : float 69 | Input coordinates X, Y, Z respectively. 70 | 71 | Examples 72 | -------- 73 | >>> from src.attractors.nose_hoover import NoseHoover 74 | >>> coordinates = (0, 1, -1) 75 | >>> model = NoseHoover(num_points=1) 76 | >>> output = model.attractor(*coordinates) 77 | >>> print(output) 78 | (1, -1, 0) 79 | >>> model = NoseHoover(num_points=10, init_point=(0.1, 0, -0.1), step=100) 80 | >>> print(model.get_coordinates()) 81 | [[ 0.1 0. -0.1 ] 82 | [ 0.1 -0.001 -0.09 ] 83 | [ 0.09999 -0.0019991 -0.08000001] 84 | [ 0.09997001 -0.0029974 -0.07000005] 85 | [ 0.09994003 -0.003995 -0.06000014] 86 | [ 0.09990008 -0.00499201 -0.0500003 ] 87 | [ 0.09985016 -0.00598851 -0.04000055] 88 | [ 0.09979028 -0.00698462 -0.03000091] 89 | [ 0.09972043 -0.00798042 -0.0200014 ] 90 | [ 0.09964063 -0.00897603 -0.01000203]] 91 | 92 | See Also 93 | ----- 94 | https://en.wikipedia.org/wiki/Nos%C3%A9%E2%80%93Hoover_thermostat 95 | 96 | """ 97 | x_out = y 98 | y_out = y * z - x 99 | z_out = 1 - y * y 100 | return x_out, y_out, z_out 101 | 102 | 103 | if __name__ == "__main__": 104 | import doctest 105 | 106 | doctest.testmod(verbose=True) 107 | -------------------------------------------------------------------------------- /src/attractors/rikitake.py: -------------------------------------------------------------------------------- 1 | r"""Rikitake chaotic system. 2 | 3 | Description : 4 | Rikitake system is ordinary differential equation (ODE) of 5 | 3rd order system. 6 | Rikitake system attempts to explain the reversal of the Earth’s 7 | magnetic field. 8 | 9 | Rikitake equations are: 10 | dx/dt = -mu * x + z * y 11 | dy/dt = -mu * y + x * (z - a) 12 | dz/dt = 1 - x * y 13 | 14 | where a, mu - are Rikitake system parameters. 15 | Default values are 16 | - a = 5, 17 | - mu = 2 18 | or 19 | 20 | - a = mu = 1. 21 | 22 | ------------------------------------------------------------------------ 23 | 24 | GNU GENERAL PUBLIC LICENSE 25 | Version 3, 29 June 2007 26 | 27 | Copyright (c) 2019 Kapitanov Alexander 28 | 29 | This program is free software: you can redistribute it and/or modify 30 | it under the terms of the GNU General Public License as published by 31 | the Free Software Foundation, either version 3 of the License, or 32 | (at your option) any later version. 33 | 34 | You should have received a copy of the GNU General Public License 35 | along with this program. If not, see . 36 | 37 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 38 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 39 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT 40 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT 41 | NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 42 | FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND 43 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 44 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR 45 | OR CORRECTION. 46 | 47 | ------------------------------------------------------------------------ 48 | """ 49 | 50 | # Authors : Alexander Kapitanov 51 | # ... 52 | # Contacts : 53 | # ... 54 | # Release Date : 2019/05/30 55 | # License : GNU GENERAL PUBLIC LICENSE 56 | 57 | from typing import Tuple 58 | 59 | from src.attractors.attractor import BaseAttractor 60 | 61 | 62 | class Rikitake(BaseAttractor): 63 | """Rikitake attractor.""" 64 | 65 | def attractor(self, x: float, y: float, z: float, a: float = 5, mu: float = 2) -> Tuple[float, float, float]: 66 | r"""Calculate the next coordinate X, Y, Z for 3rd-order Rikitake system 67 | 68 | Parameters 69 | ---------- 70 | x, y, z : float 71 | Input coordinates X, Y, Z respectively. 72 | a, mu : float 73 | Rikitake system parameters. Default: 74 | - a = 5, 75 | - mu = 2 76 | or 77 | - a = mu = 1. 78 | 79 | Examples 80 | -------- 81 | >>> from src.attractors.rikitake import Rikitake 82 | >>> coordinates = (0, 1, -1) 83 | >>> model = Rikitake(num_points=1) 84 | >>> output = model.attractor(*coordinates) 85 | >>> print(output) 86 | (-1, -2, 1) 87 | >>> model = Rikitake(num_points=10, init_point=(0.1, 0, -0.1), step=100) 88 | >>> print(model.get_coordinates()) 89 | [[ 0.1 0. -0.1 ] 90 | [ 0.098 -0.0051 -0.09 ] 91 | [ 0.09604459 -0.0099862 -0.079995 ] 92 | [ 0.09413169 -0.01466554 -0.06998541] 93 | [ 0.09225932 -0.01914469 -0.05997161] 94 | [ 0.09042561 -0.02343009 -0.04995394] 95 | [ 0.0886288 -0.02752794 -0.03993276] 96 | [ 0.08686722 -0.03144421 -0.02990836] 97 | [ 0.08513928 -0.03518467 -0.01988104] 98 | [ 0.08344349 -0.03875487 -0.00985109]] 99 | 100 | See Also 101 | ----- 102 | Cannot add wiki link ;( 103 | """ 104 | x_out = -mu * x + z * y 105 | y_out = -mu * y + x * (z - a) 106 | z_out = 1 - x * y 107 | 108 | return x_out, y_out, z_out 109 | 110 | 111 | if __name__ == "__main__": 112 | import doctest 113 | 114 | doctest.testmod(verbose=True) 115 | -------------------------------------------------------------------------------- /src/attractors/lotka_volterra.py: -------------------------------------------------------------------------------- 1 | r"""Lotka Volterra attractor. 2 | 3 | Description : 4 | The Lotka–Volterra equations, also known as the predator–prey equations, 5 | are a pair of first-order nonlinear differential equations, 6 | frequently used to describe the dynamics of biological systems in 7 | which two species interact, one as a predator and the other as prey. 8 | 9 | Chaotic Lotka-Volterra model require a careful tuning of 10 | parameters and are even less likely to exhibit chaos as the number 11 | of species increases. 12 | 13 | Lotka–Volterra equations are: 14 | Eq. 1: 15 | dx/dt = x * (1 - x - 9*y) 16 | dy/dt = -y * (1 - 6*x - y + 9*z) 17 | dz/dt = z * (1 - 3*x - z) 18 | 19 | Be careful! Init parameters of x, y, z should be set right! 20 | 21 | For example, [x, y, z] = [0.6, 0.2, 0.01] 22 | 23 | ------------------------------------------------------------------------ 24 | 25 | GNU GENERAL PUBLIC LICENSE 26 | Version 3, 29 June 2007 27 | 28 | Copyright (c) 2019 Kapitanov Alexander 29 | 30 | This program is free software: you can redistribute it and/or modify 31 | it under the terms of the GNU General Public License as published by 32 | the Free Software Foundation, either version 3 of the License, or 33 | (at your option) any later version. 34 | 35 | You should have received a copy of the GNU General Public License 36 | along with this program. If not, see . 37 | 38 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 39 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 40 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT 41 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT 42 | NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 43 | FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND 44 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 45 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR 46 | OR CORRECTION. 47 | 48 | ------------------------------------------------------------------------ 49 | """ 50 | 51 | # Authors : Alexander Kapitanov 52 | # ... 53 | # Contacts : 54 | # ... 55 | # Release Date : 2019/05/31 56 | # License : GNU GENERAL PUBLIC LICENSE 57 | 58 | from typing import Tuple 59 | 60 | from src.attractors.attractor import BaseAttractor 61 | 62 | 63 | class LotkaVolterra(BaseAttractor): 64 | """Lotka-Volterra attractor.""" 65 | 66 | def attractor(self, x: float, y: float, z: float, **kwargs) -> Tuple[float, float, float]: 67 | r"""Calculate the next coordinate X, Y, Z for 3rd-order Lotka-Volterra system 68 | 69 | Parameters 70 | ---------- 71 | x, y, z : float 72 | Input coordinates X, Y, Z respectively. 73 | 74 | Lotka-Volterra does not have initial parameters. 75 | 76 | Examples 77 | -------- 78 | >>> from src.attractors.lotka_volterra import LotkaVolterra 79 | >>> coordinates = (0, 1, -1) 80 | >>> model = LotkaVolterra(num_points=1) 81 | >>> output = model.attractor(*coordinates) 82 | >>> print(output) 83 | (0, 9, -2) 84 | >>> model = LotkaVolterra(num_points=10, init_point=(0.1, 0.5, -0.1), step=100) 85 | >>> print(model.get_coordinates()) 86 | [[ 0.1 0.5 -0.1 ] 87 | [ 0.0964 0.505 -0.1008 ] 88 | [ 0.09288969 0.51000253 -0.10161809] 89 | [ 0.08946864 0.51501026 -0.10245436] 90 | [ 0.08613633 0.52002601 -0.10330888] 91 | [ 0.08289212 0.5250527 -0.10418173] 92 | [ 0.07973528 0.53009342 -0.10507301] 93 | [ 0.07666501 0.53515137 -0.10598281] 94 | [ 0.07368042 0.54022989 -0.1069112 ] 95 | [ 0.07078055 0.54533243 -0.1078583 ]] 96 | 97 | See Also 98 | ----- 99 | https://en.wikipedia.org/wiki/Lotka%E2%80%93Volterra_equations 100 | """ 101 | x_out = x * (1 - x - 9 * y) 102 | y_out = -y * (1 - 6 * x - y + 9 * z) 103 | z_out = z * (1 - 3 * x - z) 104 | return x_out, y_out, z_out 105 | 106 | 107 | if __name__ == "__main__": 108 | import doctest 109 | 110 | doctest.testmod(verbose=True) 111 | -------------------------------------------------------------------------------- /src/attractors/lorenz.py: -------------------------------------------------------------------------------- 1 | r"""Lorenz Attractor 2 | 3 | Description: 4 | Lorenz attractor is ordinary differential equation (ODE) of 3rd order system. 5 | In 1963, E. Lorenz developed a simplified mathematical model for 6 | atmospheric convection. 7 | 8 | Lorenz equations are: 9 | dx/dt = sigma * (y - x) 10 | dy/dt = rho * x - y - x * z 11 | dz/dt = x * y - beta * z 12 | 13 | where: 14 | beta, rho and sigma - are Lorenz system parameters. Default 15 | default values for parameters are: 16 | beta = 8/3, 17 | rho = 28, 18 | sigma = 10. 19 | 20 | If rho < 1 then there is only one equilibrium point, 21 | which is at the origin. This point corresponds to no convection. 22 | 23 | ------------------------------------------------------------------------ 24 | 25 | GNU GENERAL PUBLIC LICENSE 26 | Version 3, 29 June 2007 27 | 28 | Copyright (c) 2019 Kapitanov Alexander 29 | 30 | This program is free software: you can redistribute it and/or modify 31 | it under the terms of the GNU General Public License as published by 32 | the Free Software Foundation, either version 3 of the License, or 33 | (at your option) any later version. 34 | 35 | You should have received a copy of the GNU General Public License 36 | along with this program. If not, see . 37 | 38 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 39 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 40 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT 41 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT 42 | NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 43 | FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND 44 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 45 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR 46 | OR CORRECTION. 47 | 48 | ------------------------------------------------------------------------ 49 | """ 50 | 51 | # Authors : Alexander Kapitanov 52 | # ... 53 | # Contacts : 54 | # ... 55 | # Release Date : 2019/05/31 56 | # License : GNU GENERAL PUBLIC LICENSE 57 | 58 | from typing import Tuple 59 | 60 | from src.attractors.attractor import BaseAttractor 61 | 62 | 63 | class Lorenz(BaseAttractor): 64 | """Lorenz attractor.""" 65 | 66 | def attractor( 67 | self, x: float, y: float, z: float, sigma: float = 10, beta: float = 8 / 3, rho: float = 28, 68 | ) -> Tuple[float, float, float]: 69 | r"""Calculate the next coordinate X, Y, Z for 3rd-order Lorenz system 70 | 71 | Parameters 72 | ---------- 73 | x, y, z : float 74 | Input coordinates X, Y, Z respectively. 75 | sigma, beta, rho : float 76 | Lorenz system parameters. Default: 77 | - sigma = 10, 78 | - beta = 8/3, 79 | - rho = 28, 80 | 81 | Examples 82 | -------- 83 | >>> from src.attractors.lorenz import Lorenz 84 | >>> coordinates = (0, 1, -1) 85 | >>> model = Lorenz(num_points=1) 86 | >>> output = model.attractor(*coordinates) 87 | >>> print(output) 88 | (10, -1, 2.6666666666666665) 89 | >>> model = Lorenz(num_points=10, init_point=(0.1, 0, -0.1), step=100) 90 | >>> print(model.get_coordinates()) 91 | [[ 0.1 0. -0.1 ] 92 | [ 0.09 0.0281 -0.09733333] 93 | [ 0.08381 0.0531066 -0.09471249] 94 | [ 0.08073966 0.07612171 -0.09214231] 95 | [ 0.08027787 0.098042 -0.08962372] 96 | [ 0.08205428 0.11961133 -0.08715505] 97 | [ 0.08580998 0.14146193 -0.08473277] 98 | [ 0.09137518 0.16414681 -0.08235184] 99 | [ 0.09865234 0.18816564 -0.0800058 ] 100 | [ 0.10760367 0.21398557 -0.07768669]] 101 | 102 | See Also 103 | ----- 104 | https://en.wikipedia.org/wiki/Lorenz_system 105 | """ 106 | x_out = sigma * (y - x) 107 | y_out = rho * x - y - x * z 108 | z_out = x * y - beta * z 109 | return x_out, y_out, z_out 110 | 111 | 112 | if __name__ == "__main__": 113 | import doctest 114 | 115 | doctest.testmod(verbose=True) 116 | -------------------------------------------------------------------------------- /src/attractors/chua.py: -------------------------------------------------------------------------------- 1 | r"""Chua attractor 2 | 3 | Description: 4 | Chua circuit. This is a simple electronic circuit that exhibits 5 | classic chaotic behavior. This means roughly that it is a 6 | "nonperiodic oscillator". 7 | 8 | Chua equations are: 9 | 10 | Eq. 1: 11 | dx/dt = alpha * (y - x - ht) 12 | dy/dt = x - y + z 13 | dz/dt = -beta * y 14 | 15 | where ht = mu1*x + 0.5*(mu0 - mu1)*(np.abs(x + 1) - np.abs(x - 1)) 16 | and alpha, beta, mu0 and mu1 - are Chua system parameters. 17 | 18 | Default values are: 19 | alpha = 15.6 20 | beta = 28 21 | mu0 = -1.143 22 | mu1 = -0.714 23 | 24 | Eq. 2: 25 | dx/dt = 0.3*y + x - x**3 26 | dy/dt = x + z 27 | dz/dt = y 28 | 29 | without default values. 30 | 31 | ------------------------------------------------------------------------ 32 | 33 | GNU GENERAL PUBLIC LICENSE 34 | Version 3, 29 June 2007 35 | 36 | Copyright (c) 2019 Kapitanov Alexander 37 | 38 | This program is free software: you can redistribute it and/or modify 39 | it under the terms of the GNU General Public License as published by 40 | the Free Software Foundation, either version 3 of the License, or 41 | (at your option) any later version. 42 | 43 | You should have received a copy of the GNU General Public License 44 | along with this program. If not, see . 45 | 46 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 47 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 48 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT 49 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT 50 | NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 51 | FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND 52 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 53 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR 54 | OR CORRECTION. 55 | 56 | ------------------------------------------------------------------------ 57 | """ 58 | 59 | # Authors : Alexander Kapitanov 60 | # ... 61 | # Contacts : 62 | # ... 63 | # Release Date : 2019/05/31 64 | # License : GNU GENERAL PUBLIC LICENSE 65 | 66 | from math import fabs 67 | from typing import Tuple 68 | 69 | from src.attractors.attractor import BaseAttractor 70 | 71 | 72 | class Chua(BaseAttractor): 73 | """Chua attractor.""" 74 | 75 | def attractor( 76 | self, 77 | x: float, 78 | y: float, 79 | z: float, 80 | alpha: float = 15.6, 81 | beta: float = 28, 82 | mu0: float = -1.143, 83 | mu1: float = -0.714, 84 | ) -> Tuple[float, float, float]: 85 | r"""Calculate the next coordinate X, Y, Z for Chua system. 86 | 87 | Parameters 88 | ---------- 89 | x, y, z : float 90 | Input coordinates X, Y, Z respectively. 91 | 92 | alpha, beta, mu0, mu1 : float 93 | Chua system parameters. Default: 94 | - alpha = 15.6, 95 | - beta = 28, 96 | - mu0 = -1.143, 97 | - mu1 = -0.714, 98 | 99 | Examples 100 | -------- 101 | >>> from src.attractors.chua import Chua 102 | >>> coordinates = (0, 1, -1) 103 | >>> model = Chua(num_points=1) 104 | >>> output = model.attractor(*coordinates) 105 | >>> print(output) 106 | (15.6, -2, -28) 107 | >>> model = Chua(num_points=10, init_point=(0.1, 0, -0.1), step=100) 108 | >>> print(model.get_coordinates()) 109 | [[ 1.00000000e-01 0.00000000e+00 -1.00000000e-01] 110 | [ 1.02230800e-01 0.00000000e+00 -1.00000000e-01] 111 | [ 1.04511365e-01 2.23080000e-05 -1.00000000e-01] 112 | [ 1.06846284e-01 6.71985669e-05 -1.00006246e-01] 113 | [ 1.09240294e-01 1.34926961e-04 -1.00025062e-01] 114 | [ 1.11698275e-01 2.25730015e-04 -1.00062841e-01] 115 | [ 1.14225254e-01 3.39827053e-04 -1.00126046e-01] 116 | [ 1.16826404e-01 4.77420867e-04 -1.00221197e-01] 117 | [ 1.19507045e-01 6.38698727e-04 -1.00354875e-01] 118 | [ 1.22272645e-01 8.23833441e-04 -1.00533711e-01]] 119 | 120 | See Also 121 | ----- 122 | https://en.wikipedia.org/wiki/Chua%27s_circuit 123 | """ 124 | 125 | ht = mu1 * x + 0.5 * (mu0 - mu1) * (fabs(x + 1) - fabs(x - 1)) 126 | # Next step coordinates: 127 | x_out = alpha * (y - x - ht) 128 | y_out = x - y + z 129 | z_out = -beta * y 130 | return x_out, y_out, z_out 131 | 132 | 133 | if __name__ == "__main__": 134 | import doctest 135 | 136 | doctest.testmod(verbose=True) 137 | -------------------------------------------------------------------------------- /src/dynamic_system.py: -------------------------------------------------------------------------------- 1 | """Dynamic system class. 2 | 3 | Description: 4 | Combine attractor, calculator and drawer. 5 | 6 | ------------------------------------------------------------------------ 7 | 8 | GNU GENERAL PUBLIC LICENSE 9 | Version 3, 29 June 2007 10 | 11 | Copyright (c) 2019 Kapitanov Alexander 12 | 13 | This program is free software: you can redistribute it and/or modify 14 | it under the terms of the GNU General Public License as published by 15 | the Free Software Foundation, either version 3 of the License, or 16 | (at your option) any later version. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with this program. If not, see . 20 | 21 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 22 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 23 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT 24 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT 25 | NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 26 | FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND 27 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 28 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR 29 | OR CORRECTION. 30 | 31 | ------------------------------------------------------------------------ 32 | """ 33 | 34 | # Authors : Alexander Kapitanov 35 | # ... 36 | # Contacts : 37 | # ... 38 | # Release Date : 2020/07/25 39 | # License : GNU GENERAL PUBLIC LICENSE 40 | 41 | from typing import Optional 42 | 43 | import pandas as pd 44 | from src.utils.calculator import Calculator 45 | from src.utils.drawer import PlotDrawer 46 | from src.utils.parser import AttractorType, Settings 47 | 48 | 49 | class DynamicSystem: 50 | """Main class for computing chaotic system. 51 | 52 | Parameters 53 | ---------- 54 | # TODO: add parameters 55 | 56 | Attributes 57 | ---------- 58 | model: ChaoticAttractor() 59 | drawer: PlotDrawer() 60 | calculator: Calculator() 61 | settings: Settings() 62 | 63 | Examples 64 | -------- 65 | # TODO: Add examples 66 | 67 | See Also: 68 | ----- 69 | 70 | Dynamic systems: 71 | https://en.wikipedia.org/wiki/Dynamical_system 72 | https://en.wikipedia.org/wiki/Dynamical_systems_theory 73 | 74 | Differential equations: 75 | https://en.wikipedia.org/wiki/Differential_equation 76 | 77 | """ 78 | 79 | def __init__(self, input_args: Optional[tuple] = None, show_log: bool = False): 80 | # Main modules 81 | self.settings = Settings(show_logs=show_log) 82 | self.settings.update_params(input_args) 83 | 84 | self.model: AttractorType = self.settings.model 85 | self.drawer: PlotDrawer = PlotDrawer( 86 | self.settings.save_plots, 87 | self.settings.show_plots, 88 | self.settings.add_2d_gif 89 | ) 90 | self.drawer.model_name = self.settings.attractor.capitalize() 91 | self.calculator = Calculator() 92 | 93 | def collect_statistics(self): 94 | math_dict = {} 95 | _min_max = self.calculator.check_min_max() 96 | _moments = self.calculator.check_moments() 97 | math_dict.update({"Min": _min_max[0]}) 98 | math_dict.update({"Max": _min_max[1]}) 99 | math_dict.update(_moments) 100 | math_df = pd.DataFrame.from_dict(math_dict, columns=["X", "Y", "Z"], orient="index") 101 | return math_df 102 | 103 | def run(self): 104 | # Get vector of coordinates 105 | coordinates = self.model.get_coordinates() 106 | self.calculator.coordinates = coordinates 107 | 108 | # Calculate 109 | stats = self.collect_statistics() 110 | if self.settings.show_logs: 111 | print(f"[INFO]: Show statistics:\n{stats}\n") 112 | 113 | self.calculator.check_probability() 114 | spectrums = self.calculator.calculate_spectrum() 115 | correlations = self.calculator.calculate_correlation() 116 | 117 | # Draw results 118 | 119 | if self.settings.show_all: 120 | self.drawer.show_all_plots(coordinates, spectrums, correlations) 121 | else: 122 | if self.settings.show_spectrum: 123 | self.drawer.show_spectrum_and_correlation(coordinates, spectrums, correlations) 124 | if self.settings.show_timeplot: 125 | self.drawer.show_time_plots(coordinates) 126 | if self.settings.show_3d_plots: 127 | self.drawer.show_3d_plots(coordinates) 128 | # self.drawer.make_3d_plot_gif(50) 129 | 130 | 131 | if __name__ == "__main__": 132 | command_line = ( 133 | "--init_point", 134 | "1 -1 2", 135 | "--points", 136 | "3000", 137 | "--step", 138 | "50", 139 | "--save_plots", 140 | # "--show_plots", 141 | "--add_2d_gif", 142 | "lorenz", 143 | ) 144 | 145 | dynamic_system = DynamicSystem(input_args=command_line, show_log=True) 146 | dynamic_system.run() 147 | -------------------------------------------------------------------------------- /src/attractors/rossler.py: -------------------------------------------------------------------------------- 1 | r"""Rossler attractor (see 'Strange attractors' book). 2 | 3 | Description : 4 | Rossler attractor is the attractor for the Rössler system. Rossler 5 | attractor is a system of three non-linear ordinary differential 6 | equations. 7 | 8 | Rossler equations are: 9 | dx/dt = -(y + z) 10 | dy/dt = x + a * y 11 | dz/dt = b + z * (x - c) 12 | 13 | where a, b and sigma - are Rossler system parameters. Default 14 | values are: a = 0.2, b = 0.2 and c = 5.7. 15 | 16 | 1) a = 0.2, b = 0.2 and c = 5.7 (Standard model) 17 | 2) a = 0.1, b = 0.1 and c = 14 (another useful parameters) 18 | 3) a = 0.5, b = 1.0 and c = 3 (J. C. Sprott) 19 | 20 | Wiki (Varying parameters); 21 | 22 | Varying a: 23 | b = 0.2 and c = 5.7 are fixed. Change a: 24 | 25 | a <= 0 : Converges to the centrally located fixed point 26 | a = 0.1 : Unit cycle of period 1 27 | a = 0.2 : Standard parameter value selected by Rössler, chaotic 28 | a = 0.3 : Chaotic attractor, significantly more Möbius strip-like 29 | (folding over itself). 30 | a = 0.35 : Similar to .3, but increasingly chaotic 31 | a = 0.38 : Similar to .35, but increasingly chaotic 32 | 33 | Varying b: 34 | a = 0.2 and c = 5.7 are fixed. Change b: 35 | 36 | If b approaches 0 the attractor approaches infinity, but if b would 37 | be more than a and c, system becomes not a chaotic. 38 | 39 | Varying c: 40 | a = b = 0.1 are fixed. Change c: 41 | 42 | c = 4 : period-1 orbit, 43 | c = 6 : period-2 orbit, 44 | c = 8.5 : period-4 orbit, 45 | c = 8.7 : period-8 orbit, 46 | c = 9 : sparse chaotic attractor, 47 | c = 12 : period-3 orbit, 48 | c = 12.6 : period-6 orbit, 49 | c = 13 : sparse chaotic attractor, 50 | c = 18 : filled-in chaotic attractor. 51 | 52 | ------------------------------------------------------------------------ 53 | 54 | GNU GENERAL PUBLIC LICENSE 55 | Version 3, 29 June 2007 56 | 57 | Copyright (c) 2019 Kapitanov Alexander 58 | 59 | This program is free software: you can redistribute it and/or modify 60 | it under the terms of the GNU General Public License as published by 61 | the Free Software Foundation, either version 3 of the License, or 62 | (at your option) any later version. 63 | 64 | You should have received a copy of the GNU General Public License 65 | along with this program. If not, see . 66 | 67 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 68 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 69 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT 70 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT 71 | NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 72 | FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND 73 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 74 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR 75 | OR CORRECTION. 76 | 77 | ------------------------------------------------------------------------ 78 | """ 79 | 80 | # Authors : Alexander Kapitanov 81 | # ... 82 | # Contacts : 83 | # ... 84 | # Release Date : 2019/05/31 85 | # License : GNU GENERAL PUBLIC LICENSE 86 | 87 | from typing import Tuple 88 | 89 | from src.attractors.attractor import BaseAttractor 90 | 91 | 92 | class Rossler(BaseAttractor): 93 | """Rossler attractor.""" 94 | 95 | def attractor( 96 | self, x: float, y: float, z: float, a: float = 0.2, b: float = 0.2, c: float = 5.7, 97 | ) -> Tuple[float, float, float]: 98 | r"""Calculate the next coordinate X, Y, Z for 3rd-order Rossler system 99 | 100 | Parameters 101 | ---------- 102 | x, y, z : float 103 | Input coordinates X, Y, Z respectively. 104 | a, b, c : float 105 | Rossler system parameters. Default: 106 | 1) a = 0.2, b = 0.2 and c = 5.7 (Standard model) 107 | 2) a = 0.1, b = 0.1 and c = 14 (another useful parameters) 108 | 3) a = 0.5, b = 1.0 and c = 3 (J. C. Sprott) 109 | 110 | Examples 111 | -------- 112 | >>> from src.attractors.rossler import Rossler 113 | >>> coordinates = (0, 1, -1) 114 | >>> model = Rossler(num_points=1) 115 | >>> output = model.attractor(*coordinates) 116 | >>> print(output) 117 | (0, 0.2, 5.9) 118 | >>> model = Rossler(num_points=10, init_point=(0.1, 0, -0.1), step=100) 119 | >>> print(model.get_coordinates()) 120 | [[ 0.1 0. -0.1 ] 121 | [ 0.101 0.001 -0.0924 ] 122 | [ 0.101914 0.002012 -0.08522652] 123 | [ 0.10274615 0.00303516 -0.07845547] 124 | [ 0.10350035 0.0040687 -0.07206412] 125 | [ 0.1041803 0.00511184 -0.06603105] 126 | [ 0.10478949 0.00616386 -0.06033607] 127 | [ 0.10533122 0.00722409 -0.05496014] 128 | [ 0.10580858 0.00829185 -0.0498853 ] 129 | [ 0.10622451 0.00936652 -0.04509462]] 130 | 131 | See Also 132 | ----- 133 | https://en.wikipedia.org/wiki/R%C3%B6ssler_attractor 134 | """ 135 | x_out = -(y + z) 136 | y_out = x + a * y 137 | z_out = b + z * (x - c) 138 | 139 | return x_out, y_out, z_out 140 | 141 | 142 | if __name__ == "__main__": 143 | import doctest 144 | 145 | doctest.testmod(verbose=True) 146 | -------------------------------------------------------------------------------- /src/utils/calculator.py: -------------------------------------------------------------------------------- 1 | """Chaotic system calculator. 2 | 3 | Description: 4 | Useful component for calculate some parameters: 5 | math moments, FFTs, min and max values etc. 6 | 7 | ------------------------------------------------------------------------ 8 | 9 | GNU GENERAL PUBLIC LICENSE 10 | Version 3, 29 June 2007 11 | 12 | Copyright (c) 2019 Kapitanov Alexander 13 | 14 | This program is free software: you can redistribute it and/or modify 15 | it under the terms of the GNU General Public License as published by 16 | the Free Software Foundation, either version 3 of the License, or 17 | (at your option) any later version. 18 | 19 | You should have received a copy of the GNU General Public License 20 | along with this program. If not, see . 21 | 22 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 23 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 24 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT 25 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT 26 | NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 27 | FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND 28 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 29 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR 30 | OR CORRECTION. 31 | 32 | ------------------------------------------------------------------------ 33 | """ 34 | 35 | # Authors : Alexander Kapitanov 36 | # ... 37 | # Contacts : 38 | # ... 39 | # Release Date : 2020/07/25 40 | # License : GNU GENERAL PUBLIC LICENSE 41 | 42 | from typing import Tuple 43 | 44 | import numpy as np 45 | from scipy.fftpack import fft, fftshift 46 | from scipy.stats import gaussian_kde, kurtosis, skew 47 | 48 | 49 | class Calculator: 50 | """Main class for calculate math parameters: FFTs, Auto-Correlation, KDE (Prob) etc. 51 | 52 | See Also: 53 | ----- 54 | 55 | """ 56 | 57 | def __init__(self, kde_dots: int = 1000, fft_dots: int = 4096): 58 | self.kde_dots = kde_dots 59 | self.fft_dots = fft_dots 60 | self._coordinates = None 61 | 62 | def __len__(self): 63 | return len(self.coordinates) 64 | 65 | @property 66 | def coordinates(self) -> np.ndarray: 67 | return self._coordinates 68 | 69 | @coordinates.setter 70 | def coordinates(self, value: np.ndarray): 71 | """3D coordinates. 72 | 73 | Parameters 74 | ---------- 75 | value : np.ndarray 76 | Numpy 3D array of dynamic system coordinates. 77 | 78 | """ 79 | self._coordinates = value 80 | 81 | def check_min_max(self) -> Tuple[np.ndarray, np.ndarray]: 82 | """Calculate minimum and maximum for X, Y, Z coordinates. 83 | """ 84 | return np.min(self.coordinates, axis=0), np.max(self.coordinates, axis=0) 85 | 86 | def check_moments(self, is_common: bool = False) -> dict: 87 | """Calculate stochastic parameters: mean, variance, skewness, kurtosis etc. 88 | 89 | Parameters 90 | ---------- 91 | is_common : bool 92 | If False - method returns moments for each coordinate. Otherwise 93 | returns moments over all ndarray. Similar for axis or axes along 94 | which the moments are computed. 95 | The default is to compute the moments for each coordinate. 96 | """ 97 | axis = None if is_common else 0 98 | return { 99 | "Mean": np.mean(self.coordinates, axis=axis), 100 | "Variance": np.var(self.coordinates, axis=axis), 101 | "Skewness": skew(self.coordinates, axis=axis), 102 | "Kurtosis": kurtosis(self.coordinates, axis=axis), 103 | "Median": np.median(self.coordinates, axis=axis), 104 | } 105 | 106 | def check_probability(self): 107 | """Check probability for each chaotic coordinates. 108 | 109 | """ 110 | p_axi = np.zeros([3, self.kde_dots]) 111 | d_kde = np.zeros([3, self.kde_dots]) 112 | for ii in range(3): 113 | p_axi[ii] = np.linspace(self.coordinates[ii, :].min(), self.coordinates[ii, :].max(), self.kde_dots) 114 | d_kde[ii] = gaussian_kde(self.coordinates[ii, :]).evaluate(p_axi[ii, :]) 115 | d_kde[ii] /= d_kde[ii].max() 116 | return d_kde 117 | 118 | def calculate_spectrum(self): 119 | """Calculate FFT (in dB) for input 3D coordinates. You can set number of FFT points into the object instance. 120 | 121 | """ 122 | spectrum = fft(self.coordinates, self.fft_dots, axis=0) 123 | spectrum = np.abs(fftshift(spectrum, axes=0)) 124 | # spectrum = np.abs(spectrum) 125 | spectrum /= np.max(spectrum) 126 | spec_log = 20 * np.log10(spectrum + np.finfo(np.float32).eps) 127 | return spec_log 128 | 129 | def calculate_correlation(self): 130 | """Calculate auto correlation function for chaotic coordinates. 131 | 132 | """ 133 | nn, mm = 3, len(self.coordinates) 134 | auto_corr = np.zeros([mm, nn]) 135 | for ii in range(nn): 136 | auto_corr[:, ii] = np.correlate(self.coordinates[:, ii], self.coordinates[:, ii], "same") 137 | return auto_corr 138 | 139 | 140 | if __name__ == "__main__": 141 | calc = Calculator() 142 | 143 | num_dots = 10000 144 | np.random.seed(42) 145 | calc.coordinates = np.random.randn(num_dots, 3) 146 | 147 | dd_kde = calc.check_probability() 148 | import matplotlib.pyplot as plt 149 | 150 | print(dd_kde.shape) 151 | plt.figure("Probability density function") 152 | for idx in range(dd_kde.shape[0]): 153 | plt.plot(dd_kde[idx], ".") 154 | # plt.xlim([0, dd_kde.shape[1] - 1]) 155 | plt.grid() 156 | plt.tight_layout() 157 | plt.show() 158 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | .. -*- mode: rst -*- 2 | 3 | Python scripts for some 3rd-order chaotic systems (Lorenz attractor, 4 | Nose-Hoover oscillator, Rossler attractor, Riktake model, Duffing map etc.) 5 | 6 | Chaotic attractors 7 | ================== 8 | 9 | .. image:: https://raw.githubusercontent.com/capitanov/chaospy/master/img/Lorenz_3d.gif?sanitize=true 10 | 11 | Math model:: 12 | 13 | dx/dt = sigma * (y - x) 14 | dy/dt = rho * x - y - x * z 15 | dz/dt = x * y - beta * z 16 | 17 | where sigma = 10, rho = 28 and beta = 8/3. 18 | 19 | Main info 20 | ~~~~~~~~~ 21 | 22 | +---------------------+-----------------------------------------+ 23 | | **Title** | Analysis and modeling chaotic systems | 24 | +=====================+=========================================+ 25 | | **Author** | Alexander Kapitanov | 26 | +---------------------+-----------------------------------------+ 27 | | **Contact** | | 28 | +---------------------+-----------------------------------------+ 29 | | **Project lang** | Python 3 | 30 | +---------------------+-----------------------------------------+ 31 | | **First Release** | 30 May 2019 | 32 | +---------------------+-----------------------------------------+ 33 | | **License** | GNU GPL 3.0. | 34 | +---------------------+-----------------------------------------+ 35 | 36 | Chaotic system 37 | ~~~~~~~~~~~~~~~~~~~~~~~~ 38 | 39 | Rossler attractor:: 40 | 41 | dx/dt = -(y + z) 42 | dy/dt = x + a * y 43 | dz/dt = b + z * (x - c) 44 | 45 | where a = 0.2, b = 0.2 and c = 5.7. 46 | 47 | .. image:: https://raw.githubusercontent.com/capitanov/chaospy/master/img/Rossler_3D.png?sanitize=true 48 | 49 | Spectrum and auto correlation 50 | **************** 51 | .. image:: https://raw.githubusercontent.com/capitanov/chaospy/master/img/Lorenz_Spectrum.png?sanitize=true 52 | 53 | Source code 54 | ~~~~~~~~~~~ 55 | 56 | You can check the latest sources with the command:: 57 | 58 | $ git clone 59 | $ cd chaospy 60 | $ 61 | $ conda create -y -n venv python==3.9 62 | $ conda activate venv 63 | $ pip install -r requirements.txt 64 | 65 | Example run:: 66 | 67 | $ python run.py --show_plots --show_all lorenz 68 | 69 | 70 | Dependencies 71 | ~~~~~~~~~~~~ 72 | 73 | Project requirements: ``requirements.txt`` 74 | 75 | Chaotic models 76 | ~~~~~~~~~~~~~~~~~~~~~~~~ 77 | 78 | - Lorenz 79 | - Rossler 80 | - Rikitake 81 | - Duffing 82 | - Nose-Hoover 83 | - Lotka-Volterra 84 | - Wang 85 | - Chua 86 | 87 | Help 88 | ~~~~ 89 | 90 | :: 91 | 92 | usage: parser.py [-h] [-p POINTS] [-s STEP] 93 | [--init_point INIT_POINT [INIT_POINT ...]] [--show_plots] 94 | [--save_plots] [--add_2d_gif] 95 | {lorenz,rossler,rikitake,chua,duffing,wang,nose-hoover,lotka-volterra} 96 | ... 97 | 98 | Specify command line arguments for dynamic system.Calculate some math 99 | parameters and plot some graphs of a given chaotic system. 100 | 101 | optional arguments: 102 | -h, --help show this help message and exit 103 | -p POINTS, --points POINTS 104 | Number of points for dymanic system. Default: 1024. 105 | -s STEP, --step STEP Step size for calculating the next coordinates of 106 | chaotic system. Default: 100. 107 | --init_point INIT_POINT [INIT_POINT ...] 108 | Initial point as string of three floats: "X, Y, Z". 109 | --show_plots Show plots of a model. Default: False. 110 | --save_plots Save plots to PNG files. Default: False. 111 | --add_2d_gif Add 2D coordinates to 3D model into GIF. Default: 112 | False. 113 | 114 | Chaotic models: 115 | You can select one of the chaotic models: 116 | 117 | {lorenz,rossler,rikitake,chua,duffing,wang,nose-hoover,lotka-volterra} 118 | lorenz Lorenz chaotic model 119 | rossler Rossler chaotic model 120 | rikitake Rikitake chaotic model 121 | chua Chua chaotic model 122 | duffing Duffing chaotic model 123 | wang Wang chaotic model 124 | nose-hoover Nose-hoover chaotic model 125 | lotka-volterra Lotka-volterra chaotic model 126 | 127 | Chaotic attractors are used as subparse command. Example: 128 | 129 | Lorenz attractor 130 | **************** 131 | :: 132 | 133 | usage: parser.py lorenz [-h] [--sigma SIGMA] [--beta BETA] [--rho RHO] 134 | 135 | optional arguments: 136 | -h, --help show this help message and exit 137 | 138 | Lorenz model arguments: 139 | --sigma SIGMA Lorenz system parameter. Default: 10 140 | --beta BETA Lorenz system parameter. Default: 2.6666 141 | --rho RHO Lorenz system parameter. Default: 28 142 | 143 | Chua circuit 144 | ************ 145 | :: 146 | 147 | usage: parser.py chua [-h] [--alpha ALPHA] [--beta BETA] [--mu0 MU0] 148 | [--mu1 MU1] 149 | 150 | optional arguments: 151 | -h, --help show this help message and exit 152 | 153 | Chua model arguments: 154 | --alpha ALPHA Chua system parameter. Default: 0.1 155 | --beta BETA Chua system parameter. Default: 28 156 | --mu0 MU0 Chua system parameter. Default: -1.143 157 | --mu1 MU1 Chua system parameter. Default: -0.714 158 | 159 | See Also 160 | ~~~~~~~~ 161 | 162 | - `Wiki `__ 163 | - `Habr `__ 164 | -------------------------------------------------------------------------------- /src/attractors/attractor.py: -------------------------------------------------------------------------------- 1 | """Main attractor 2 | 3 | Description : 4 | Attractor base class. 5 | It implements abstract method (Chua, Lorenz, Duffing system). 6 | Can check some parameters for each chaotic system. 7 | 8 | ------------------------------------------------------------------------ 9 | 10 | GNU GENERAL PUBLIC LICENSE 11 | Version 3, 29 June 2007 12 | 13 | Copyright (c) 2019 Kapitanov Alexander 14 | 15 | This program is free software: you can redistribute it and/or modify 16 | it under the terms of the GNU General Public License as published by 17 | the Free Software Foundation, either version 3 of the License, or 18 | (at your option) any later version. 19 | 20 | You should have received a copy of the GNU General Public License 21 | along with this program. If not, see . 22 | 23 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 24 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 25 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT 26 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT 27 | NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 28 | FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND 29 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 30 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR 31 | OR CORRECTION. 32 | 33 | ------------------------------------------------------------------------ 34 | """ 35 | 36 | # Authors : Alexander Kapitanov 37 | # ... 38 | # Contacts : 39 | # ... 40 | # Release Date : 2020/07/16 41 | # License : GNU GENERAL PUBLIC LICENSE 42 | 43 | from abc import abstractmethod 44 | from typing import Tuple 45 | 46 | import numpy as np 47 | 48 | 49 | class BaseAttractor: 50 | """Base class for 3D chaotic system. 51 | 52 | Warning: Do not use this class directly. Use derived classes instead. 53 | 54 | Parameters 55 | ---------- 56 | num_points: int 57 | Number of points for X, Y, Z coordinates. 58 | 59 | init_point: tuple 60 | Initial point [x0, y0, z0] for chaotic attractor system. 61 | Do not use zeros or very big values because of unstable behavior of dynamic system. 62 | Default: x, y, z == 1e-4. 63 | 64 | step: float / int 65 | Step for the next coordinate of dynamic system. Default: 1.0. 66 | 67 | Examples 68 | -------- 69 | >>> from src.attractors.attractor import BaseAttractor 70 | >>> coordinates = (0, 1, -1) 71 | >>> model = BaseAttractor(num_points=10, init_point=(0.1, 2, -0.5), step=10) 72 | >>> print(model.get_coordinates()) 73 | [[ 0.1 2. -0.5 ] 74 | [ 0.11 2.2 -0.55 ] 75 | [ 0.121 2.42 -0.605 ] 76 | [ 0.1331 2.662 -0.6655 ] 77 | [ 0.14641 2.9282 -0.73205 ] 78 | [ 0.161051 3.22102 -0.805255 ] 79 | [ 0.1771561 3.543122 -0.8857805 ] 80 | [ 0.19487171 3.8974342 -0.97435855] 81 | [ 0.21435888 4.28717762 -1.07179441] 82 | [ 0.23579477 4.71589538 -1.17897385]] 83 | >>> print(len(model)) 84 | 10 85 | >>> model.update_attributes(num_points=1, init_point=(0, 1, 2), nfft=8) 86 | >>> model.__dict__ 87 | {'num_points': 1, 'init_point': (0, 1, 2), 'step': 10, 'nfft': 8, '_coordinates': None} 88 | >>> len(model) 89 | 1 90 | 91 | See Also: 92 | ----- 93 | Chaotic theory: 94 | https://en.wikipedia.org/wiki/Chaos_theory 95 | Attractors (dynamical systems): 96 | https://en.wikipedia.org/wiki/Attractor 97 | """ 98 | 99 | def __init__( 100 | self, 101 | num_points: int, 102 | init_point: Tuple[float, float, float] = (1e-4, 1e-4, 1e-4), 103 | step: float = 1.0, 104 | show_log: bool = False, 105 | **kwargs: dict, 106 | ): 107 | if show_log: 108 | print(f"[INFO]: Initialize chaotic system: {self.__class__.__name__}\n") 109 | self.num_points = num_points 110 | self.init_point = init_point 111 | self.step = step 112 | self.kwargs = kwargs 113 | 114 | def get_coordinates(self): 115 | return np.array(list(next(self))) 116 | 117 | def __len__(self): 118 | return self.num_points 119 | 120 | def __iter__(self): 121 | return self 122 | 123 | def __next__(self): 124 | points = self.init_point 125 | for i in range(self.num_points): 126 | try: 127 | yield points 128 | next_points = self.attractor(*points, **self.kwargs) 129 | points = tuple(prev + curr / self.step for prev, curr in zip(points, next_points)) 130 | except OverflowError: 131 | print(f"[FAIL]: Cannot do the next step because of floating point overflow. Step: {i}") 132 | break 133 | 134 | @abstractmethod 135 | def attractor(self, x: float, y: float, z: float, **kwargs) -> Tuple[float, float, float]: 136 | """Calculate the next coordinate X, Y, Z for chaotic system. 137 | Do not use this method for parent BaseAttractor class. 138 | 139 | Parameters 140 | ---------- 141 | x, y, z : float 142 | Input coordinates: X, Y, Z respectively 143 | 144 | Returns 145 | ------- 146 | result: tuple 147 | The next coordinates: X, Y, Z respectively 148 | """ 149 | # raise NotImplementedError 150 | return x + y + z, y - z, x ** 2 - z ** 2 151 | 152 | def update_attributes(self, **kwargs): 153 | """Update chaotic system parameters.""" 154 | for key in kwargs: 155 | if key in self.__dict__ and not key.startswith("_"): 156 | self.__dict__[key] = kwargs.get(key) 157 | 158 | 159 | if __name__ == "__main__": 160 | 161 | base_model = BaseAttractor(num_points=10, init_point=(-0.01, 0.5, 2), step=100) 162 | print(f"Model attributes: {base_model.__dict__}") 163 | print(f"Model length: {len(base_model)}") 164 | xyz = base_model.get_coordinates() 165 | print(xyz) 166 | -------------------------------------------------------------------------------- /src/attractors/duffing.py: -------------------------------------------------------------------------------- 1 | r"""Duffing map. 2 | 3 | Description: 4 | Duffing map. It is a discrete-time dynamical system (2nd order) 5 | The map depends on the two constants: a and b. 6 | Z coordinate is a linear function. 7 | 8 | Duffing equations are: 9 | Eq. 1: 10 | dx/dt = y 11 | dy/dt = -a*y - x**3 + b * cos(z) 12 | dz/dt = 1 13 | where a = 0.1 and b = 11 (default parameters) 14 | 15 | Eq. 2: 16 | dx/dt = y 17 | dy/dt = a*y - y**3 - b*x 18 | dz/dt = 1 19 | where a = 2.75 and b = 0.2 (default parameters) 20 | 21 | ------------------------------------------------------------------------ 22 | 23 | GNU GENERAL PUBLIC LICENSE 24 | Version 3, 29 June 2007 25 | 26 | Copyright (c) 2019 Kapitanov Alexander 27 | 28 | This program is free software: you can redistribute it and/or modify 29 | it under the terms of the GNU General Public License as published by 30 | the Free Software Foundation, either version 3 of the License, or 31 | (at your option) any later version. 32 | 33 | You should have received a copy of the GNU General Public License 34 | along with this program. If not, see . 35 | 36 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 37 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 38 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT 39 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT 40 | NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 41 | FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND 42 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 43 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR 44 | OR CORRECTION. 45 | 46 | ------------------------------------------------------------------------ 47 | """ 48 | 49 | # Authors : Alexander Kapitanov 50 | # ... 51 | # Contacts : 52 | # ... 53 | # Release Date : 2019/05/31 54 | # License : GNU GENERAL PUBLIC LICENSE 55 | 56 | from math import cos 57 | from typing import Tuple 58 | 59 | from src.attractors.attractor import BaseAttractor 60 | 61 | 62 | class Duffing(BaseAttractor): 63 | """Duffing attractor.""" 64 | 65 | def attractor( 66 | self, x: float, y: float, z: float, alpha: float = 0.1, beta: float = 11 67 | ) -> Tuple[float, float, float]: 68 | r"""Calculate the next coordinate X, Y, Z for 3rd-order Duffing map. 69 | It is 2nd order attractor (Z coordinate = 1) 70 | 71 | Parameters 72 | ---------- 73 | x, y, z : float 74 | Input coordinates X, Y, Z respectively 75 | alpha, beta: float 76 | Duffing map parameters. Default: 77 | - alpha = 0.1, 78 | - beta = 11, 79 | 80 | Examples 81 | -------- 82 | >>> from src.attractors.duffing import Duffing 83 | >>> coordinates = (0, 1, -1) 84 | >>> model = Duffing(num_points=1) 85 | >>> output = model.attractor(*coordinates) 86 | >>> print(output) 87 | (1, 5.843325364549537, 1) 88 | >>> model = Duffing(num_points=10, init_point=(0.1, 0, -0.1), step=100) 89 | >>> print(model.get_coordinates()) 90 | [[ 0.1 0. -0.1 ] 91 | [ 0.1 0.10944046 -0.09 ] 92 | [ 0.1010944 0.21887582 -0.08 ] 93 | [ 0.10328316 0.3282948 -0.07 ] 94 | [ 0.10656611 0.4376861 -0.06 ] 95 | [ 0.11094297 0.54703837 -0.05 ] 96 | [ 0.11641336 0.6563402 -0.04 ] 97 | [ 0.12297676 0.7655801 -0.03 ] 98 | [ 0.13063256 0.87474642 -0.02 ] 99 | [ 0.13938002 0.98382738 -0.01 ]] 100 | 101 | See Also 102 | ----- 103 | Duffing map (attractor): 104 | https://en.wikipedia.org/wiki/Duffing_map 105 | Duffing equation: 106 | https://en.wikipedia.org/wiki/Duffing_equation 107 | 108 | """ 109 | x_out = y 110 | y_out = -alpha * y - x ** 3 + beta * cos(z) 111 | z_out = 1 112 | return x_out, y_out, z_out 113 | 114 | 115 | class DuffingMap(BaseAttractor): 116 | """Duffing attractor.""" 117 | 118 | def attractor( 119 | self, x: float, y: float, z: float, alpha: float = 2.75, beta: float = 0.2 120 | ) -> Tuple[float, float, float]: 121 | """Calculate the next coordinate X, Y, Z for 3rd-order Duffing map. 122 | It is 2nd order attractor (Z coordinate = 1) 123 | 124 | Parameters 125 | ---------- 126 | x, y, z : float 127 | Input coordinates X, Y, Z respectively 128 | alpha, beta: float 129 | Duffing map parameters. Default: 130 | - alpha = 2.75, 131 | - beta = 0.2, 132 | 133 | Examples 134 | -------- 135 | >>> from src.attractors.duffing import Duffing 136 | >>> coordinates = (0, 0.5, -1) 137 | >>> model = Duffing(num_points=1) 138 | >>> output = model.attractor(*coordinates) 139 | >>> print(output) 140 | (0.5, 5.893325364549537, 1) 141 | >>> model = Duffing(num_points=10, init_point=(0, 4, -0.1), step=100) 142 | >>> print(model.get_coordinates()) 143 | [[ 0. 4. -0.1 ] 144 | [ 0.04 4.10545046 -0.09 ] 145 | [ 0.0810545 4.21089917 -0.08 ] 146 | [ 0.1231635 4.31633113 -0.07 ] 147 | [ 0.16632681 4.42172673 -0.06 ] 148 | [ 0.21054407 4.52706105 -0.05 ] 149 | [ 0.25581469 4.63230318 -0.04 ] 150 | [ 0.30213772 4.73741548 -0.03 ] 151 | [ 0.34951187 4.84235276 -0.02 ] 152 | [ 0.3979354 4.94706145 -0.01 ]] 153 | 154 | See Also 155 | ----- 156 | Duffing map (attractor): 157 | https://en.wikipedia.org/wiki/Duffing_map 158 | Duffing equation: 159 | https://en.wikipedia.org/wiki/Duffing_equation 160 | 161 | """ 162 | x_out = y 163 | y_out = alpha * y - y ** 3 - beta * x 164 | z_out = 1 165 | return x_out, y_out, z_out 166 | 167 | 168 | if __name__ == "__main__": 169 | import doctest 170 | 171 | doctest.testmod(verbose=True) 172 | -------------------------------------------------------------------------------- /src/utils/parser.py: -------------------------------------------------------------------------------- 1 | r"""Argument parser for testing chaotic attractor. 2 | 3 | ------------------------------------------------------------------------ 4 | 5 | GNU GENERAL PUBLIC LICENSE 6 | Version 3, 29 June 2007 7 | 8 | Copyright (c) 2019 Kapitanov Alexander 9 | 10 | This program is free software: you can redistribute it and/or modify 11 | it under the terms of the GNU General Public License as published by 12 | the Free Software Foundation, either version 3 of the License, or 13 | (at your option) any later version. 14 | 15 | You should have received a copy of the GNU General Public License 16 | along with this program. If not, see . 17 | 18 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 19 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 20 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT 21 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT 22 | NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 23 | FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND 24 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 25 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR 26 | OR CORRECTION. 27 | 28 | ------------------------------------------------------------------------ 29 | """ 30 | 31 | # Authors : Alexander Kapitanov 32 | # ... 33 | # Contacts : 34 | # ... 35 | # Release Date : 2020/07/30 36 | # License : GNU GENERAL PUBLIC LICENSE 37 | 38 | import argparse 39 | from typing import Optional, Sequence, Tuple, Union 40 | 41 | from src.attractors.chua import Chua 42 | from src.attractors.duffing import Duffing 43 | from src.attractors.lorenz import Lorenz 44 | from src.attractors.lotka_volterra import LotkaVolterra 45 | from src.attractors.nose_hoover import NoseHoover 46 | from src.attractors.rikitake import Rikitake 47 | from src.attractors.rossler import Rossler 48 | from src.attractors.wang import Wang 49 | 50 | AttractorType = Union[Chua, Duffing, Rossler, Lorenz, Wang, NoseHoover, Rikitake, Wang, LotkaVolterra] 51 | 52 | DEFAULT_PARAMETERS = { 53 | "lorenz": {"sigma": 10, "beta": 8 / 3, "rho": 28}, 54 | "rikitake": {"a": 1, "mu": 1}, 55 | "duffing": {"alpha": 0.1, "beta": 11}, 56 | "rossler": {"a": 0.2, "b": 0.2, "c": 5.7}, 57 | "chua": {"alpha": 0.1, "beta": 28, "mu0": -1.143, "mu1": -0.714}, 58 | } 59 | 60 | 61 | class Settings: 62 | r"""Attributes collection for chaotic system. 63 | 64 | Attributes 65 | ---------- 66 | 67 | attractor : Optional[AttractorType] 68 | Chaotic model. 69 | 70 | points : step 71 | Number of points for 3D system. 72 | 73 | step : float 74 | Step for diff. equations. 75 | 76 | show_timeplot : bool 77 | Show time plots 78 | 79 | show_spectrum : bool 80 | Show spectrum plots 81 | 82 | show_3d_plots : bool 83 | Show 3D plots 84 | 85 | show_all : bool 86 | Show all plots 87 | 88 | show_plots : bool 89 | Show plots after calculations: True / False. 90 | 91 | save_plots : bool 92 | Save plots after calculations: True / False. 93 | 94 | """ 95 | __model_map = { 96 | "lorenz": Lorenz, 97 | "rossler": Rossler, 98 | "rikitake": Rikitake, 99 | "chua": Chua, 100 | "duffing": Duffing, 101 | "wang": Wang, 102 | "nose-hoover": NoseHoover, 103 | "lotka-volterra": LotkaVolterra, 104 | } 105 | 106 | def __init__(self, show_logs: bool = False, show_help: bool = False): 107 | self.show_logs = show_logs 108 | self.show_help = show_help 109 | # Settings 110 | self.attractor: str = "lorenz" 111 | self.init_point: Tuple[float, float, float] = (0.1, -0.1, 0.1) 112 | self.points: int = 1024 113 | self.step: float = 10 114 | self.add_2d_gif: bool = False 115 | self.show_all: bool = False 116 | self.show_timeplot: bool = False 117 | self.show_spectrum: bool = False 118 | self.show_3d_plots: bool = False 119 | self.show_plots: bool = False 120 | self.save_plots: bool = False 121 | self.kwargs: dict = {} 122 | # Model 123 | self._model: Optional[AttractorType] = None 124 | 125 | @property 126 | def model(self) -> Optional[AttractorType]: 127 | r"""Return model from dict of attractors. 128 | Set initial parameters. 129 | 130 | """ 131 | if self._model is None: 132 | self._model = self.__model_map.get(self.attractor)( 133 | num_points=self.points, 134 | init_point=self.init_point, 135 | step=self.step, 136 | show_log=self.show_logs, 137 | **self.kwargs, 138 | ) 139 | return self._model 140 | 141 | def update_params(self, input_args: Optional[Sequence[str]] = None): 142 | r"""Update class attributes from command line parser. 143 | Kwargs is a dictionary, and it can have some parameters for chaotic model. 144 | 145 | Parameters 146 | ---------- 147 | input_args : tuple 148 | Tuple of strings for input arguments. Example: ("--show_plots", "--step", "1000", "lorenz") 149 | 150 | """ 151 | args_dict = self.parse_arguments(input_args=input_args, show_args=self.show_logs, show_help=self.show_help) 152 | for item in args_dict: 153 | if hasattr(self, item) and item is not None: 154 | setattr(self, item, args_dict[item]) 155 | else: 156 | self.kwargs[item] = args_dict[item] 157 | 158 | self.init_point = args_dict["init_point"] 159 | 160 | @staticmethod 161 | def _three_floats(value) -> Tuple: 162 | values = value.split() 163 | if len(values) != 3: 164 | print(f"[FAIL]: Please enter initial points as X, Y, Z list. Example: --init_point 1 2 3") 165 | raise argparse.ArgumentError 166 | return tuple(map(float, values)) 167 | 168 | def parse_arguments( 169 | self, input_args: Optional[Sequence[str]] = None, show_help: bool = False, show_args: bool = False 170 | ) -> dict: 171 | """This method is the useful command line helper. You can use it with command line arguments. 172 | 173 | Parameters 174 | ---------- 175 | input_args : tuple 176 | 177 | show_help : bool 178 | Show help of argument parser. 179 | 180 | show_args : bool 181 | Display arguments and their values as {key : item} 182 | 183 | Returns 184 | ------- 185 | arguments : dict 186 | Parsed arguments from command line. Note: some arguments are positional. 187 | 188 | Examples 189 | -------- 190 | >>> from src.utils.parser import Settings 191 | >>> settings = Settings() 192 | >>> command_line_str = "lorenz", 193 | >>> test_args = settings.parse_arguments(command_line_str, show_args=True) 194 | [INFO]: Cmmaind line arguments: 195 | points = 1024 196 | step = 100 197 | init_point = (0.1, -0.1, 0.1) 198 | show_plots = False 199 | save_plots = False 200 | add_2d_gif = False 201 | attractor = lorenz 202 | sigma = 10 203 | beta = 2.6666666666666665 204 | rho = 28 205 | 206 | >>> command_line_str = "--show_plots rossler --a 2 --b 4".split() 207 | >>> test_args = settings.parse_arguments(command_line_str, show_args=True) 208 | [INFO]: Cmmaind line arguments: 209 | points = 1024 210 | step = 100 211 | init_point = (0.1, -0.1, 0.1) 212 | show_plots = True 213 | save_plots = False 214 | add_2d_gif = False 215 | attractor = rossler 216 | a = 2.0 217 | b = 4.0 218 | c = 5.7 219 | 220 | """ 221 | parser = argparse.ArgumentParser( 222 | description="Specify command line arguments for dynamic system." 223 | "Calculate some math parameters and plot some graphs of a given chaotic system." 224 | ) 225 | 226 | parser.add_argument( 227 | "-p", 228 | "--points", 229 | type=int, 230 | default=1024, 231 | action="store", 232 | help=f"Number of points for dymanic system. Default: 1024.", 233 | ) 234 | 235 | parser.add_argument( 236 | "-s", 237 | "--step", 238 | type=int, 239 | default=100, 240 | action="store", 241 | help=f"Step size for calculating the next coordinates of chaotic system. Default: 100.", 242 | ) 243 | 244 | parser.add_argument( 245 | "--init_point", 246 | action="store", 247 | type=self._three_floats, 248 | default=(0.1, -0.1, 0.1), 249 | help='Initial point as string of three floats: "X, Y, Z".', 250 | ) 251 | parser.add_argument("--show_plots", action="store_true", help="Show plots of a model. Default: False.") 252 | parser.add_argument("--save_plots", action="store_true", help="Save plots to PNG files. Default: False.") 253 | parser.add_argument("--show_spectrum", action="store_true", help="Show spectrum plots") 254 | parser.add_argument("--show_timeplot", action="store_true", help="Save time plots.") 255 | parser.add_argument("--show_3d_plots", action="store_true", help="Save 3d plots.") 256 | parser.add_argument("--show_all", action="store_true", help="Save all plots.") 257 | parser.add_argument( 258 | "--add_2d_gif", action="store_true", help="Add 2D coordinates to 3D model into GIF. Default: False." 259 | ) 260 | 261 | subparsers = parser.add_subparsers( 262 | title="Chaotic models", description="You can select one of the chaotic models:", dest="attractor" 263 | ) 264 | 265 | sub_list = [] 266 | for attractor in [*self.__model_map]: 267 | chosen_items = DEFAULT_PARAMETERS.get(attractor) 268 | chosen_model = f"{attractor}".capitalize() 269 | subparser = subparsers.add_parser(f"{attractor}", help=f"{chosen_model} chaotic model") 270 | if chosen_items is not None: 271 | group = subparser.add_argument_group(title=f"{chosen_model} model arguments") 272 | for key in chosen_items: 273 | group.add_argument( 274 | f"--{key}", 275 | type=float, 276 | default=chosen_items[key], 277 | action="store", 278 | help=f"{chosen_model} system parameter. Default: {chosen_items[key]}", 279 | ) 280 | sub_list.append(subparser) 281 | 282 | if show_help: 283 | parser.print_help() 284 | for item in sub_list: 285 | item.print_help() 286 | 287 | args = vars(parser.parse_args(input_args)) 288 | if args["attractor"] is None: 289 | raise AssertionError(f"[FAIL]: Please select a chaotic model from the next set: {[*self.__model_map]}") 290 | if show_args: 291 | print(f"[INFO]: Cmmaind line arguments:") 292 | for arg in args: 293 | print(f"{arg :<14} = {args[arg]}") 294 | 295 | if args["init_point"] is not None and len(args["init_point"]) != 3: 296 | raise AssertionError(f"[FAIL]: Please enter initial points as X, Y, Z list. Example: --init_point 1 2 3") 297 | return args 298 | 299 | 300 | if __name__ == "__main__": 301 | import doctest 302 | 303 | doctest.testmod(verbose=True) 304 | # command_line = "--init_point", '0 -1 2', "lorenz" 305 | # params = Settings(show_logs=True, show_help=True) 306 | # params.update_params(input_args=command_line) 307 | -------------------------------------------------------------------------------- /src/utils/drawer.py: -------------------------------------------------------------------------------- 1 | """Plot drawer 2 | 3 | Description : 4 | Useful component for plotting results 5 | 6 | ------------------------------------------------------------------------ 7 | 8 | GNU GENERAL PUBLIC LICENSE 9 | Version 3, 29 June 2007 10 | 11 | Copyright (c) 2019 Kapitanov Alexander 12 | 13 | This program is free software: you can redistribute it and/or modify 14 | it under the terms of the GNU General Public License as published by 15 | the Free Software Foundation, either version 3 of the License, or 16 | (at your option) any later version. 17 | 18 | You should have received a copy of the GNU General Public License 19 | along with this program. If not, see . 20 | 21 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 22 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 23 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT 24 | WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT 25 | NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS 26 | FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND 27 | PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE PROGRAM PROVE 28 | DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, REPAIR OR 29 | OR CORRECTION. 30 | 31 | ------------------------------------------------------------------------ 32 | """ 33 | 34 | # Authors : Alexander Kapitanov 35 | # ... 36 | # Contacts : 37 | # ... 38 | # Release Date : 2020/07/25 39 | # License : GNU GENERAL PUBLIC LICENSE 40 | 41 | import matplotlib.animation as animation 42 | import matplotlib.pyplot as plt 43 | import mpl_toolkits.mplot3d.axes3d as p3 # noqa # pylint: disable=unused-import 44 | import numpy as np 45 | 46 | 47 | class PlotDrawer: 48 | """Main class for drawing plots. 49 | 50 | See Also: 51 | ----- 52 | Matplotlib: Visualization with Python: 53 | https://matplotlib.org/ 54 | 55 | """ 56 | 57 | _plot_axis = ((0, 1), (2, 1), (0, 2)) 58 | _plot_labels = {0: "X", 1: "Y", 2: "Z"} 59 | 60 | def __init__( 61 | self, save_plots: bool = False, show_plots: bool = False, add_2d_gif: bool = False, model_name: str = None, 62 | ): 63 | self.save_plots = save_plots 64 | self.show_plots = show_plots 65 | self.add_2d_gif = add_2d_gif 66 | self.time_or_dot = False 67 | 68 | self._model_name = model_name 69 | self._coordinates = None 70 | # Internal parameters 71 | self._color_map = None 72 | self._plot_list = None 73 | self._min_max_axis = None 74 | self.coordinates = None 75 | 76 | @property 77 | def model_name(self): 78 | return self._model_name 79 | 80 | @model_name.setter 81 | def model_name(self, value: str): 82 | self._model_name = value 83 | 84 | @staticmethod 85 | def __min_max_axis(coordinates: np.ndarray): 86 | return np.vstack([np.min(coordinates, axis=0), np.max(coordinates, axis=0)]).T 87 | 88 | def plot_kde(self, kde: np.ndarray, pdf: np.ndarray): 89 | """Plot Probability density function""" 90 | _ = plt.figure("Probability density function", figsize=(8, 6), dpi=100) 91 | for ii, axis in enumerate(self._plot_labels.values()): 92 | plt.subplot(3, 3, ii + 1) 93 | plt.title("KDE plots", y=1.0) if ii % 2 == 1 else None 94 | plt.plot(kde[ii], ".") 95 | plt.xlim([0, pdf - 1]) 96 | plt.grid() 97 | plt.tight_layout() 98 | 99 | def show_spectrum_and_correlation(self, coordinates: np.ndarray, spectrums: np.ndarray, correlations: np.ndarray): 100 | """Plot 3D coordinates as time series.""" 101 | _ = plt.figure("Autocorrelation and Spectrum", figsize=(8, 6), dpi=100) 102 | 103 | x_corr = np.linspace(-len(coordinates) // 2, len(coordinates) // 2, len(coordinates)) 104 | x_ffts = np.linspace(-0.5, 0.5, len(spectrums)) 105 | 106 | plt.suptitle(f"{self.model_name} attractor", x=0.1) 107 | for ii, axis in enumerate(self._plot_labels.values()): 108 | plt.subplot(3, 3, ii + 1) 109 | plt.title("Time plots", y=1.0) if ii % 2 == 1 else None 110 | plt.plot(coordinates[:, ii], linewidth=0.75) 111 | plt.grid(True) 112 | plt.ylabel(axis) 113 | plt.xlim([0, len(coordinates) - 1]) 114 | plt.subplot(3, 3, ii + 4) 115 | plt.title("Spectrum plots", y=1.0) if ii % 2 == 1 else None 116 | plt.plot(x_ffts, spectrums[:, ii], linewidth=0.75) 117 | plt.grid(True) 118 | plt.ylabel(axis) 119 | plt.xlim([np.min(x_ffts), np.max(x_ffts)]) 120 | plt.subplot(3, 3, ii + 7) 121 | plt.title("Correlation plots", y=1.0) if ii % 2 == 1 else None 122 | plt.plot(x_corr, correlations[:, ii], linewidth=0.75) 123 | plt.grid(True) 124 | plt.ylabel(axis) 125 | plt.xlim([np.min(x_corr), np.max(x_corr)]) 126 | plt.tight_layout() 127 | 128 | if self.save_plots: 129 | plt.savefig(f"{self.model_name}_spectrum_correlations.png") 130 | if self.show_plots: 131 | plt.show() 132 | 133 | def show_time_plots(self, coordinates: np.ndarray): 134 | """Plot 3D coordinates as time series.""" 135 | _ = plt.figure("Coordinates evolution in time", figsize=(8, 6), dpi=100) 136 | for ii, axis in enumerate(self._plot_labels.values()): 137 | plt.subplot(3, 1, ii + 1) 138 | plt.plot(coordinates[:, ii], linewidth=0.75) 139 | plt.grid(True) 140 | if axis == "Z": 141 | plt.xlabel("Time (t)") 142 | plt.ylabel(axis) 143 | plt.xlim([0, len(coordinates) - 1]) 144 | plt.tight_layout() 145 | if self.save_plots: 146 | plt.savefig(f"{self.model_name}_coordinates_in_time.png") 147 | if self.show_plots: 148 | plt.show() 149 | 150 | def __axis_defaults_3d(self, plots, coordinates: np.ndarray): 151 | min_max = self.__min_max_axis(coordinates) 152 | plots.set_title(f"{self.model_name} model") 153 | plots.set_xlabel("X") 154 | plots.set_ylabel("Y") 155 | plots.set_zlabel("Z") 156 | plots.set_xlim3d(min_max[0]) 157 | plots.set_ylim3d(min_max[1]) 158 | plots.set_zlim3d(min_max[2]) 159 | plots.xaxis.pane.fill = False 160 | plots.yaxis.pane.fill = False 161 | plots.zaxis.pane.fill = False 162 | 163 | def __axis_defaults_2d(self, plots, coordinates: np.ndarray): 164 | min_max = self.__min_max_axis(coordinates) 165 | for idx, (xx, yy) in enumerate(self._plot_axis): 166 | plots[idx].set_xlim(min_max[xx]) 167 | plots[idx].set_ylim(min_max[yy]) 168 | plots[idx].set_xlabel(self._plot_labels[xx]) 169 | plots[idx].set_ylabel(self._plot_labels[yy]) 170 | plots[idx].grid(True) 171 | # ax.set_axis_off() 172 | # ax.xaxis.pane.set_edgecolor('w') 173 | # ax.yaxis.pane.set_edgecolor('w') 174 | # ax.zaxis.pane.set_edgecolor('w') 175 | # ax.grid(False) 176 | # ax.tight_layout() 177 | 178 | def show_3d_plots(self, coordinates: np.ndarray): 179 | """Plot 3D coordinates as time series.""" 180 | min_max = self.__min_max_axis(coordinates) 181 | 182 | fig = plt.figure(f"3D model of {self.model_name} system", figsize=(8, 6), dpi=100) 183 | for ii, (xx, yy) in enumerate(self._plot_axis): 184 | plt.subplot(2, 2, 1 + ii) 185 | plt.plot(coordinates[:, xx], coordinates[:, yy], linewidth=0.75) 186 | plt.grid() 187 | plt.xlabel(self._plot_labels[xx]) 188 | plt.ylabel(self._plot_labels[yy]) 189 | plt.xlim(min_max[xx]) 190 | plt.ylim(min_max[yy]) 191 | 192 | ax = fig.add_subplot(2, 2, 4, projection="3d") 193 | ax.plot(coordinates[:, 0], coordinates[:, 1], coordinates[:, 2], linewidth=0.75) 194 | self.__axis_defaults_3d(ax, coordinates) 195 | plt.tight_layout() 196 | 197 | if self.save_plots: 198 | plt.savefig(f"{self.model_name}_3d_coordinates.png") 199 | if self.show_plots: 200 | plt.show() 201 | 202 | def _add_2d_to_plots(self, figure, coordinates: np.ndarray): 203 | self._plot_list += [figure.add_subplot(2, 2, 1 + ii) for ii in range(3)] 204 | self.__axis_defaults_2d(self._plot_list[1:], coordinates) 205 | plt.tight_layout() 206 | 207 | def make_3d_plot_gif(self, coordinates: np.ndarray, step_size: int = 10): 208 | """Make git for 3D coordinates as time series.""" 209 | nodes = 2 if self.add_2d_gif else 1 210 | posit = 4 if self.add_2d_gif else 1 211 | fig = plt.figure(f"3D model of {self.model_name} system", figsize=(8, 6), dpi=100) 212 | 213 | self._plot_list = [fig.add_subplot(nodes, nodes, posit, projection="3d")] 214 | self.__axis_defaults_3d(self._plot_list[0], coordinates) 215 | 216 | if self.add_2d_gif: 217 | self._add_2d_to_plots(fig, coordinates) 218 | 219 | # Convert ax to plot 220 | self._plot_list = [item.plot([], [], ".--", lw=0.75)[0] for item in self._plot_list] 221 | 222 | step_dots = len(coordinates) // step_size 223 | self._color_map = plt.cm.get_cmap("hsv", step_dots) 224 | 225 | self.coordinates = coordinates 226 | ani = animation.FuncAnimation( 227 | fig, self._update_coordinates, step_dots, fargs=(step_size,), interval=100, blit=False, repeat=True 228 | ) 229 | 230 | if self.save_plots: 231 | ani.save(f"{self.model_name}_3d.gif", writer="imagemagick") 232 | if self.show_plots: 233 | plt.show() 234 | 235 | def _update_coordinates(self, num, step): 236 | """Update plots for making gif""" 237 | self._plot_list[0].set_data(self.coordinates[0 : 1 + num * step, 0], self.coordinates[0 : 1 + num * step, 1]) 238 | self._plot_list[0].set_3d_properties(self.coordinates[0 : 1 + num * step, 2]) 239 | self._plot_list[0].set_color(self._color_map(num)) 240 | if self.add_2d_gif: 241 | for ii, (x, y) in enumerate(self._plot_axis): 242 | self._plot_list[ii + 1].set_data( 243 | self.coordinates[0 : 1 + num * step, x], self.coordinates[0 : 1 + num * step, y] 244 | ) 245 | self._plot_list[ii + 1].set_color(self._color_map(num)) 246 | 247 | def show_all_plots(self, coordinates: np.ndarray, spectrums: np.ndarray, correlations: np.ndarray): 248 | """Cannot show all plots while 'show_plots' is True. 249 | 250 | Note: After closing plots you cannot reopen them! 251 | """ 252 | show_plots, self.show_plots = self.show_plots, False 253 | self.show_time_plots(coordinates) 254 | self.show_3d_plots(coordinates) 255 | self.show_spectrum_and_correlation(coordinates, spectrums, correlations) 256 | plt.show() 257 | self.show_plots = show_plots 258 | 259 | 260 | def random_circle(num_points: int = 100, sigma: float = 0.01, angle: float = 2.) -> np.ndarray: 261 | r"""Create random circle for 3D plots. 262 | 263 | Parameters 264 | ---------- 265 | num_points : int 266 | Number of points to draw 267 | 268 | sigma : int 269 | Random shift 270 | 271 | angle : int 272 | Rotate angle 273 | 274 | Returns 275 | ------- 276 | 277 | arr: np.ndarray 278 | Numpy 3D array with shapes [3, num_points] 279 | """ 280 | 281 | theta = np.linspace(0, angle * np.pi, num_points) 282 | xyz = np.vstack([np.cos(theta), np.sin(theta), np.sin(np.linspace(0, 2.05 * np.pi, num_points))]).T 283 | xyz += sigma * np.cumsum(np.random.randn(num_points, 3), axis=1) 284 | return xyz 285 | 286 | 287 | if __name__ == "__main__": 288 | np.random.seed(42) 289 | circle_points = random_circle(num_points=400, sigma=0.01) 290 | 291 | drawer = PlotDrawer(show_plots=True, add_2d_gif=True) 292 | drawer.model_name = "Chaotic" 293 | 294 | # print(drawer.min_max_axis) 295 | drawer.make_3d_plot_gif(step_size=10, coordinates=circle_points) 296 | # drawer.show_time_plots() 297 | # drawer.show_3d_plots() 298 | # drawer.show_all_plots() 299 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 3, 29 June 2007 3 | 4 | Copyright (C) 2007 Free Software Foundation, Inc. 5 | Everyone is permitted to copy and distribute verbatim copies 6 | of this license document, but changing it is not allowed. 7 | 8 | Preamble 9 | 10 | The GNU General Public License is a free, copyleft license for 11 | software and other kinds of works. 12 | 13 | The licenses for most software and other practical works are designed 14 | to take away your freedom to share and change the works. By contrast, 15 | the GNU General Public License is intended to guarantee your freedom to 16 | share and change all versions of a program--to make sure it remains free 17 | software for all its users. We, the Free Software Foundation, use the 18 | GNU General Public License for most of our software; it applies also to 19 | any other work released this way by its authors. You can apply it to 20 | your programs, too. 21 | 22 | When we speak of free software, we are referring to freedom, not 23 | price. Our General Public Licenses are designed to make sure that you 24 | have the freedom to distribute copies of free software (and charge for 25 | them if you wish), that you receive source code or can get it if you 26 | want it, that you can change the software or use pieces of it in new 27 | free programs, and that you know you can do these things. 28 | 29 | To protect your rights, we need to prevent others from denying you 30 | these rights or asking you to surrender the rights. Therefore, you have 31 | certain responsibilities if you distribute copies of the software, or if 32 | you modify it: responsibilities to respect the freedom of others. 33 | 34 | For example, if you distribute copies of such a program, whether 35 | gratis or for a fee, you must pass on to the recipients the same 36 | freedoms that you received. You must make sure that they, too, receive 37 | or can get the source code. And you must show them these terms so they 38 | know their rights. 39 | 40 | Developers that use the GNU GPL protect your rights with two steps: 41 | (1) assert copyright on the software, and (2) offer you this License 42 | giving you legal permission to copy, distribute and/or modify it. 43 | 44 | For the developers' and authors' protection, the GPL clearly explains 45 | that there is no warranty for this free software. For both users' and 46 | authors' sake, the GPL requires that modified versions be marked as 47 | changed, so that their problems will not be attributed erroneously to 48 | authors of previous versions. 49 | 50 | Some devices are designed to deny users access to install or run 51 | modified versions of the software inside them, although the manufacturer 52 | can do so. This is fundamentally incompatible with the aim of 53 | protecting users' freedom to change the software. The systematic 54 | pattern of such abuse occurs in the area of products for individuals to 55 | use, which is precisely where it is most unacceptable. Therefore, we 56 | have designed this version of the GPL to prohibit the practice for those 57 | products. If such problems arise substantially in other domains, we 58 | stand ready to extend this provision to those domains in future versions 59 | of the GPL, as needed to protect the freedom of users. 60 | 61 | Finally, every program is threatened constantly by software patents. 62 | States should not allow patents to restrict development and use of 63 | software on general-purpose computers, but in those that do, we wish to 64 | avoid the special danger that patents applied to a free program could 65 | make it effectively proprietary. To prevent this, the GPL assures that 66 | patents cannot be used to render the program non-free. 67 | 68 | The precise terms and conditions for copying, distribution and 69 | modification follow. 70 | 71 | TERMS AND CONDITIONS 72 | 73 | 0. Definitions. 74 | 75 | "This License" refers to version 3 of the GNU General Public License. 76 | 77 | "Copyright" also means copyright-like laws that apply to other kinds of 78 | works, such as semiconductor masks. 79 | 80 | "The Program" refers to any copyrightable work licensed under this 81 | License. Each licensee is addressed as "you". "Licensees" and 82 | "recipients" may be individuals or organizations. 83 | 84 | To "modify" a work means to copy from or adapt all or part of the work 85 | in a fashion requiring copyright permission, other than the making of an 86 | exact copy. The resulting work is called a "modified version" of the 87 | earlier work or a work "based on" the earlier work. 88 | 89 | A "covered work" means either the unmodified Program or a work based 90 | on the Program. 91 | 92 | To "propagate" a work means to do anything with it that, without 93 | permission, would make you directly or secondarily liable for 94 | infringement under applicable copyright law, except executing it on a 95 | computer or modifying a private copy. Propagation includes copying, 96 | distribution (with or without modification), making available to the 97 | public, and in some countries other activities as well. 98 | 99 | To "convey" a work means any kind of propagation that enables other 100 | parties to make or receive copies. Mere interaction with a user through 101 | a computer network, with no transfer of a copy, is not conveying. 102 | 103 | An interactive user interface displays "Appropriate Legal Notices" 104 | to the extent that it includes a convenient and prominently visible 105 | feature that (1) displays an appropriate copyright notice, and (2) 106 | tells the user that there is no warranty for the work (except to the 107 | extent that warranties are provided), that licensees may convey the 108 | work under this License, and how to view a copy of this License. If 109 | the interface presents a list of user commands or options, such as a 110 | menu, a prominent item in the list meets this criterion. 111 | 112 | 1. Source Code. 113 | 114 | The "source code" for a work means the preferred form of the work 115 | for making modifications to it. "Object code" means any non-source 116 | form of a work. 117 | 118 | A "Standard Interface" means an interface that either is an official 119 | standard defined by a recognized standards body, or, in the case of 120 | interfaces specified for a particular programming language, one that 121 | is widely used among developers working in that language. 122 | 123 | The "System Libraries" of an executable work include anything, other 124 | than the work as a whole, that (a) is included in the normal form of 125 | packaging a Major Component, but which is not part of that Major 126 | Component, and (b) serves only to enable use of the work with that 127 | Major Component, or to implement a Standard Interface for which an 128 | implementation is available to the public in source code form. A 129 | "Major Component", in this context, means a major essential component 130 | (kernel, window system, and so on) of the specific operating system 131 | (if any) on which the executable work runs, or a compiler used to 132 | produce the work, or an object code interpreter used to run it. 133 | 134 | The "Corresponding Source" for a work in object code form means all 135 | the source code needed to generate, install, and (for an executable 136 | work) run the object code and to modify the work, including scripts to 137 | control those activities. However, it does not include the work's 138 | System Libraries, or general-purpose tools or generally available free 139 | programs which are used unmodified in performing those activities but 140 | which are not part of the work. For example, Corresponding Source 141 | includes interface definition files associated with source files for 142 | the work, and the source code for shared libraries and dynamically 143 | linked subprograms that the work is specifically designed to require, 144 | such as by intimate data communication or control flow between those 145 | subprograms and other parts of the work. 146 | 147 | The Corresponding Source need not include anything that users 148 | can regenerate automatically from other parts of the Corresponding 149 | Source. 150 | 151 | The Corresponding Source for a work in source code form is that 152 | same work. 153 | 154 | 2. Basic Permissions. 155 | 156 | All rights granted under this License are granted for the term of 157 | copyright on the Program, and are irrevocable provided the stated 158 | conditions are met. This License explicitly affirms your unlimited 159 | permission to run the unmodified Program. The output from running a 160 | covered work is covered by this License only if the output, given its 161 | content, constitutes a covered work. This License acknowledges your 162 | rights of fair use or other equivalent, as provided by copyright law. 163 | 164 | You may make, run and propagate covered works that you do not 165 | convey, without conditions so long as your license otherwise remains 166 | in force. You may convey covered works to others for the sole purpose 167 | of having them make modifications exclusively for you, or provide you 168 | with facilities for running those works, provided that you comply with 169 | the terms of this License in conveying all material for which you do 170 | not control copyright. Those thus making or running the covered works 171 | for you must do so exclusively on your behalf, under your direction 172 | and control, on terms that prohibit them from making any copies of 173 | your copyrighted material outside their relationship with you. 174 | 175 | Conveying under any other circumstances is permitted solely under 176 | the conditions stated below. Sublicensing is not allowed; section 10 177 | makes it unnecessary. 178 | 179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law. 180 | 181 | No covered work shall be deemed part of an effective technological 182 | measure under any applicable law fulfilling obligations under article 183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or 184 | similar laws prohibiting or restricting circumvention of such 185 | measures. 186 | 187 | When you convey a covered work, you waive any legal power to forbid 188 | circumvention of technological measures to the extent such circumvention 189 | is effected by exercising rights under this License with respect to 190 | the covered work, and you disclaim any intention to limit operation or 191 | modification of the work as a means of enforcing, against the work's 192 | users, your or third parties' legal rights to forbid circumvention of 193 | technological measures. 194 | 195 | 4. Conveying Verbatim Copies. 196 | 197 | You may convey verbatim copies of the Program's source code as you 198 | receive it, in any medium, provided that you conspicuously and 199 | appropriately publish on each copy an appropriate copyright notice; 200 | keep intact all notices stating that this License and any 201 | non-permissive terms added in accord with section 7 apply to the code; 202 | keep intact all notices of the absence of any warranty; and give all 203 | recipients a copy of this License along with the Program. 204 | 205 | You may charge any price or no price for each copy that you convey, 206 | and you may offer support or warranty protection for a fee. 207 | 208 | 5. Conveying Modified Source Versions. 209 | 210 | You may convey a work based on the Program, or the modifications to 211 | produce it from the Program, in the form of source code under the 212 | terms of section 4, provided that you also meet all of these conditions: 213 | 214 | a) The work must carry prominent notices stating that you modified 215 | it, and giving a relevant date. 216 | 217 | b) The work must carry prominent notices stating that it is 218 | released under this License and any conditions added under section 219 | 7. This requirement modifies the requirement in section 4 to 220 | "keep intact all notices". 221 | 222 | c) You must license the entire work, as a whole, under this 223 | License to anyone who comes into possession of a copy. This 224 | License will therefore apply, along with any applicable section 7 225 | additional terms, to the whole of the work, and all its parts, 226 | regardless of how they are packaged. This License gives no 227 | permission to license the work in any other way, but it does not 228 | invalidate such permission if you have separately received it. 229 | 230 | d) If the work has interactive user interfaces, each must display 231 | Appropriate Legal Notices; however, if the Program has interactive 232 | interfaces that do not display Appropriate Legal Notices, your 233 | work need not make them do so. 234 | 235 | A compilation of a covered work with other separate and independent 236 | works, which are not by their nature extensions of the covered work, 237 | and which are not combined with it such as to form a larger program, 238 | in or on a volume of a storage or distribution medium, is called an 239 | "aggregate" if the compilation and its resulting copyright are not 240 | used to limit the access or legal rights of the compilation's users 241 | beyond what the individual works permit. Inclusion of a covered work 242 | in an aggregate does not cause this License to apply to the other 243 | parts of the aggregate. 244 | 245 | 6. Conveying Non-Source Forms. 246 | 247 | You may convey a covered work in object code form under the terms 248 | of sections 4 and 5, provided that you also convey the 249 | machine-readable Corresponding Source under the terms of this License, 250 | in one of these ways: 251 | 252 | a) Convey the object code in, or embodied in, a physical product 253 | (including a physical distribution medium), accompanied by the 254 | Corresponding Source fixed on a durable physical medium 255 | customarily used for software interchange. 256 | 257 | b) Convey the object code in, or embodied in, a physical product 258 | (including a physical distribution medium), accompanied by a 259 | written offer, valid for at least three years and valid for as 260 | long as you offer spare parts or customer support for that product 261 | model, to give anyone who possesses the object code either (1) a 262 | copy of the Corresponding Source for all the software in the 263 | product that is covered by this License, on a durable physical 264 | medium customarily used for software interchange, for a price no 265 | more than your reasonable cost of physically performing this 266 | conveying of source, or (2) access to copy the 267 | Corresponding Source from a network server at no charge. 268 | 269 | c) Convey individual copies of the object code with a copy of the 270 | written offer to provide the Corresponding Source. This 271 | alternative is allowed only occasionally and noncommercially, and 272 | only if you received the object code with such an offer, in accord 273 | with subsection 6b. 274 | 275 | d) Convey the object code by offering access from a designated 276 | place (gratis or for a charge), and offer equivalent access to the 277 | Corresponding Source in the same way through the same place at no 278 | further charge. You need not require recipients to copy the 279 | Corresponding Source along with the object code. If the place to 280 | copy the object code is a network server, the Corresponding Source 281 | may be on a different server (operated by you or a third party) 282 | that supports equivalent copying facilities, provided you maintain 283 | clear directions next to the object code saying where to find the 284 | Corresponding Source. Regardless of what server hosts the 285 | Corresponding Source, you remain obligated to ensure that it is 286 | available for as long as needed to satisfy these requirements. 287 | 288 | e) Convey the object code using peer-to-peer transmission, provided 289 | you inform other peers where the object code and Corresponding 290 | Source of the work are being offered to the general public at no 291 | charge under subsection 6d. 292 | 293 | A separable portion of the object code, whose source code is excluded 294 | from the Corresponding Source as a System Library, need not be 295 | included in conveying the object code work. 296 | 297 | A "User Product" is either (1) a "consumer product", which means any 298 | tangible personal property which is normally used for personal, family, 299 | or household purposes, or (2) anything designed or sold for incorporation 300 | into a dwelling. In determining whether a product is a consumer product, 301 | doubtful cases shall be resolved in favor of coverage. For a particular 302 | product received by a particular user, "normally used" refers to a 303 | typical or common use of that class of product, regardless of the status 304 | of the particular user or of the way in which the particular user 305 | actually uses, or expects or is expected to use, the product. A product 306 | is a consumer product regardless of whether the product has substantial 307 | commercial, industrial or non-consumer uses, unless such uses represent 308 | the only significant mode of use of the product. 309 | 310 | "Installation Information" for a User Product means any methods, 311 | procedures, authorization keys, or other information required to install 312 | and execute modified versions of a covered work in that User Product from 313 | a modified version of its Corresponding Source. The information must 314 | suffice to ensure that the continued functioning of the modified object 315 | code is in no case prevented or interfered with solely because 316 | modification has been made. 317 | 318 | If you convey an object code work under this section in, or with, or 319 | specifically for use in, a User Product, and the conveying occurs as 320 | part of a transaction in which the right of possession and use of the 321 | User Product is transferred to the recipient in perpetuity or for a 322 | fixed term (regardless of how the transaction is characterized), the 323 | Corresponding Source conveyed under this section must be accompanied 324 | by the Installation Information. But this requirement does not apply 325 | if neither you nor any third party retains the ability to install 326 | modified object code on the User Product (for example, the work has 327 | been installed in ROM). 328 | 329 | The requirement to provide Installation Information does not include a 330 | requirement to continue to provide support service, warranty, or updates 331 | for a work that has been modified or installed by the recipient, or for 332 | the User Product in which it has been modified or installed. Access to a 333 | network may be denied when the modification itself materially and 334 | adversely affects the operation of the network or violates the rules and 335 | protocols for communication across the network. 336 | 337 | Corresponding Source conveyed, and Installation Information provided, 338 | in accord with this section must be in a format that is publicly 339 | documented (and with an implementation available to the public in 340 | source code form), and must require no special password or key for 341 | unpacking, reading or copying. 342 | 343 | 7. Additional Terms. 344 | 345 | "Additional permissions" are terms that supplement the terms of this 346 | License by making exceptions from one or more of its conditions. 347 | Additional permissions that are applicable to the entire Program shall 348 | be treated as though they were included in this License, to the extent 349 | that they are valid under applicable law. If additional permissions 350 | apply only to part of the Program, that part may be used separately 351 | under those permissions, but the entire Program remains governed by 352 | this License without regard to the additional permissions. 353 | 354 | When you convey a copy of a covered work, you may at your option 355 | remove any additional permissions from that copy, or from any part of 356 | it. (Additional permissions may be written to require their own 357 | removal in certain cases when you modify the work.) You may place 358 | additional permissions on material, added by you to a covered work, 359 | for which you have or can give appropriate copyright permission. 360 | 361 | Notwithstanding any other provision of this License, for material you 362 | add to a covered work, you may (if authorized by the copyright holders of 363 | that material) supplement the terms of this License with terms: 364 | 365 | a) Disclaiming warranty or limiting liability differently from the 366 | terms of sections 15 and 16 of this License; or 367 | 368 | b) Requiring preservation of specified reasonable legal notices or 369 | author attributions in that material or in the Appropriate Legal 370 | Notices displayed by works containing it; or 371 | 372 | c) Prohibiting misrepresentation of the origin of that material, or 373 | requiring that modified versions of such material be marked in 374 | reasonable ways as different from the original version; or 375 | 376 | d) Limiting the use for publicity purposes of names of licensors or 377 | authors of the material; or 378 | 379 | e) Declining to grant rights under trademark law for use of some 380 | trade names, trademarks, or service marks; or 381 | 382 | f) Requiring indemnification of licensors and authors of that 383 | material by anyone who conveys the material (or modified versions of 384 | it) with contractual assumptions of liability to the recipient, for 385 | any liability that these contractual assumptions directly impose on 386 | those licensors and authors. 387 | 388 | All other non-permissive additional terms are considered "further 389 | restrictions" within the meaning of section 10. If the Program as you 390 | received it, or any part of it, contains a notice stating that it is 391 | governed by this License along with a term that is a further 392 | restriction, you may remove that term. If a license document contains 393 | a further restriction but permits relicensing or conveying under this 394 | License, you may add to a covered work material governed by the terms 395 | of that license document, provided that the further restriction does 396 | not survive such relicensing or conveying. 397 | 398 | If you add terms to a covered work in accord with this section, you 399 | must place, in the relevant source files, a statement of the 400 | additional terms that apply to those files, or a notice indicating 401 | where to find the applicable terms. 402 | 403 | Additional terms, permissive or non-permissive, may be stated in the 404 | form of a separately written license, or stated as exceptions; 405 | the above requirements apply either way. 406 | 407 | 8. Termination. 408 | 409 | You may not propagate or modify a covered work except as expressly 410 | provided under this License. Any attempt otherwise to propagate or 411 | modify it is void, and will automatically terminate your rights under 412 | this License (including any patent licenses granted under the third 413 | paragraph of section 11). 414 | 415 | However, if you cease all violation of this License, then your 416 | license from a particular copyright holder is reinstated (a) 417 | provisionally, unless and until the copyright holder explicitly and 418 | finally terminates your license, and (b) permanently, if the copyright 419 | holder fails to notify you of the violation by some reasonable means 420 | prior to 60 days after the cessation. 421 | 422 | Moreover, your license from a particular copyright holder is 423 | reinstated permanently if the copyright holder notifies you of the 424 | violation by some reasonable means, this is the first time you have 425 | received notice of violation of this License (for any work) from that 426 | copyright holder, and you cure the violation prior to 30 days after 427 | your receipt of the notice. 428 | 429 | Termination of your rights under this section does not terminate the 430 | licenses of parties who have received copies or rights from you under 431 | this License. If your rights have been terminated and not permanently 432 | reinstated, you do not qualify to receive new licenses for the same 433 | material under section 10. 434 | 435 | 9. Acceptance Not Required for Having Copies. 436 | 437 | You are not required to accept this License in order to receive or 438 | run a copy of the Program. Ancillary propagation of a covered work 439 | occurring solely as a consequence of using peer-to-peer transmission 440 | to receive a copy likewise does not require acceptance. However, 441 | nothing other than this License grants you permission to propagate or 442 | modify any covered work. These actions infringe copyright if you do 443 | not accept this License. Therefore, by modifying or propagating a 444 | covered work, you indicate your acceptance of this License to do so. 445 | 446 | 10. Automatic Licensing of Downstream Recipients. 447 | 448 | Each time you convey a covered work, the recipient automatically 449 | receives a license from the original licensors, to run, modify and 450 | propagate that work, subject to this License. You are not responsible 451 | for enforcing compliance by third parties with this License. 452 | 453 | An "entity transaction" is a transaction transferring control of an 454 | organization, or substantially all assets of one, or subdividing an 455 | organization, or merging organizations. If propagation of a covered 456 | work results from an entity transaction, each party to that 457 | transaction who receives a copy of the work also receives whatever 458 | licenses to the work the party's predecessor in interest had or could 459 | give under the previous paragraph, plus a right to possession of the 460 | Corresponding Source of the work from the predecessor in interest, if 461 | the predecessor has it or can get it with reasonable efforts. 462 | 463 | You may not impose any further restrictions on the exercise of the 464 | rights granted or affirmed under this License. For example, you may 465 | not impose a license fee, royalty, or other charge for exercise of 466 | rights granted under this License, and you may not initiate litigation 467 | (including a cross-claim or counterclaim in a lawsuit) alleging that 468 | any patent claim is infringed by making, using, selling, offering for 469 | sale, or importing the Program or any portion of it. 470 | 471 | 11. Patents. 472 | 473 | A "contributor" is a copyright holder who authorizes use under this 474 | License of the Program or a work on which the Program is based. The 475 | work thus licensed is called the contributor's "contributor version". 476 | 477 | A contributor's "essential patent claims" are all patent claims 478 | owned or controlled by the contributor, whether already acquired or 479 | hereafter acquired, that would be infringed by some manner, permitted 480 | by this License, of making, using, or selling its contributor version, 481 | but do not include claims that would be infringed only as a 482 | consequence of further modification of the contributor version. For 483 | purposes of this definition, "control" includes the right to grant 484 | patent sublicenses in a manner consistent with the requirements of 485 | this License. 486 | 487 | Each contributor grants you a non-exclusive, worldwide, royalty-free 488 | patent license under the contributor's essential patent claims, to 489 | make, use, sell, offer for sale, import and otherwise run, modify and 490 | propagate the contents of its contributor version. 491 | 492 | In the following three paragraphs, a "patent license" is any express 493 | agreement or commitment, however denominated, not to enforce a patent 494 | (such as an express permission to practice a patent or covenant not to 495 | sue for patent infringement). To "grant" such a patent license to a 496 | party means to make such an agreement or commitment not to enforce a 497 | patent against the party. 498 | 499 | If you convey a covered work, knowingly relying on a patent license, 500 | and the Corresponding Source of the work is not available for anyone 501 | to copy, free of charge and under the terms of this License, through a 502 | publicly available network server or other readily accessible means, 503 | then you must either (1) cause the Corresponding Source to be so 504 | available, or (2) arrange to deprive yourself of the benefit of the 505 | patent license for this particular work, or (3) arrange, in a manner 506 | consistent with the requirements of this License, to extend the patent 507 | license to downstream recipients. "Knowingly relying" means you have 508 | actual knowledge that, but for the patent license, your conveying the 509 | covered work in a country, or your recipient's use of the covered work 510 | in a country, would infringe one or more identifiable patents in that 511 | country that you have reason to believe are valid. 512 | 513 | If, pursuant to or in connection with a single transaction or 514 | arrangement, you convey, or propagate by procuring conveyance of, a 515 | covered work, and grant a patent license to some of the parties 516 | receiving the covered work authorizing them to use, propagate, modify 517 | or convey a specific copy of the covered work, then the patent license 518 | you grant is automatically extended to all recipients of the covered 519 | work and works based on it. 520 | 521 | A patent license is "discriminatory" if it does not include within 522 | the scope of its coverage, prohibits the exercise of, or is 523 | conditioned on the non-exercise of one or more of the rights that are 524 | specifically granted under this License. You may not convey a covered 525 | work if you are a party to an arrangement with a third party that is 526 | in the business of distributing software, under which you make payment 527 | to the third party based on the extent of your activity of conveying 528 | the work, and under which the third party grants, to any of the 529 | parties who would receive the covered work from you, a discriminatory 530 | patent license (a) in connection with copies of the covered work 531 | conveyed by you (or copies made from those copies), or (b) primarily 532 | for and in connection with specific products or compilations that 533 | contain the covered work, unless you entered into that arrangement, 534 | or that patent license was granted, prior to 28 March 2007. 535 | 536 | Nothing in this License shall be construed as excluding or limiting 537 | any implied license or other defenses to infringement that may 538 | otherwise be available to you under applicable patent law. 539 | 540 | 12. No Surrender of Others' Freedom. 541 | 542 | If conditions are imposed on you (whether by court order, agreement or 543 | otherwise) that contradict the conditions of this License, they do not 544 | excuse you from the conditions of this License. If you cannot convey a 545 | covered work so as to satisfy simultaneously your obligations under this 546 | License and any other pertinent obligations, then as a consequence you may 547 | not convey it at all. For example, if you agree to terms that obligate you 548 | to collect a royalty for further conveying from those to whom you convey 549 | the Program, the only way you could satisfy both those terms and this 550 | License would be to refrain entirely from conveying the Program. 551 | 552 | 13. Use with the GNU Affero General Public License. 553 | 554 | Notwithstanding any other provision of this License, you have 555 | permission to link or combine any covered work with a work licensed 556 | under version 3 of the GNU Affero General Public License into a single 557 | combined work, and to convey the resulting work. The terms of this 558 | License will continue to apply to the part which is the covered work, 559 | but the special requirements of the GNU Affero General Public License, 560 | section 13, concerning interaction through a network will apply to the 561 | combination as such. 562 | 563 | 14. Revised Versions of this License. 564 | 565 | The Free Software Foundation may publish revised and/or new versions of 566 | the GNU General Public License from time to time. Such new versions will 567 | be similar in spirit to the present version, but may differ in detail to 568 | address new problems or concerns. 569 | 570 | Each version is given a distinguishing version number. If the 571 | Program specifies that a certain numbered version of the GNU General 572 | Public License "or any later version" applies to it, you have the 573 | option of following the terms and conditions either of that numbered 574 | version or of any later version published by the Free Software 575 | Foundation. If the Program does not specify a version number of the 576 | GNU General Public License, you may choose any version ever published 577 | by the Free Software Foundation. 578 | 579 | If the Program specifies that a proxy can decide which future 580 | versions of the GNU General Public License can be used, that proxy's 581 | public statement of acceptance of a version permanently authorizes you 582 | to choose that version for the Program. 583 | 584 | Later license versions may give you additional or different 585 | permissions. However, no additional obligations are imposed on any 586 | author or copyright holder as a result of your choosing to follow a 587 | later version. 588 | 589 | 15. Disclaimer of Warranty. 590 | 591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY 592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT 593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY 594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, 595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR 596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM 597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF 598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION. 599 | 600 | 16. Limitation of Liability. 601 | 602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS 604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY 605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE 606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF 607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD 608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), 609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF 610 | SUCH DAMAGES. 611 | 612 | 17. Interpretation of Sections 15 and 16. 613 | 614 | If the disclaimer of warranty and limitation of liability provided 615 | above cannot be given local legal effect according to their terms, 616 | reviewing courts shall apply local law that most closely approximates 617 | an absolute waiver of all civil liability in connection with the 618 | Program, unless a warranty or assumption of liability accompanies a 619 | copy of the Program in return for a fee. 620 | 621 | END OF TERMS AND CONDITIONS 622 | 623 | How to Apply These Terms to Your New Programs 624 | 625 | If you develop a new program, and you want it to be of the greatest 626 | possible use to the public, the best way to achieve this is to make it 627 | free software which everyone can redistribute and change under these terms. 628 | 629 | To do so, attach the following notices to the program. It is safest 630 | to attach them to the start of each source file to most effectively 631 | state the exclusion of warranty; and each file should have at least 632 | the "copyright" line and a pointer to where the full notice is found. 633 | 634 | 635 | Copyright (C) 636 | 637 | This program is free software: you can redistribute it and/or modify 638 | it under the terms of the GNU General Public License as published by 639 | the Free Software Foundation, either version 3 of the License, or 640 | (at your option) any later version. 641 | 642 | This program is distributed in the hope that it will be useful, 643 | but WITHOUT ANY WARRANTY; without even the implied warranty of 644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 645 | GNU General Public License for more details. 646 | 647 | You should have received a copy of the GNU General Public License 648 | along with this program. If not, see . 649 | 650 | Also add information on how to contact you by electronic and paper mail. 651 | 652 | If the program does terminal interaction, make it output a short 653 | notice like this when it starts in an interactive mode: 654 | 655 | Copyright (C) 656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 657 | This is free software, and you are welcome to redistribute it 658 | under certain conditions; type `show c' for details. 659 | 660 | The hypothetical commands `show w' and `show c' should show the appropriate 661 | parts of the General Public License. Of course, your program's commands 662 | might be different; for a GUI interface, you would use an "about box". 663 | 664 | You should also get your employer (if you work as a programmer) or school, 665 | if any, to sign a "copyright disclaimer" for the program, if necessary. 666 | For more information on this, and how to apply and follow the GNU GPL, see 667 | . 668 | 669 | The GNU General Public License does not permit incorporating your program 670 | into proprietary programs. If your program is a subroutine library, you 671 | may consider it more useful to permit linking proprietary applications with 672 | the library. If this is what you want to do, use the GNU Lesser General 673 | Public License instead of this License. But first, please read 674 | . 675 | --------------------------------------------------------------------------------