├── .gitignore
├── LICENSE.txt
├── README.md
├── preisach
├── __init__.py
├── plot_preisach_widget.py
├── preisach_python.py
└── weights.py
├── pyproject.toml
└── setup.py
/.gitignore:
--------------------------------------------------------------------------------
1 | # Python
2 | *.egg-info/
3 | *.pyc
4 | MANIFEST
5 | build/
6 | dist/
7 |
8 | # Environments
9 | venv/
10 |
--------------------------------------------------------------------------------
/LICENSE.txt:
--------------------------------------------------------------------------------
1 | MIT License
2 |
3 | Copyright (c) 2023 Isaac Kramer
4 |
5 | Permission is hereby granted, free of charge, to any person obtaining a copy
6 | of this software and associated documentation files (the "Software"), to deal
7 | in the Software without restriction, including without limitation the rights
8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9 | copies of the Software, and to permit persons to whom the Software is
10 | furnished to do so, subject to the following conditions:
11 |
12 | The above copyright notice and this permission notice shall be included in all
13 | copies or substantial portions of the Software.
14 |
15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21 | SOFTWARE.
22 |
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # Python implementation of the Preisach model of hysteresis
2 |
3 | This GitHub repository contains code that can be used to execute the Preisach model of hysteresis. The interactive notebooks featured here were produced for the published article [Hysteresis in soil hydraulic conductivity as driven by salinity and sodicity – a modeling framework](https://hess.copernicus.org/articles/25/1993/2021/).
4 | The corresponding GitHub repository for that project can be found [here](https://github.com/isaackramer/soil-hysteresis).
5 |
6 | This repository contains:
7 |
8 | * Widgets designed to give users an intuitive sense of how the Preisach framework works.
9 | * Basic implementation of the Preisach framework using Python.
10 |
11 | ## Widgets
12 |
13 | ##### 1. Geometric Intepretation of the Preisach Framework
14 |
15 | This widget demonstrates how hysterons, the core of the Preisach framework, are used to model hysteresis. To run the widget, click the Launch Binder. Wait for the notebook to load (this can take several minutes) and then click Cell → Run All.
16 |
17 | [](https://mybinder.org/v2/gh/yairmau/hysteresis-python/master?filepath=Hysteron%20Widget%20Vertical%20Version.ipynb)
18 |
19 |
20 | ##### 2. The Weight Function
21 |
22 | In this widget we demonstrate how weight functions affect the system's output. With this widget, the user can compare different weight functions, including how each affects output. To run the widget, click the Launch Binder. Wait for the notebook to load (this can take several minutes) and then click Cell → Run All.
23 |
24 | [](https://mybinder.org/v2/gh/yairmau/hysteresis-python/master?filepath=Weights%20Widget.ipynb)
25 |
26 |
27 |
--------------------------------------------------------------------------------
/preisach/__init__.py:
--------------------------------------------------------------------------------
1 | """
2 | Python implementation of the Preisach model of hysteresis
3 | """
4 |
5 | __version__ = "0.1.0"
6 |
--------------------------------------------------------------------------------
/preisach/plot_preisach_widget.py:
--------------------------------------------------------------------------------
1 | """One input widget"""
2 |
3 | import matplotlib.gridspec as gridspec
4 | import matplotlib.pyplot as plt
5 | import numpy as np
6 |
7 | from matplotlib.widgets import Slider, Button
8 | from palettable.colorbrewer.sequential import YlGnBu_9
9 |
10 | from preisach.preisach_python import preisach_single_value
11 | from preisach.weights import weights
12 |
13 |
14 | # number of hysterons on each side of the triangle
15 | hys_per_side = 101
16 |
17 | # create meshgrid with location of hysterons
18 | beta_values = np.around(np.linspace(0, 1, hys_per_side), 2)
19 | alpha_values = np.around(np.linspace(1, 0, hys_per_side), 2)
20 | beta_grid, alpha_grid = np.meshgrid(beta_values, alpha_values)
21 |
22 | # create array showing whether hysterons on/off
23 | # inital values: all hysterons set to 0 (negative saturation) and
24 | # values outside of preisach triangle set to np.nan
25 | preisach_triangle = np.where(alpha_grid >= beta_grid, 0, np.nan)
26 |
27 | # assign weights: "uniform", "linear", "bottom_heavy", "top_heavy",
28 | # "left_heavy", "right_heavy" "center_light_alpha", "center_light_beta",
29 | # "center_heavy_alpha", "center_heavy_beta"
30 | mu = weights("irreversible", beta_grid, alpha_grid)
31 | mass = np.nansum(mu)
32 | mu = mu / mass
33 |
34 |
35 | # initial state of system
36 | initial_input = 0
37 | inputs = np.array([initial_input])
38 | outputs = np.array([np.nansum(preisach_triangle)])
39 |
40 |
41 | # Begin plotting
42 | plt.ion()
43 | plt.clf()
44 |
45 | fig = plt.figure(1)
46 | gs = gridspec.GridSpec(2, 2, width_ratios=[2, 1], height_ratios=[1, 1])
47 | gs.update(left=0.1, right=0.95, bottom=0.25, top=0.9, wspace=0.3)
48 |
49 |
50 | ax1 = plt.subplot(gs[:, 0]) # Input/output
51 | ax2 = plt.subplot(gs[0, 1]) # Preisach plane
52 | ax3 = plt.subplot(gs[1, 1]) # Weights
53 |
54 | (plot1,) = ax1.plot(inputs[0], 1 - outputs[0], color="red")
55 | plot2 = ax2.pcolormesh(beta_grid, alpha_grid, preisach_triangle, cmap=YlGnBu_9.mpl_colormap)
56 | plot3 = ax3.scatter(beta_grid, alpha_grid, c=mu, cmap=YlGnBu_9.mpl_colormap, s=0.2)
57 |
58 |
59 | # axis limits
60 | ax1.set_xlim([-0.05, 1.05])
61 | ax1.set_ylim([-0.05, 1.05])
62 | ax2.set_xlim([-0.05, 1.05])
63 | ax2.set_ylim([-0.05, 1.05])
64 |
65 | # add slider (rect = [left, bottom, width, height])
66 | axcolor = "lightgoldenrodyellow"
67 | axinputs = plt.axes([0.25, 0.1, 0.65, 0.03], facecolor=axcolor)
68 | sinputs = Slider(axinputs, "input", valmin=0, valmax=1, valinit=0.0)
69 |
70 | # function to update plots based on slider input
71 | def update(val):
72 | global inputs, outputs, preisach_triangle
73 | inputs = np.concatenate((inputs, np.array([sinputs.val])))
74 | outputs, preisach_triangle = preisach_single_value(
75 | inputs, alpha_grid, beta_grid, mu, preisach_triangle, outputs
76 | )
77 | plot1.set_ydata(outputs)
78 | plot1.set_xdata(inputs)
79 | ax2.pcolormesh(beta_grid, alpha_grid, preisach_triangle)
80 | fig.canvas.draw_idle()
81 |
82 |
83 | # for the slider to remain responsive you must maintain a reference to it.
84 | # Call on_changed() to connect to the slider event.
85 | sinputs.on_changed(update)
86 |
--------------------------------------------------------------------------------
/preisach/preisach_python.py:
--------------------------------------------------------------------------------
1 | """Functions used for calculating preisach output based on given input"""
2 |
3 | import numpy as np
4 |
5 |
6 | def preisach_single_value(
7 | inputs, alpha_grid, beta_grid, mu, preisach_triangle, outputs
8 | ):
9 | """Preisach function with single input"""
10 |
11 | # compare new input to previous input value and change hysteron values accordingly
12 | if inputs[-1] > inputs[-2]: # if input increases
13 | preisach_triangle = np.where(inputs[-1] > alpha_grid, 1, preisach_triangle)
14 | elif inputs[-1] < inputs[-2]: # if input increases
15 | preisach_triangle = np.where(inputs[-1] < beta_grid, 0, preisach_triangle)
16 |
17 | # values outside the presiach half-plane are set to nan
18 | preisach_triangle = np.where(alpha_grid >= beta_grid, preisach_triangle, np.nan)
19 |
20 | # calculate weighted presiach triangle
21 | weighted_preisach = preisach_triangle * mu
22 |
23 | # new output value
24 | f = np.nansum(weighted_preisach)
25 | outputs = np.concatenate((outputs, np.array([f])))
26 | return outputs, preisach_triangle
27 |
28 |
29 | def preisach_array(inputs, alpha_grid, beta_grid, mu, starting_value):
30 | """Preisach function for array of input values"""
31 |
32 | preisach_triangle = np.where(alpha_grid >= beta_grid, starting_value, np.nan)
33 | outputs = np.array([np.nansum(preisach_triangle * mu)])
34 |
35 | for ii in range(len(inputs) - 1):
36 | new_input = inputs[ii + 1]
37 | old_input = inputs[ii]
38 |
39 | if new_input > old_input: # if input increases
40 | preisach_triangle = np.where(new_input > alpha_grid, 1, preisach_triangle)
41 | elif new_input < old_input: # if input increases
42 | preisach_triangle = np.where(new_input < beta_grid, 0, preisach_triangle)
43 |
44 | preisach_triangle = np.where(alpha_grid >= beta_grid, preisach_triangle, np.nan)
45 | weighted_preisach = preisach_triangle * mu
46 |
47 | f = np.nansum(weighted_preisach)
48 | outputs = np.concatenate((outputs, np.array([f])))
49 |
50 | return outputs, preisach_triangle
51 |
--------------------------------------------------------------------------------
/preisach/weights.py:
--------------------------------------------------------------------------------
1 | """function for creating different weight functions"""
2 | import numpy as np
3 |
4 | from numpy import where, nan, nansum
5 |
6 |
7 | def weights(method, beta, alpha):
8 | distance = (alpha - beta) / np.sqrt(2)
9 | mu = {
10 | "uniform": where(alpha >= beta, 1, nan),
11 | "linear": where(alpha == beta, 1, nan),
12 | "top_heavy": where(alpha >= beta, alpha, nan),
13 | "bottom_heavy": where(alpha >= beta, 1 - alpha, nan),
14 | "right_heavy": where(alpha >= beta, beta, nan),
15 | "left_heavy": where(alpha >= beta, 1 - beta, nan),
16 | "center_light_alpha": where(alpha >= beta, np.abs(0.5 - alpha), nan),
17 | "center_light_beta": where(alpha >= beta, np.abs(0.5 - beta), nan),
18 | "single_line": where(np.logical_and(0.3 < beta, beta < 0.5), 1, 0),
19 | "upper_left": where(np.logical_and(0.6 > beta, alpha > 0.90), 1, 0),
20 | "near_diagonal": where((alpha - beta) < 0.2, 1, 0),
21 | "far_diagonal": where((alpha - beta) < 0.5, 0, 1),
22 | "dirac_detal": where(np.logical_and(0.5 == beta, alpha == 0.5), 1, 0),
23 | "irreversible": where(alpha >= beta, distance, 0),
24 | "reversible": where(alpha >= beta, (1 - distance) ** 4, 0),
25 | "set_1": where(alpha >= beta, (1 - distance), nan),
26 | "set_2": where(alpha >= beta, (1 - distance) ** 2, nan),
27 | "set_3": where(alpha >= beta, (1 - distance) ** 4, nan),
28 | "mcneal": where(
29 | np.logical_and(
30 | np.logical_or(0.3 > beta, 0.8 < beta),
31 | alpha > 0.8
32 | ),
33 | 1,
34 | 0
35 | ),
36 | }[method]
37 | mu = where(alpha >= beta, mu, nan)
38 | mass = nansum(mu)
39 | mu = mu / mass
40 | return mu
41 |
--------------------------------------------------------------------------------
/pyproject.toml:
--------------------------------------------------------------------------------
1 | [project]
2 | name = "preisach"
3 | dynamic = ["version"]
4 | authors = [
5 | { name="Isaac Kramer", email="43068145+isaackramer@users.noreply.github.com" },
6 | { name="Peter Hillerström", email="peter.hillerstrom@gmail.com" },
7 | ]
8 | description = "Python implementation of the Preisach model of hysteresis"
9 | readme = "README.md"
10 | keywords = [
11 | "hysteresis",
12 | ]
13 | license.text = "MIT License"
14 | classifiers = [
15 | "License :: OSI Approved :: MIT License",
16 | "Programming Language :: Python :: 3",
17 | "Topic :: Scientific/Engineering :: Physics",
18 | ]
19 | requires-python = ">=3.7"
20 | dependencies = [
21 | "numpy >= 1.23.5",
22 | "palettable >= 3.3.0",
23 | ]
24 |
25 | [project.optional-dependencies]
26 | dev = [
27 | "black >= 22.1.0",
28 | "flake8 >= 6.0.0",
29 | "pycodestyle >= 2.10.0",
30 | "pylint >= 2.15.10",
31 | ]
32 | notebook = [
33 | "jupyter ~= 1.0.0",
34 | ]
35 | plot = [
36 | "matplotlib ~= 3.4.3",
37 | ]
38 |
39 | # [project.gui-scripts]
40 | # preisach-widget = preisach.plot_preisach_widget:main [plot]
41 |
42 | [project.urls]
43 | "Source code" = "https://github.com/isaackramer/python-preisach"
44 | "Issue tracker" = "https://github.com/isaackramer/python-preisach/issues"
45 |
46 | [tool.setuptools]
47 | packages = ["preisach"]
48 |
49 | [tool.setuptools.dynamic]
50 | version.attr = "preisach.__version__"
51 |
52 | [build-system]
53 | requires = ["setuptools", "setuptools-scm"]
54 | build-backend = "setuptools.build_meta"
55 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup
2 |
3 | setup()
4 |
--------------------------------------------------------------------------------