├── .gitignore
├── .readthedocs.yaml
├── LICENSE
├── PyIT2FLS_icon.png
├── README.md
├── article examples
├── cartPole.mp4
├── example1.py
├── example2.py
├── example3.py
└── example4.py
├── docs
├── Makefile
├── _generated
│ └── pyit2fls.rst
├── _static
│ ├── Figure_1.png
│ ├── Figure_10.png
│ ├── Figure_11.png
│ ├── Figure_12.png
│ ├── Figure_13.png
│ ├── Figure_14.png
│ ├── Figure_15.png
│ ├── Figure_16.png
│ ├── Figure_17.png
│ ├── Figure_18.png
│ ├── Figure_19.png
│ ├── Figure_2.png
│ ├── Figure_20.png
│ ├── Figure_21.png
│ ├── Figure_22.png
│ ├── Figure_23.png
│ ├── Figure_24.png
│ ├── Figure_3.png
│ ├── Figure_4.png
│ ├── Figure_5.png
│ ├── Figure_6.png
│ ├── Figure_7.png
│ ├── Figure_8.png
│ └── Figure_9.png
├── algorithms.rst
├── classes.rst
├── conf.py
├── functions.rst
├── index.html
├── index.rst
├── it2fs.rst
├── make.bat
├── matrices.rst
├── membershipfunctions.rst
├── requirements.txt
└── t_s_norms.rst
├── examples
├── PyIT2FLSPSO.py
├── Sphinx docs examples
│ ├── Ex1.py
│ ├── Ex2.py
│ ├── Ex3.py
│ ├── Ex4.py
│ ├── Ex5.py
│ ├── Ex6.py
│ ├── Ex7.py
│ ├── Ex8.py
│ └── Ex9.py
├── ddeintlib.py
├── ex_1.py
├── ex_10.py
├── ex_11.py
├── ex_12.py
├── ex_13.py
├── ex_14.py
├── ex_15.py
├── ex_16.py
├── ex_17.py
├── ex_18.py
├── ex_19.py
├── ex_2.py
├── ex_20.py
├── ex_21.py
├── ex_22.py
├── ex_23.py
├── ex_24.py
├── ex_3.py
├── ex_4.py
├── ex_5.py
├── ex_6.py
├── ex_7.py
├── ex_8.py
├── ex_9.py
└── images
│ ├── 10_1.png
│ ├── 10_2.png
│ ├── 10_3.png
│ ├── 10_4.png
│ ├── 10_5.png
│ ├── 10_6.png
│ ├── 11_1.png
│ ├── 11_2.png
│ ├── 12_1.png
│ ├── 12_2.png
│ ├── 12_3.png
│ ├── 13_1.png
│ ├── 13_2.png
│ ├── 13_3.png
│ ├── 13_4.png
│ ├── 13_5.png
│ ├── 13_6.png
│ ├── 14_1.png
│ ├── 14_2.png
│ ├── 14_3.png
│ ├── 14_4.png
│ ├── 14_5.png
│ ├── 15_1.png
│ ├── 15_2.png
│ ├── 18_1.png
│ ├── 18_2.png
│ ├── 18_3.png
│ ├── 18_4.png
│ ├── 18_5.png
│ ├── 18_6.png
│ ├── 18_7.png
│ ├── 19_1.png
│ ├── 19_2.png
│ ├── 19_3.png
│ ├── 19_4.png
│ ├── 19_5.png
│ ├── 19_6.png
│ ├── 19_7.png
│ ├── 1_1.png
│ ├── 20_3.png
│ ├── 21_3.png
│ ├── 22_1.png
│ ├── 23_1.png
│ ├── 24_1.png
│ ├── 24_2.png
│ ├── 24_3.png
│ ├── 2_1.png
│ ├── 2_2.png
│ ├── 2_3.png
│ ├── 3_1.png
│ ├── 3_2.png
│ ├── 3_3.png
│ ├── 3_4.png
│ ├── 3_5.png
│ ├── 4_2.png
│ ├── 4_4.png
│ ├── 5_1.png
│ ├── 5_2.png
│ ├── 5_3.png
│ ├── 5_4.png
│ ├── 5_block.jpg
│ ├── 6_1.png
│ ├── 6_2.png
│ ├── 6_3.png
│ ├── 6_4.png
│ ├── 6_5.png
│ ├── 6_6.png
│ ├── 6_7.png
│ ├── 6_8.png
│ ├── 8_1.png
│ ├── 8_2.png
│ ├── 8_3.png
│ ├── 8_4.png
│ ├── 9_1.png
│ ├── 9_2.png
│ ├── 9_3.png
│ ├── 9_4.png
│ ├── 9_5.png
│ ├── 9_6.png
│ ├── IT2TSKFLSY1.png
│ └── IT2TSKFLSY2.png
├── markdown docs
├── MIT2FLS.md
├── MT1FLS.md
├── README.md
├── T1FSOp.md
├── TSKIT2FLS.md
├── TSKT1FLS.md
├── Xnorm.md
├── _config.yml
├── defIT2FS.md
├── defT1FS.md
├── defXnorm.md
├── evalMethods.md
├── examples.md
├── images
│ ├── 1.1._.png
│ ├── 1.1.png
│ ├── 1.2._.png
│ ├── 1.2.png
│ ├── 1.3._.png
│ ├── 1.3.png
│ ├── 2.1._.png
│ ├── 2.1.png
│ ├── 2.2._.png
│ ├── 2.2.png
│ ├── 2.3._.png
│ ├── 2.3.png
│ ├── 3.1.png
│ ├── 3.2.png
│ ├── 3.3.png
│ ├── 3.4.png
│ ├── InvPenCon.png
│ ├── InvPenSets.png
│ └── InvPenSt.png
├── index.md
├── meetjoin.md
├── overview.md
└── typereduction.md
├── pyit2fls
├── __init__.py
├── fuzzymatrix.py
├── learning.py
└── pyit2fls.py
├── setup.py
└── typereduction
├── MANIFEST
├── MANIFEST.in
├── README.md
├── examples
└── ex_1.py
├── setup.py
└── typereduction
├── __init__.py
├── makefile
├── typereduction.c
└── typereduction.py
/.gitignore:
--------------------------------------------------------------------------------
1 | .pypirc
2 | __pycache__
3 | dist
4 | build
5 | typereduction.egg-info
6 | pyit2fls.egg-info
7 | *.pdf
8 | *.sh
--------------------------------------------------------------------------------
/.readthedocs.yaml:
--------------------------------------------------------------------------------
1 | # Read the Docs configuration file for Sphinx projects
2 | # See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
3 |
4 | # Required
5 | version: 2
6 |
7 | # Set the OS, Python version and other tools you might need
8 | build:
9 | os: ubuntu-20.04
10 | tools:
11 | python: "3.8"
12 | # You can also specify other tool versions:
13 | # nodejs: "20"
14 | # rust: "1.70"
15 | # golang: "1.20"
16 |
17 | # Build documentation in the "docs/" directory with Sphinx
18 | sphinx:
19 | configuration: docs/conf.py
20 | # You can configure Sphinx to use a different builder, for instance use the dirhtml builder for simpler URLs
21 | # builder: "dirhtml"
22 | # Fail on all warnings to avoid broken references
23 | # fail_on_warning: true
24 |
25 | # Optionally build your docs in additional formats such as PDF and ePub
26 | # formats:
27 | # - pdf
28 | # - epub
29 |
30 | # Optional but recommended, declare the Python requirements required
31 | # to build your documentation
32 | # See https://docs.readthedocs.io/en/stable/guides/reproducible-builds.html
33 | python:
34 | install:
35 | - requirements: docs/requirements.txt
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | Copyright (c) 2020 Amir Arslan Haghrah
2 |
3 | Permission is hereby granted, free of charge, to any person obtaining a copy
4 | of this software and associated documentation files (the "Software"), to deal
5 | in the Software without restriction, including without limitation the rights
6 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
7 | copies of the Software, and to permit persons to whom the Software is
8 | furnished to do so, subject to the following conditions:
9 |
10 | The above copyright notice and this permission notice shall be included in all
11 | copies or substantial portions of the Software.
12 |
13 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
16 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
17 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
18 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
19 | SOFTWARE.
20 |
--------------------------------------------------------------------------------
/PyIT2FLS_icon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/PyIT2FLS_icon.png
--------------------------------------------------------------------------------
/article examples/cartPole.mp4:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/article examples/cartPole.mp4
--------------------------------------------------------------------------------
/article examples/example1.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Sun Dec 15 17:11:43 2024
5 |
6 | @author: arslan
7 | """
8 |
9 | from pyit2fls import (T1FS, trapezoid_mf, T1FS_plot,
10 | min_t_norm, product_t_norm, T1FS_AND,
11 | max_s_norm, probabilistic_sum_s_norm, T1FS_OR,
12 | IT2FS_RGaussian_UncertStd,
13 | IT2FS_LGaussian_UncertStd, IT2FS_plot,
14 | MEET, JOIN)
15 | from numpy import (linspace, )
16 | import matplotlib.pyplot as plt
17 |
18 | domain = linspace(-1.0, 1.0, 2001)
19 | set1 = T1FS(domain, trapezoid_mf, [-0.75, -0.25, 0.25, 0.75, 1.])
20 | set2 = -set1
21 |
22 | T1FS_plot(set1, set2, legends=["[T1FS1]", "[NOT T1FS1]", ], filename="../images/figure1_1")
23 |
24 | set3 = T1FS_AND(domain, set1, set2, min_t_norm)
25 | set4 = T1FS_AND(domain, set1, set2, product_t_norm)
26 | T1FS_plot(set3, set4, legends=["[T1FS1] AND [NOT T1FS1] (minimum t-norm)",
27 | "[T1FS1] AND [NOT T1FS1] (product t-norm)", ],
28 | filename="../images/figure1_2")
29 |
30 | set5 = T1FS_OR(domain, set1, set2, max_s_norm)
31 | set6 = T1FS_OR(domain, set1, set2, probabilistic_sum_s_norm)
32 | T1FS_plot(set5, set6, legends=["[T1FS1] OR [NOT T1FS1] (maximum s-norm)",
33 | "[T1FS1] OR [NOT T1FS1] (probabilistic sum s-norm)", ],
34 | filename="../images/figure1_3")
35 |
36 |
37 | domain = linspace(1, 2, 1001)
38 |
39 | it2fs1 = IT2FS_RGaussian_UncertStd(domain, [1.25, 0.2, 0.05, 0.6])
40 | it2fs2 = IT2FS_LGaussian_UncertStd(domain, [1.75, 0.2, 0.05, 0.6])
41 | it2fs3 = -it2fs1
42 | it2fs4 = -it2fs2
43 |
44 | it2fs5 = MEET(domain, min_t_norm, it2fs1, it2fs2, it2fs3, it2fs4)
45 | it2fs6 = JOIN(domain, max_s_norm, it2fs1, it2fs2, it2fs3, it2fs4)
46 |
47 | IT2FS_plot(it2fs1, it2fs2, it2fs3, it2fs4,
48 | legends=["[IT2FS1]",
49 | "[IT2FS2]",
50 | "[NOT IT2FS1]",
51 | "[NOT IT2FS2]", ],
52 | legendloc="upper right",
53 | filename="../images/figure3_1", ext="pdf")
54 | plt.tight_layout()
55 |
56 |
57 | IT2FS_plot(it2fs5, it2fs6,
58 | legends=["MEET of the all four sets",
59 | "JOIN of the all four sets", ],
60 | filename="../images/figure3_2", ext="pdf")
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
--------------------------------------------------------------------------------
/article examples/example3.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Sun Dec 15 17:11:43 2024
5 |
6 | @author: arslan
7 | """
8 |
9 | from numpy import (linspace, array, vstack, )
10 | from numpy.random import (random, )
11 | import matplotlib.pyplot as plt
12 | from pyit2fls import (IT2TSK_ML, T1TSK_ML, IT2FS_Gaussian_UncertMean, )
13 |
14 | def mackey_glass(tav, n, beta, gamma, step):
15 | x = [random() for i in range(tav)]
16 | for i in range(step):
17 | x.append(x[-1] + beta * x[-tav] / (1 + x[-tav] ** n) - gamma * x[-1])
18 | return array(x[tav:])
19 |
20 | mg = mackey_glass(2, 9.65, 2., 1., 1000)
21 |
22 | domain = linspace(0., 1.5, 15)
23 | H = 3
24 | L = 100 # Training and test data length
25 | S = 200 # Starting index of training and test data in Mackey-Glass time series
26 | X_train = vstack([mg[S - h - 1:S + L - h - 1] for h in range(H)]).T
27 | X_test = vstack([mg[S + L - h - 1:S + 2 * L - h - 1] for h in range(H)]).T
28 | y_train_actual = mg[S:S + L]
29 | y_test_actual = mg[S + L:S + 2 * L]
30 | for i in range(S, S + L):
31 | X_train[i - S, :] = array(mg[i - H :i])
32 | X_test[i - S, :] = array(mg[i + L - H:i + L])
33 |
34 | N = 3
35 | M = 9
36 | myIT2TSK = IT2TSK_ML(N, M, IT2FS_Gaussian_UncertMean, (-2., 2.),
37 | algorithm="GA",
38 | algorithm_params=[50, 200, 400, 20, 0.04])
39 | myIT2TSK.fit(X_train, y_train_actual)
40 | y_train_prediction = myIT2TSK.score(X_train)
41 | y_test_prediction = myIT2TSK.score(X_test)
42 |
43 | learning_indices = linspace(S, S + L - 1, L)
44 | test_indices = linspace(S + L, S + 2 * L - 1, L)
45 |
46 | plt.figure(figsize=(12, 5), )
47 | plt.plot(learning_indices, y_train_actual, label="Actual Training Values", linestyle="-", )
48 | plt.plot(learning_indices, y_train_prediction, label="Model Fit (Training)", linestyle="--", )
49 | plt.plot(test_indices, y_test_actual, label="Actual Test Values", linestyle=":", )
50 | plt.plot(test_indices, y_test_prediction, label="Model Forecast (Test)", linestyle="-.", )
51 | plt.xticks([S + 10 * i for i in range(21)])
52 | plt.title("Mackey-Glass Chaotic Time Series\n" + r"$\gamma$=1, $\beta$=2, $\tau$=2, and $n$=9.65")
53 | plt.legend(loc="upper left", bbox_to_anchor=(1., 1.02))
54 | plt.grid(which="major", linestyle="-", linewidth=0.75, color="gray", alpha=0.7)
55 | plt.minorticks_on()
56 | plt.grid(which="minor", linestyle=":", linewidth=0.5, color="lightgray", alpha=0.7)
57 | plt.savefig("../images/mackey_glass_1.pdf", format="pdf", dpi=600, bbox_inches="tight")
58 | plt.show()
59 |
60 |
61 | myTSK = T1TSK_ML(N, M, (-4., 4.), algorithm="PSO",
62 | algorithm_params=[200, 200, 0.3, 0.3, 1.8])
63 | myTSK.fit(X_train, y_train_actual)
64 | y_train_prediction = myTSK.score(X_train)
65 | y_test_prediction = myTSK.score(X_test)
66 |
67 | plt.figure(figsize=(12, 5), )
68 | plt.plot(learning_indices, y_train_actual, label="Actual Training Values", linestyle="-", )
69 | plt.plot(learning_indices, y_train_prediction, label="Model Fit (Training)", linestyle="--", )
70 | plt.plot(test_indices, y_test_actual, label="Actual Test Values", linestyle=":", )
71 | plt.plot(test_indices, y_test_prediction, label="Model Forecast (Test)", linestyle="-.", )
72 | plt.xticks([S + 10 * i for i in range(21)])
73 | plt.title("Mackey-Glass Chaotic Time Series\n" + r"$\gamma$=1, $\beta$=2, $\tau$=2, and $n$=9.65")
74 | plt.legend(loc="upper left", bbox_to_anchor=(1., 1.02))
75 | plt.grid(which="major", linestyle="-", linewidth=0.75, color="gray", alpha=0.7)
76 | plt.minorticks_on()
77 | plt.grid(which="minor", linestyle=":", linewidth=0.5, color="lightgray", alpha=0.7)
78 | plt.savefig("../images/mackey_glass_2.pdf", format="pdf", dpi=600, bbox_inches="tight")
79 | plt.show()
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
--------------------------------------------------------------------------------
/article examples/example4.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Sun Dec 15 17:11:44 2024
5 |
6 | @author: arslan
7 | """
8 |
9 | from pyit2fls import (IT2Mamdani_ML, IT2FS_Gaussian_UncertMean,
10 | Optimizer, )
11 | from numpy import (linspace, array, pi, sin, argmin, argmax, exp,
12 | cos, meshgrid, zeros_like, sum, zeros, empty, )
13 | from numpy.random import (rand, uniform, randint, )
14 | import matplotlib.pyplot as plt
15 |
16 |
17 | class HSO(Optimizer):
18 | def __init__(self, population_size, solution_size, objective_function, bounds, args=None):
19 | super().__init__(population_size, solution_size, objective_function, bounds, args)
20 |
21 | # Initialize Harmony Memory (HM) randomly
22 | self.hm = uniform(low=self.bounds[0], high=self.bounds[1], size=(self.population_size, self.solution_size))
23 | self.hm_fitness = []
24 | for harmony in self.hm:
25 | try:
26 | self.hm_fitness.append(self.objective_function(harmony, *self.args))
27 | except:
28 | self.hm_fitness.append(float("inf"))
29 | self.hm_fitness = array(self.hm_fitness)
30 |
31 | best_index = argmin(self.hm_fitness)
32 | self.best_solution = self.hm[best_index]
33 | self.best_fitness = self.hm_fitness[best_index]
34 |
35 | def iterate(self, algorithm_params): # hmcr=0.9, par=0.3, bw=0.01
36 | new_harmony = zeros(self.solution_size)
37 |
38 | for i in range(self.solution_size):
39 | if rand() < algorithm_params[2]:
40 | # Memory consideration
41 | new_harmony[i] = self.hm[randint(0, self.population_size), i]
42 | if rand() < algorithm_params[3]:
43 | # Pitch adjustment
44 | new_harmony[i] += uniform(-algorithm_params[4], algorithm_params[4])
45 | else:
46 | # Random selection
47 | new_harmony[i] = uniform(self.bounds[0], self.bounds[1])
48 | try:
49 | new_fitness = self.objective_function(new_harmony, *self.args)
50 | except:
51 | new_fitness = float("inf")
52 |
53 | # Update Harmony Memory
54 | worst_index = argmax(self.hm_fitness)
55 | if new_fitness < self.hm_fitness[worst_index]:
56 | self.hm[worst_index] = new_harmony
57 | self.hm_fitness[worst_index] = new_fitness
58 |
59 | best_index = argmin(self.hm_fitness)
60 | self.best_solution = self.hm[best_index]
61 | self.best_fitness = self.hm_fitness[best_index]
62 |
63 | return self.best_fitness
64 |
65 |
66 |
67 | X1 = linspace(-pi, pi, 10)
68 | X2 = linspace(-pi, pi, 10)
69 |
70 | X = []
71 | y = []
72 | noise = 1.0 * (rand(len(X1), len(X2)) - 0.5)
73 | for i, x1 in zip(range(len(X1)), X1):
74 | for j, x2 in zip(range(len(X2)), X2):
75 | X.append([x1, x2])
76 | y.append(sin(x1) + cos(x2) + noise[i, j])
77 | X = array(X)
78 |
79 | N = 2
80 | M = 4
81 | myIT2Mamdani = IT2Mamdani_ML(N, M, IT2FS_Gaussian_UncertMean, (-pi, pi),
82 | algorithm=HSO,
83 | algorithm_params=[2, 5000, 0.95, 0.9, 0.05])
84 | err, conv = myIT2Mamdani.fit(X, y)
85 |
86 | x1, x2 = meshgrid(X1, X2)
87 | y1 = sin(x1) + cos(x2) + noise
88 | y2 = zeros_like(y1)
89 | for i in range(10):
90 | for j in range(10):
91 | y2[i, j] = myIT2Mamdani.score(array([X1[j], X2[i], ]))
92 |
93 | y3 = sin(x1) + cos(x2)
94 |
95 | print(f"Fitting error with respect to original surface: {sum((y2-y3) ** 2) ** 0.5}")
96 | print(f"Fitting error with respect to noisy surface: {sum((y2-y1) ** 2) ** 0.5}")
97 |
98 |
99 | plt.figure(figsize=(8, 5))
100 | plt.plot(conv, label="HSO Algorithm")
101 | plt.legend()
102 | plt.title("Convergence Diagram")
103 | plt.grid(which="major", linestyle="-", linewidth=0.75, color="gray", alpha=0.7)
104 | plt.minorticks_on()
105 | plt.grid(which="minor", linestyle=":", linewidth=0.5, color="lightgray", alpha=0.7)
106 | plt.xlabel("Iteration")
107 | plt.ylabel("Objective function")
108 | plt.savefig("../images/example4_conv.pdf", format="pdf", dpi=600, bbox_inches="tight")
109 | plt.show()
110 |
111 | fig = plt.figure(figsize=(6, 4))
112 | ax = fig.add_subplot(111, projection='3d')
113 | original = ax.plot_surface(x1, x2, y3, cmap="Blues",
114 | vmin=y1.min(), vmax=y1.max())
115 | fig.colorbar(original, ax=ax, shrink=0.5, aspect=10,
116 | label="Original Surface")
117 | ax.view_init(elev=10, azim=-60)
118 | ax.set_xlabel(r"$x_{1}$")
119 | ax.set_ylabel(r"$x_{2}$")
120 |
121 | plt.tight_layout()
122 | plt.savefig("example4_1.pdf", format="pdf",
123 | dpi=600, bbox_inches="tight")
124 | plt.show()
125 |
126 |
127 | fig = plt.figure(figsize=(6, 4))
128 | ax = fig.add_subplot(111, projection='3d')
129 | fitted = ax.plot_surface(x1, x2, y1, cmap="Blues",
130 | vmin=y1.min(), vmax=y1.max())
131 | fig.colorbar(fitted, ax=ax, shrink=0.5, aspect=10,
132 | label="Noisy Surface")
133 | ax.view_init(elev=10, azim=-60)
134 | ax.set_xlabel(r"$x_{1}$")
135 | ax.set_ylabel(r"$x_{2}$")
136 |
137 | plt.tight_layout()
138 | plt.savefig("example4_2.pdf", format="pdf",
139 | dpi=600, bbox_inches="tight")
140 | plt.show()
141 |
142 |
143 | fig = plt.figure(figsize=(6, 4))
144 | ax = fig.add_subplot(111, projection='3d')
145 | error_surface = ax.plot_surface(x1, x2, abs(y2 - y3),
146 | cmap="Greens", alpha=0.8)
147 | fig.colorbar(error_surface, ax=ax, shrink=0.5, aspect=10,
148 | label="Error Surface")
149 | ax.plot_surface(x1, x2, y2, cmap="Blues", alpha=0.7)
150 | ax.view_init(elev=10, azim=-60)
151 | ax.set_xlabel(r"$x_{1}$")
152 | ax.set_ylabel(r"$x_{2}$")
153 |
154 | plt.tight_layout()
155 | plt.savefig("example4_3.pdf", format="pdf",
156 | dpi=600, bbox_inches="tight")
157 | plt.show()
158 |
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 |
174 |
175 |
176 |
177 |
178 |
179 |
--------------------------------------------------------------------------------
/docs/Makefile:
--------------------------------------------------------------------------------
1 | # Minimal makefile for Sphinx documentation
2 | #
3 |
4 | # You can set these variables from the command line, and also
5 | # from the environment for the first two.
6 | SPHINXOPTS ?=
7 | SPHINXBUILD ?= sphinx-build
8 | SOURCEDIR = source
9 | BUILDDIR = build
10 |
11 | # Put it first so that "make" without argument is like "make help".
12 | help:
13 | @$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
14 |
15 | .PHONY: help Makefile
16 |
17 | # Catch-all target: route all unknown targets to Sphinx using the new
18 | # "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
19 | %: Makefile
20 | @$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
21 |
--------------------------------------------------------------------------------
/docs/_static/Figure_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/docs/_static/Figure_1.png
--------------------------------------------------------------------------------
/docs/_static/Figure_10.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/docs/_static/Figure_10.png
--------------------------------------------------------------------------------
/docs/_static/Figure_11.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/docs/_static/Figure_11.png
--------------------------------------------------------------------------------
/docs/_static/Figure_12.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/docs/_static/Figure_12.png
--------------------------------------------------------------------------------
/docs/_static/Figure_13.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/docs/_static/Figure_13.png
--------------------------------------------------------------------------------
/docs/_static/Figure_14.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/docs/_static/Figure_14.png
--------------------------------------------------------------------------------
/docs/_static/Figure_15.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/docs/_static/Figure_15.png
--------------------------------------------------------------------------------
/docs/_static/Figure_16.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/docs/_static/Figure_16.png
--------------------------------------------------------------------------------
/docs/_static/Figure_17.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/docs/_static/Figure_17.png
--------------------------------------------------------------------------------
/docs/_static/Figure_18.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/docs/_static/Figure_18.png
--------------------------------------------------------------------------------
/docs/_static/Figure_19.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/docs/_static/Figure_19.png
--------------------------------------------------------------------------------
/docs/_static/Figure_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/docs/_static/Figure_2.png
--------------------------------------------------------------------------------
/docs/_static/Figure_20.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/docs/_static/Figure_20.png
--------------------------------------------------------------------------------
/docs/_static/Figure_21.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/docs/_static/Figure_21.png
--------------------------------------------------------------------------------
/docs/_static/Figure_22.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/docs/_static/Figure_22.png
--------------------------------------------------------------------------------
/docs/_static/Figure_23.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/docs/_static/Figure_23.png
--------------------------------------------------------------------------------
/docs/_static/Figure_24.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/docs/_static/Figure_24.png
--------------------------------------------------------------------------------
/docs/_static/Figure_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/docs/_static/Figure_3.png
--------------------------------------------------------------------------------
/docs/_static/Figure_4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/docs/_static/Figure_4.png
--------------------------------------------------------------------------------
/docs/_static/Figure_5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/docs/_static/Figure_5.png
--------------------------------------------------------------------------------
/docs/_static/Figure_6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/docs/_static/Figure_6.png
--------------------------------------------------------------------------------
/docs/_static/Figure_7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/docs/_static/Figure_7.png
--------------------------------------------------------------------------------
/docs/_static/Figure_8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/docs/_static/Figure_8.png
--------------------------------------------------------------------------------
/docs/_static/Figure_9.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/docs/_static/Figure_9.png
--------------------------------------------------------------------------------
/docs/algorithms.rst:
--------------------------------------------------------------------------------
1 | Algorithms
2 | ===================
3 |
4 | .. autofunction:: pyit2fls.KM_algorithm
5 |
6 | .. autofunction:: pyit2fls.EKM_algorithm
7 |
8 | .. autofunction:: pyit2fls.WEKM_algorithm
9 |
10 | .. autofunction:: pyit2fls.TWEKM_algorithm
11 |
12 | .. autofunction:: pyit2fls.EIASC_algorithm
13 |
14 | .. autofunction:: pyit2fls.WM_algorithm
15 |
16 | .. autofunction:: pyit2fls.BMM_algorithm
17 |
18 | .. autofunction:: pyit2fls.LBMM_algorithm
19 |
20 | .. autofunction:: pyit2fls.NT_algorithm
21 |
22 |
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
--------------------------------------------------------------------------------
/docs/classes.rst:
--------------------------------------------------------------------------------
1 | Classes
2 | =======
3 |
4 | T1FS
5 | ----
6 | .. autoclass:: pyit2fls.T1FS
7 |
8 | .. autofunction:: pyit2fls.T1FS.__repr__
9 |
10 | .. autofunction:: pyit2fls.T1FS.copy
11 |
12 | .. autofunction:: pyit2fls.T1FS.__call__
13 |
14 | .. autofunction:: pyit2fls.T1FS.__neg__
15 |
16 | .. autofunction:: pyit2fls.T1FS._CoG
17 |
18 | .. autofunction:: pyit2fls.T1FS.defuzzify
19 |
20 | .. autofunction:: pyit2fls.T1FS.plot
21 |
22 | T1TSK
23 | -----
24 | .. autoclass:: pyit2fls.T1TSK
25 |
26 | .. autofunction:: pyit2fls.T1TSK.__repr__
27 |
28 | .. autofunction:: pyit2fls.T1TSK.copy
29 |
30 | .. autofunction:: pyit2fls.T1TSK.add_input_variable
31 |
32 | .. autofunction:: pyit2fls.T1TSK.add_output_variable
33 |
34 | .. autofunction:: pyit2fls.T1TSK.add_rule
35 |
36 | .. autofunction:: pyit2fls.T1TSK.evaluate
37 |
38 | T1Mamdani
39 | ---------
40 | .. autoclass:: pyit2fls.T1Mamdani
41 |
42 | .. autofunction:: pyit2fls.T1Mamdani.__repr__
43 |
44 | .. autofunction:: pyit2fls.T1Mamdani.copy
45 |
46 | .. autofunction:: pyit2fls.T1Mamdani.add_input_variable
47 |
48 | .. autofunction:: pyit2fls.T1Mamdani.add_output_variable
49 |
50 | .. autofunction:: pyit2fls.T1Mamdani.add_rule
51 |
52 | .. autofunction:: pyit2fls.T1Mamdani._CoG
53 |
54 | .. autofunction:: pyit2fls.T1Mamdani._CoA
55 |
56 | .. autofunction:: pyit2fls.T1Mamdani._product_evaluate
57 |
58 | .. autofunction:: pyit2fls.T1Mamdani._minimum_evaluate
59 |
60 | .. autofunction:: pyit2fls.T1Mamdani._lukasiewicz_evaluate
61 |
62 | .. autofunction:: pyit2fls.T1Mamdani._zadeh_evaluate
63 |
64 | .. autofunction:: pyit2fls.T1Mamdani._dienes_rescher_evaluate
65 |
66 | IT2FS
67 | -----
68 | .. autoclass:: pyit2fls.IT2FS
69 |
70 | .. autofunction:: pyit2fls.IT2FS.__repr__
71 |
72 | .. autoproperty:: pyit2fls.IT2FS.upper
73 |
74 | .. autoproperty:: pyit2fls.IT2FS.lower
75 |
76 | .. autofunction:: pyit2fls.IT2FS.check_set
77 |
78 | .. autofunction:: pyit2fls.IT2FS.copy
79 |
80 | .. autofunction:: pyit2fls.IT2FS.plot
81 |
82 | .. autofunction:: pyit2fls.IT2FS.__neg__
83 |
84 | IT2FLS
85 | ------
86 | .. autoclass:: pyit2fls.IT2FLS
87 |
88 | .. autofunction:: pyit2fls.IT2FLS.__repr__
89 |
90 | .. autofunction:: pyit2fls.IT2FLS.add_input_variable
91 |
92 | .. autofunction:: pyit2fls.IT2FLS.add_output_variable
93 |
94 | .. autofunction:: pyit2fls.IT2FLS.add_rule
95 |
96 | .. autofunction:: pyit2fls.IT2FLS.copy
97 |
98 | .. autofunction:: pyit2fls.IT2FLS.evaluate_list
99 |
100 | .. autofunction:: pyit2fls.IT2FLS.evaluate
101 |
102 | IT2TSK
103 | ------
104 | .. autoclass:: pyit2fls.IT2TSK
105 |
106 | .. autofunction:: pyit2fls.IT2TSK.__repr__
107 |
108 | .. autofunction:: pyit2fls.IT2TSK.add_input_variable
109 |
110 | .. autofunction:: pyit2fls.IT2TSK.add_output_variable
111 |
112 | .. autofunction:: pyit2fls.IT2TSK.add_rule
113 |
114 | .. autofunction:: pyit2fls.IT2TSK.copy
115 |
116 | .. autofunction:: pyit2fls.IT2TSK.evaluate
117 |
118 | IT2Mamdani
119 | ----------
120 | .. autoclass:: pyit2fls.IT2Mamdani
121 |
122 | .. autofunction:: pyit2fls.IT2Mamdani.add_input_variable
123 |
124 | .. autofunction:: pyit2fls.IT2Mamdani.add_output_variable
125 |
126 | .. autofunction:: pyit2fls.IT2Mamdani.add_rule
127 |
128 | .. autofunction:: pyit2fls.IT2Mamdani.copy
129 |
130 | .. autofunction:: pyit2fls.IT2Mamdani.__repr__
131 |
132 | .. autofunction:: pyit2fls.IT2Mamdani.__meet
133 |
134 | .. autofunction:: pyit2fls.IT2Mamdani.__join
135 |
136 | .. autofunction:: pyit2fls.IT2Mamdani.__Mamdani_Centroid
137 |
138 | .. autofunction:: pyit2fls.IT2Mamdani.__Mamdani_CoSet
139 |
140 | .. autofunction:: pyit2fls.IT2Mamdani.__Mamdani_CoSum
141 |
142 | .. autofunction:: pyit2fls.IT2Mamdani.__Mamdani_Height
143 |
144 | .. autofunction:: pyit2fls.IT2Mamdani.__Mamdani_ModiHe
145 |
146 |
147 | T1Fuzzy_ML
148 | ----------
149 | .. autoclass:: pyit2fls.T1Fuzzy_ML
150 |
151 | .. autofunction:: pyit2fls.T1Fuzzy_ML.error
152 |
153 | .. autofunction:: pyit2fls.T1Fuzzy_ML.fit
154 |
155 | .. autofunction:: pyit2fls.T1Fuzzy_ML.score
156 |
157 |
158 | T1Mamdani_ML
159 | ------------
160 | .. autoclass:: pyit2fls.T1Mamdani_ML
161 |
162 | .. autofunction:: pyit2fls.T1Mamdani_ML.get_T1Mamdani
163 |
164 |
165 | T1TSK_ML
166 | --------
167 | .. autoclass:: pyit2fls.T1TSK_ML
168 |
169 | .. autofunction:: pyit2fls.T1TSK_ML.get_T1TSK
170 |
171 |
172 | Linear_System
173 | -------------
174 | .. autoclass:: pyit2fls.Linear_System
175 |
176 | .. autofunction:: pyit2fls.Linear_System.__call__
177 |
178 | .. autofunction:: pyit2fls.Linear_System.Y
179 |
180 | .. autofunction:: pyit2fls.Linear_System.__repr__
181 |
182 | .. autofunction:: pyit2fls.Linear_System.__str__
183 |
184 | .. autofunction:: pyit2fls.Linear_System.__add__
185 |
186 | .. autofunction:: pyit2fls.Linear_System.__sub__
187 |
188 | .. autofunction:: pyit2fls.Linear_System.__neg__
189 |
190 | .. autofunction:: pyit2fls.Linear_System.__mul__
191 |
192 | .. autofunction:: pyit2fls.Linear_System.__truediv__
193 |
194 | .. autofunction:: pyit2fls.Linear_System.__isub__
195 |
196 | .. autofunction:: pyit2fls.Linear_System.__iadd__
197 |
198 | .. autofunction:: pyit2fls.Linear_System.__imul__
199 |
200 | .. autofunction:: pyit2fls.Linear_System.__idiv__
201 |
202 |
203 | T1_TS_Model
204 | -----------
205 | .. autoclass:: pyit2fls.T1_TS_Model
206 |
207 | .. autofunction:: pyit2fls.T1_TS_Model.d0
208 |
209 | .. autofunction:: pyit2fls.T1_TS_Model.__call__
210 |
211 | .. autofunction:: pyit2fls.T1_TS_Model.Y
212 |
213 |
214 |
215 | IT2TSK_ML_Model
216 | ---------------
217 | .. autoclass:: pyit2fls.IT2TSK_ML_Model
218 |
219 | .. autofunction:: pyit2fls.IT2TSK_ML_Model.__call__
220 |
221 |
222 | IT2TSK_ML
223 | ---------
224 | .. autoclass:: pyit2fls.IT2TSK_ML
225 |
226 | .. autofunction:: pyit2fls.IT2TSK_ML.error
227 |
228 | .. autofunction:: pyit2fls.IT2TSK_ML.fit
229 |
230 | .. autofunction:: pyit2fls.IT2TSK_ML.score
231 |
232 |
233 | IT2Mamdani_ML_Model
234 | -------------------
235 | .. autoclass:: pyit2fls.IT2Mamdani_ML_Model
236 |
237 | .. autofunction:: pyit2fls.IT2Mamdani_ML_Model.__call__
238 |
239 |
240 | IT2Mamdani_ML
241 | -------------
242 | .. autoclass:: pyit2fls.IT2Mamdani_ML
243 |
244 | .. autofunction:: pyit2fls.IT2Mamdani_ML.error
245 |
246 | .. autofunction:: pyit2fls.IT2Mamdani_ML.fit
247 |
248 | .. autofunction:: pyit2fls.IT2Mamdani_ML.score
249 |
250 |
251 | IT2_TS_Model
252 | ------------
253 | .. autoclass:: pyit2fls.IT2_TS_Model
254 |
255 | .. autofunction:: pyit2fls.IT2_TS_Model.d0
256 |
257 | .. autofunction:: pyit2fls.IT2_TS_Model.__call__
258 |
259 | .. autofunction:: pyit2fls.IT2_TS_Model.Y
260 |
261 |
262 | GA
263 | --
264 | .. autoclass:: pyit2fls.GA
265 |
266 | .. autofunction:: pyit2fls.GA.tournament_selection
267 |
268 | .. autofunction:: pyit2fls.GA.mutate
269 |
270 | .. autofunction:: pyit2fls.GA.crossover
271 |
272 | .. autofunction:: pyit2fls.GA.iterate
273 |
274 |
275 | PSO
276 | ---
277 | .. autoclass:: pyit2fls.PSO
278 |
279 | .. autofunction:: pyit2fls.PSO.iterate
280 |
281 |
282 | GWO
283 | ---
284 | .. autoclass:: pyit2fls.GWO
285 |
286 | .. autofunction:: pyit2fls.GWO.iterate
287 |
288 | .. autofunction:: pyit2fls.GWO._update_leaders
289 |
290 |
291 | WOA
292 | ---
293 | .. autoclass:: pyit2fls.WOA
294 |
295 | .. autofunction:: pyit2fls.WOA.iterate
296 |
297 |
298 | FFA
299 | ---
300 | .. autoclass:: pyit2fls.FFA
301 |
302 | .. autofunction:: pyit2fls.FFA.iterate
303 |
304 |
305 | CuckooSearch
306 | ------------
307 | .. autoclass:: pyit2fls.CuckooSearch
308 |
309 | .. autofunction:: pyit2fls.CuckooSearch.iterate
310 |
311 | .. autofunction:: pyit2fls.CuckooSearch.get_cuckoo
312 |
313 | .. autofunction:: pyit2fls.CuckooSearch.get_best_solution
314 |
315 |
316 | ICA
317 | ---
318 | .. autoclass:: pyit2fls.ICA
319 |
320 | .. autofunction:: pyit2fls.ICA.iterate
321 |
322 | .. autofunction:: pyit2fls.ICA.get_best_solution
323 |
324 |
325 |
326 |
327 |
--------------------------------------------------------------------------------
/docs/conf.py:
--------------------------------------------------------------------------------
1 | # Configuration file for the Sphinx documentation builder.
2 | #
3 | # For the full list of built-in configuration values, see the documentation:
4 | # https://www.sphinx-doc.org/en/master/usage/configuration.html
5 |
6 | # -- Project information -----------------------------------------------------
7 | # https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information
8 |
9 | project = 'PyIT2FLS'
10 | copyright = '2024, Amir Arslan Haghrah'
11 | author = 'Amir Arslan Haghrah'
12 | release = '0.8.0'
13 |
14 | # -- General configuration ---------------------------------------------------
15 | # https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration
16 |
17 | templates_path = ['_templates']
18 | exclude_patterns = []
19 |
20 | # -- Options for HTML output -------------------------------------------------
21 | # https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output
22 |
23 | html_theme = 'sphinx_rtd_theme'
24 | html_static_path = ['_static']
25 |
26 | html_title = 'PyIT2FLS'
27 |
28 | extensions = ['sphinx.ext.autodoc',
29 | 'sphinx.ext.mathjax', ]
30 |
31 | import os
32 | import sys
33 | sys.path.insert(0, os.path.abspath('../'))
34 |
35 | html_theme_options = {
36 | # If False, expand all TOC entries
37 | 'globaltoc_collapse': False,
38 | # If True, show hidden TOC entries
39 | 'globaltoc_includehidden': False,
40 | }
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
--------------------------------------------------------------------------------
/docs/functions.rst:
--------------------------------------------------------------------------------
1 | Functions
2 | ====================
3 |
4 | .. autofunction:: pyit2fls.T1FS_Emphasize
5 |
6 | .. autofunction:: pyit2fls.T1FS_plot
7 |
8 | .. autofunction:: pyit2fls.T1FS_AND
9 |
10 | .. autofunction:: pyit2fls.T1FS_OR
11 |
12 | .. autofunction:: pyit2fls.IT2FS_Emphasize
13 |
14 | .. autofunction:: pyit2fls.IT2FS_plot
15 |
16 | .. autofunction:: pyit2fls.TR_plot
17 |
18 | .. autofunction:: pyit2fls.crisp
19 |
20 | .. autofunction:: pyit2fls.crisp_list
21 |
22 | .. autofunction:: pyit2fls.meet
23 |
24 | .. autofunction:: pyit2fls.MEET
25 |
26 | .. autofunction:: pyit2fls.join
27 |
28 | .. autofunction:: pyit2fls.JOIN
29 |
30 | .. autofunction:: pyit2fls.Centroid
31 |
32 | .. autofunction:: pyit2fls.CoSet
33 |
34 | .. autofunction:: pyit2fls.CoSum
35 |
36 | .. autofunction:: pyit2fls.Height
37 |
38 | .. autofunction:: pyit2fls.ModiHe
39 |
40 |
41 |
42 |
--------------------------------------------------------------------------------
/docs/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 | Redirecting...
6 |
7 |
8 | If you are not redirected automatically, follow this link.
9 |
10 |
11 |
--------------------------------------------------------------------------------
/docs/index.rst:
--------------------------------------------------------------------------------
1 | Welcome to PyIT2FLS's documentation!
2 | ====================================
3 |
4 | .. toctree::
5 | :maxdepth: 3
6 | :caption: Contents:
7 |
8 | _generated/pyit2fls
9 | classes
10 | membershipfunctions
11 | it2fs
12 | t_s_norms
13 | functions
14 | algorithms
15 | matrices
16 |
17 |
18 |
19 | Indices and tables
20 | ==================
21 |
22 | * :ref:`genindex`
23 | * :ref:`modindex`
24 | * :ref:`search`
25 |
--------------------------------------------------------------------------------
/docs/it2fs.rst:
--------------------------------------------------------------------------------
1 | Popular Interval Type 2 Fuzzy Sets
2 | ==================================
3 |
4 |
5 | .. autofunction:: pyit2fls.IT2FS_Elliptic
6 |
7 | .. autofunction:: pyit2fls.IT2FS_Semi_Elliptic
8 |
9 | .. autofunction:: pyit2fls.IT2FS_Gaussian_UncertMean
10 |
11 | .. autofunction:: pyit2fls.IT2FS_Gaussian_UncertStd
12 |
13 | .. autofunction:: pyit2fls.IT2FS_RGaussian_UncertStd
14 |
15 | .. autofunction:: pyit2fls.IT2FS_LGaussian_UncertStd
16 |
17 |
18 |
19 |
20 |
21 |
22 |
23 |
--------------------------------------------------------------------------------
/docs/make.bat:
--------------------------------------------------------------------------------
1 | @ECHO OFF
2 |
3 | pushd %~dp0
4 |
5 | REM Command file for Sphinx documentation
6 |
7 | if "%SPHINXBUILD%" == "" (
8 | set SPHINXBUILD=sphinx-build
9 | )
10 | set SOURCEDIR=source
11 | set BUILDDIR=build
12 |
13 | %SPHINXBUILD% >NUL 2>NUL
14 | if errorlevel 9009 (
15 | echo.
16 | echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
17 | echo.installed, then set the SPHINXBUILD environment variable to point
18 | echo.to the full path of the 'sphinx-build' executable. Alternatively you
19 | echo.may add the Sphinx directory to PATH.
20 | echo.
21 | echo.If you don't have Sphinx installed, grab it from
22 | echo.https://www.sphinx-doc.org/
23 | exit /b 1
24 | )
25 |
26 | if "%1" == "" goto help
27 |
28 | %SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
29 | goto end
30 |
31 | :help
32 | %SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
33 |
34 | :end
35 | popd
36 |
--------------------------------------------------------------------------------
/docs/matrices.rst:
--------------------------------------------------------------------------------
1 | Matrices
2 | ========
3 |
4 | .. autofunction:: pyit2fls.T1FMatrix
5 |
6 | .. autofunction:: pyit2fls.T1FMatrix_Complement
7 |
8 | .. autofunction:: pyit2fls.T1FMatrix_Intersection
9 |
10 | .. autofunction:: pyit2fls.T1FMatrix_Union
11 |
12 | .. autofunction:: pyit2fls.Minmax
13 |
14 | .. autofunction:: pyit2fls.Maxmin
15 |
16 | .. autofunction:: pyit2fls.T1FMatrix_isNull
17 |
18 | .. autofunction:: pyit2fls.T1FMatrix_isUniversal
19 |
20 | .. autofunction:: pyit2fls.T1FSoftMatrix_Product
21 |
22 | .. autofunction:: pyit2fls.T1FSoftMatrix
23 |
24 |
25 |
26 |
27 |
28 |
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
--------------------------------------------------------------------------------
/docs/membershipfunctions.rst:
--------------------------------------------------------------------------------
1 | Membership Functions
2 | ====================
3 |
4 | .. autofunction:: pyit2fls.zero_mf
5 |
6 | .. autofunction:: pyit2fls.singleton_mf
7 |
8 | .. autofunction:: pyit2fls.const_mf
9 |
10 | .. autofunction:: pyit2fls.tri_mf
11 |
12 | .. autofunction:: pyit2fls.rtri_mf
13 |
14 | .. autofunction:: pyit2fls.ltri_mf
15 |
16 | .. autofunction:: pyit2fls.trapezoid_mf
17 |
18 | .. autofunction:: pyit2fls.gaussian_mf
19 |
20 | .. autofunction:: pyit2fls.gauss_uncert_mean_umf
21 |
22 | .. autofunction:: pyit2fls.gauss_uncert_mean_lmf
23 |
24 | .. autofunction:: pyit2fls.gauss_uncert_std_umf
25 |
26 | .. autofunction:: pyit2fls.gauss_uncert_std_lmf
27 |
28 | .. autofunction:: pyit2fls.rgauss_uncert_std_umf
29 |
30 | .. autofunction:: pyit2fls.rgauss_uncert_std_lmf
31 |
32 | .. autofunction:: pyit2fls.lgauss_uncert_std_umf
33 |
34 | .. autofunction:: pyit2fls.lgauss_uncert_std_lmf
35 |
36 | .. autofunction:: pyit2fls.elliptic_mf
37 |
38 | .. autofunction:: pyit2fls.semi_elliptic_mf
39 |
40 | .. autofunction:: pyit2fls.gbell_mf
41 |
42 |
43 |
44 |
45 |
--------------------------------------------------------------------------------
/docs/requirements.txt:
--------------------------------------------------------------------------------
1 | Sphinx==7.1.2
2 | sphinx-rtd-theme==2.0.0
3 | numpy
4 | scipy
5 | matplotlib
6 |
--------------------------------------------------------------------------------
/docs/t_s_norms.rst:
--------------------------------------------------------------------------------
1 | T-Norms and S-Norms
2 | ===================
3 |
4 | .. autofunction:: pyit2fls.min_t_norm
5 |
6 | .. autofunction:: pyit2fls.product_t_norm
7 |
8 | .. autofunction:: pyit2fls.lukasiewicz_t_norm
9 |
10 | .. autofunction:: pyit2fls.drastic_t_norm
11 |
12 | .. autofunction:: pyit2fls.nilpotent_minimum_t_norm
13 |
14 | .. autofunction:: pyit2fls.hamacher_product_t_norm
15 |
16 | .. autofunction:: pyit2fls.max_s_norm
17 |
18 | .. autofunction:: pyit2fls.probabilistic_sum_s_norm
19 |
20 | .. autofunction:: pyit2fls.bounded_sum_s_norm
21 |
22 | .. autofunction:: pyit2fls.drastic_s_norm
23 |
24 | .. autofunction:: pyit2fls.nilpotent_maximum_s_norm
25 |
26 | .. autofunction:: pyit2fls.einstein_sum_s_norm
27 |
28 |
29 |
30 |
31 |
32 |
--------------------------------------------------------------------------------
/examples/PyIT2FLSPSO.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Wed Jan 24 14:48:37 2018
5 |
6 | @author: arslan
7 | """
8 |
9 | from numpy import random, shape
10 | import numpy as np
11 | import matplotlib.pyplot as plt
12 |
13 | class Particle:
14 |
15 | def __init__(self, solution_generator_function, velocity_generator_function):
16 | self.cost = float("inf")
17 | self.best_known_cost = float("inf")
18 | self.position = solution_generator_function()
19 | self.velocity = velocity_generator_function()
20 | self.best_known_position = self.position.copy()
21 | return
22 |
23 | def __repr__(self):
24 | o = "Position:\n"
25 | for d in self.position:
26 | o += str(d) + "\n"
27 | o += "Current cost: " + str(self.cost) + "\nBest known position:\n"
28 | for d in self.best_known_position:
29 | o += str(d) + "\n"
30 | o += "Best known cost: " + str(self.best_known_cost)
31 | return o
32 |
33 | class PyPSO:
34 |
35 | def __init__(self, cost_function, particle_num, iteration_num, solution_generator_function, velocity_generator_function, omega=0.3, phi_p=0.3, phi_g=2.1):
36 | self.cost_function = cost_function
37 | self.particle_num = particle_num
38 | self.iteration_num = iteration_num
39 | self.omega = omega
40 | self.phi_p = phi_p
41 | self.phi_g = phi_g
42 | self.particles = []
43 | self.best_known_cost = float("inf")
44 | self.best_known_position = []
45 | for i in range(self.particle_num):
46 | self.particles.append(Particle(solution_generator_function, velocity_generator_function))
47 | self.particles[i].cost = self.cost_function(self.particles[i].position)
48 | self.particles[i].best_known_cost = self.particles[i].cost
49 | if self.particles[i].cost < self.best_known_cost:
50 | self.best_known_position = self.particles[i].position.copy()
51 | self.best_known_cost = self.particles[i].cost
52 | print("Particle", i+1, "created!")
53 | return
54 |
55 | def __repr__(self):
56 | o = "Best known position:\n"
57 | for d in self.best_known_position:
58 | o += str(d) + "\n"
59 | o += "Best known cost: " + str(self.best_known_cost)
60 | return o
61 |
62 | def solve(self):
63 | print("Solver has started!")
64 | convergence = []
65 | for i in range(self.iteration_num):
66 | for particle in self.particles:
67 | r_p = random.random(size=shape(particle.position))
68 | r_g = random.random(size=shape(particle.position))
69 | particle.velocity = self.omega * particle.velocity + \
70 | self.phi_p * r_p * (particle.best_known_position - particle.position) + \
71 | self.phi_g * r_g * (self.best_known_position- particle.position)
72 | particle.position = np.abs(particle.position + particle.velocity)
73 | particle.cost = self.cost_function(particle.position)
74 | if particle.cost < particle.best_known_cost:
75 | particle.best_known_position = particle.position.copy()
76 | particle.best_known_cost = particle.cost
77 | if particle.best_known_cost < self.best_known_cost:
78 | self.best_known_position = particle.best_known_position.copy()
79 | self.best_known_cost = particle.best_known_cost
80 | print("Iteration. " + str(i+1))
81 | print(self.best_known_cost)
82 | convergence.append(self.best_known_cost)
83 | plt.figure()
84 | plt.plot(convergence)
85 | plt.title("Convergence diagram")
86 | plt.xlabel("Iteration")
87 | plt.ylabel("Total cost")
88 | plt.grid(True)
89 | plt.show()
90 | return convergence
91 |
92 | if __name__ == "__main__":
93 | print("PSO algorithm library")
94 |
95 |
96 |
97 |
98 |
99 |
100 |
--------------------------------------------------------------------------------
/examples/Sphinx docs examples/Ex1.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Tue Nov 12 15:40:26 2024
5 |
6 | @author: arslan
7 | """
8 |
9 |
10 | from pyit2fls import (T1FS, trapezoid_mf, T1FS_plot, )
11 | from numpy import linspace
12 |
13 | domain = linspace(-1.5, 1.5, 100)
14 | set1 = T1FS(domain, trapezoid_mf, [-1.25, -0.75, -0.25, 0.25, 1.])
15 | set2 = T1FS(domain, trapezoid_mf, [-0.25, 0.25, 0.75, 1.25, 1.])
16 | T1FS_plot(set1, set2, legends=["Trapezoidal Set 1", "Trapezoidal Set 2", ])
17 |
18 | from pyit2fls import (min_t_norm, product_t_norm, T1FS_AND, )
19 |
20 | set3 = T1FS_AND(domain, set1, set2, min_t_norm)
21 | set4 = T1FS_AND(domain, set1, set2, product_t_norm)
22 | T1FS_plot(set3, set4, legends=["Fuzzy Set 3", "Fuzzy Set 4", ])
23 |
24 | from pyit2fls import (max_s_norm, probabilistic_sum_s_norm, T1FS_OR, )
25 |
26 | set5 = T1FS_OR(domain, set1, set2, max_s_norm)
27 | set6 = T1FS_OR(domain, set1, set2, probabilistic_sum_s_norm)
28 | T1FS_plot(set5, set6, legends=["Fuzzy Set 5", "Fuzzy Set 6", ])
29 |
30 |
31 |
32 |
33 |
34 |
35 |
36 |
37 |
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
--------------------------------------------------------------------------------
/examples/Sphinx docs examples/Ex2.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Wed Nov 13 11:43:11 2024
5 |
6 | @author: arslan
7 | """
8 |
9 | from pyit2fls import (T1TSK, T1FS, gaussian_mf, T1FS_plot, )
10 | from numpy import (linspace, meshgrid, zeros, )
11 | from mpl_toolkits import mplot3d
12 | import matplotlib.pyplot as plt
13 | from matplotlib import cm
14 | from matplotlib.ticker import (LinearLocator, FormatStrFormatter, )
15 |
16 | domain = linspace(-1.5, 1.5, 100)
17 | t1fs1 = T1FS(domain, gaussian_mf, [-0.5, 0.5, 1.])
18 | t1fs2 = T1FS(domain, gaussian_mf, [ 0.5, 0.5, 1.])
19 | T1FS_plot(t1fs1, t1fs2, legends=["Gaussian Set 1", "Gaussian Set 2", ])
20 |
21 | myT1TSK = T1TSK()
22 | myT1TSK.add_input_variable("X1")
23 | myT1TSK.add_input_variable("X2")
24 |
25 | myT1TSK.add_output_variable("Y")
26 |
27 | def Y1(X1, X2):
28 | return 2. * X1 + 3. * X2
29 |
30 | def Y2(X1, X2):
31 | return -1.5 * X1 + 2. * X2
32 |
33 | def Y3(X1, X2):
34 | return -2. * X1 - 1.2 * X2
35 |
36 | def Y4(X1, X2):
37 | return 5. * X1 - 2.5 * X2
38 |
39 | myT1TSK.add_rule([("X1", t1fs1), ("X2", t1fs1)],
40 | [("Y", Y1), ])
41 | myT1TSK.add_rule([("X1", t1fs1), ("X2", t1fs2)],
42 | [("Y", Y2), ])
43 | myT1TSK.add_rule([("X1", t1fs2), ("X2", t1fs1)],
44 | [("Y", Y3), ])
45 | myT1TSK.add_rule([("X1", t1fs2), ("X2", t1fs2)],
46 | [("Y", Y4), ])
47 |
48 | X1, X2 = meshgrid(domain, domain)
49 | O = zeros(shape=X1.shape)
50 |
51 | for i, x1 in zip(range(len(domain)), domain):
52 | for j, x2 in zip(range(len(domain)), domain):
53 | o = myT1TSK.evaluate({"X1":x1, "X2":x2}, params=(x1, x2))
54 | O[i, j] = o["Y"]
55 |
56 | fig = plt.figure()
57 | ax = fig.add_subplot(111, projection="3d")
58 | surf = ax.plot_surface(X1, X2, O, cmap=cm.coolwarm,
59 | linewidth=0, antialiased=False)
60 | ax.zaxis.set_major_locator(LinearLocator(10))
61 | ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
62 | fig.colorbar(surf, shrink=0.5, aspect=5)
63 | plt.show()
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
77 |
--------------------------------------------------------------------------------
/examples/Sphinx docs examples/Ex3.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Thu Nov 14 09:03:02 2024
5 |
6 | @author: arslan
7 | """
8 |
9 | from pyit2fls import (T1Mamdani, T1FS, gaussian_mf, T1FS_plot, )
10 | from numpy import (linspace, meshgrid, zeros, )
11 | from mpl_toolkits import mplot3d
12 | import matplotlib.pyplot as plt
13 | from matplotlib import cm
14 | from matplotlib.ticker import (LinearLocator, FormatStrFormatter, )
15 |
16 | inputDomain = linspace(-1.5, 1.5, 100)
17 | t1fs1 = T1FS(inputDomain, gaussian_mf, [-0.5, 0.5, 1.])
18 | t1fs2 = T1FS(inputDomain, gaussian_mf, [ 0.5, 0.5, 1.])
19 | T1FS_plot(t1fs1, t1fs2, legends=["Gaussian Set 1", "Gaussian Set 2", ])
20 |
21 | outputDomain = linspace(-10., 10., 1000)
22 | t1fs3 = T1FS(outputDomain, gaussian_mf, [-7.5, 2.0, 1.])
23 | t1fs4 = T1FS(outputDomain, gaussian_mf, [-2.5, 2.0, 1.])
24 | t1fs5 = T1FS(outputDomain, gaussian_mf, [ 2.5, 2.0, 1.])
25 | t1fs6 = T1FS(outputDomain, gaussian_mf, [ 7.5, 2.0, 1.])
26 | T1FS_plot(t1fs3, t1fs4, t1fs5, t1fs6,
27 | legends=["Gaussian Set 3", "Gaussian Set 4",
28 | "Gaussian Set 5", "Gaussian Set 6", ])
29 |
30 | myT1Mamdani = T1Mamdani(engine="Product", defuzzification="CoG")
31 | myT1Mamdani.add_input_variable("X1")
32 | myT1Mamdani.add_input_variable("X2")
33 |
34 | myT1Mamdani.add_output_variable("Y")
35 |
36 | myT1Mamdani.add_rule([("X1", t1fs1), ("X2", t1fs1)], [("Y", t1fs3), ])
37 | myT1Mamdani.add_rule([("X1", t1fs1), ("X2", t1fs2)], [("Y", t1fs4), ])
38 | myT1Mamdani.add_rule([("X1", t1fs2), ("X2", t1fs1)], [("Y", t1fs5), ])
39 | myT1Mamdani.add_rule([("X1", t1fs2), ("X2", t1fs2)], [("Y", t1fs6), ])
40 |
41 | X1, X2 = meshgrid(inputDomain, inputDomain)
42 | O = zeros(shape=X1.shape)
43 |
44 | for i, x1 in zip(range(len(inputDomain)), inputDomain):
45 | for j, x2 in zip(range(len(inputDomain)), inputDomain):
46 | s, c = myT1Mamdani.evaluate({"X1":x1, "X2":x2})
47 | O[i, j] = c["Y"]
48 |
49 | fig = plt.figure()
50 | ax = fig.add_subplot(111, projection="3d")
51 | surf = ax.plot_surface(X1, X2, O, cmap=cm.coolwarm,
52 | linewidth=0, antialiased=False)
53 | ax.zaxis.set_major_locator(LinearLocator(10))
54 | ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
55 | fig.colorbar(surf, shrink=0.5, aspect=5)
56 | plt.show()
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
74 |
75 |
76 |
--------------------------------------------------------------------------------
/examples/Sphinx docs examples/Ex4.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Fri Nov 22 14:11:43 2024
5 |
6 | @author: arslan
7 | """
8 |
9 | from pyit2fls import (IT2FS, tri_mf, const_mf, rtri_mf, ltri_mf,
10 | trapezoid_mf, gaussian_mf, IT2FS_Gaussian_UncertMean,
11 | IT2FS_Gaussian_UncertStd, R_IT2FS_Gaussian_UncertStd,
12 | L_IT2FS_Gaussian_UncertStd, IT2FS_plot, )
13 | from numpy import linspace
14 |
15 | domain = linspace(0, 4, 1001)
16 |
17 | Const = IT2FS(domain, const_mf, [1.0], const_mf, [0.9], check_set=True)
18 | Tri = IT2FS(domain, tri_mf, [0.7, 1.0, 1.3, 0.3], tri_mf, [0.8, 1.0, 1.2, 0.2], check_set=True)
19 | RTri = IT2FS(domain, rtri_mf, [1.85, 1.25, 0.8], rtri_mf, [1.75, 1.15, 0.8], check_set=True)
20 | LTri = IT2FS(domain, ltri_mf, [0.15, 0.75, 0.7], ltri_mf, [0.25, 0.85, 0.7], check_set=True)
21 | Trapezoid = IT2FS(domain,
22 | trapezoid_mf, [0.45, 0.85, 1.15, 1.55, 0.5],
23 | trapezoid_mf, [0.55, 0.95, 1.05, 1.45, 0.45],
24 | check_set=True)
25 | Gaussian = IT2FS(domain,
26 | gaussian_mf, [2.25, 0.1, 0.5],
27 | gaussian_mf, [2.25, 0.05, 0.4],
28 | check_set=True)
29 | Gaussian_UncertMean = IT2FS_Gaussian_UncertMean(domain, [2.5, 0.1, 0.1, 0.5])
30 | Gaussian_UncertStd = IT2FS_Gaussian_UncertStd(domain, [2.75, 0.1, 0.05, 0.5])
31 | RGaussian_UncertStd = R_IT2FS_Gaussian_UncertStd(domain, [3.25, 0.2, 0.05, 0.6])
32 | LGaussian_UncertStd = L_IT2FS_Gaussian_UncertStd(domain, [3.75, 0.2, 0.05, 0.6])
33 |
34 | IT2FS_plot(Const, Tri, RTri, LTri, Trapezoid, Gaussian,
35 | Gaussian_UncertMean, Gaussian_UncertStd,
36 | RGaussian_UncertStd, LGaussian_UncertStd,
37 | legends = ["Const Set",
38 | "Triangular Set",
39 | "Right Triangular Set",
40 | "Left Triangular Set",
41 | "Trapezoid",
42 | "Gaussian",
43 | "G. with Uncertain Mean",
44 | "G. with Uncertain Std",
45 | "Right G. with Uncertain Std",
46 | "Left G. with Uncertain Std", ],
47 | legendloc="upper right", bbox_to_anchor=(1.55, 1),
48 | filename="Figure_9", ext="png")
49 |
50 |
51 |
52 |
53 |
--------------------------------------------------------------------------------
/examples/Sphinx docs examples/Ex5.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Fri Nov 22 15:47:28 2024
5 |
6 | @author: arslan
7 | """
8 |
9 | from pyit2fls import (IT2FS, R_IT2FS_Gaussian_UncertStd,
10 | L_IT2FS_Gaussian_UncertStd, IT2FS_plot,
11 | hamacher_product_t_norm, probabilistic_sum_s_norm,
12 | meet, join)
13 | from numpy import linspace
14 |
15 | domain = linspace(1, 2, 1001)
16 |
17 | RGaussian_UncertStd = R_IT2FS_Gaussian_UncertStd(domain, [1.25, 0.2, 0.05, 0.6])
18 | LGaussian_UncertStd = L_IT2FS_Gaussian_UncertStd(domain, [1.75, 0.2, 0.05, 0.6])
19 |
20 | MEET = meet(domain, RGaussian_UncertStd, LGaussian_UncertStd, hamacher_product_t_norm)
21 | JOIN = join(domain, RGaussian_UncertStd, LGaussian_UncertStd, probabilistic_sum_s_norm)
22 |
23 | IT2FS_plot(RGaussian_UncertStd, LGaussian_UncertStd,
24 | legends=["IT2FS1",
25 | "IT2FS2", ])
26 |
27 | IT2FS_plot(MEET, JOIN,
28 | legends=["MEET",
29 | "JOIN", ])
30 |
--------------------------------------------------------------------------------
/examples/Sphinx docs examples/Ex6.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Fri Nov 22 19:41:38 2024
5 |
6 | @author: arslan
7 | """
8 |
9 | from pyit2fls import (IT2TSK, IT2FS_Gaussian_UncertStd, IT2FS_plot,
10 | product_t_norm, max_s_norm, )
11 | from mpl_toolkits import mplot3d
12 | import matplotlib.pyplot as plt
13 | from matplotlib import cm
14 | from matplotlib.ticker import LinearLocator, FormatStrFormatter
15 | from numpy import linspace, meshgrid, zeros
16 |
17 | domain = linspace(0., 1., 100)
18 |
19 | X1, X2 = meshgrid(domain, domain)
20 |
21 | IT2FS1 = IT2FS_Gaussian_UncertStd(domain, [0, 0.2, 0.05, 1.])
22 | IT2FS2 = IT2FS_Gaussian_UncertStd(domain, [1., 0.2, 0.05, 1.])
23 | IT2FS_plot(IT2FS1, IT2FS2, title="Sets",
24 | legends=["IT2FS1", "IT2FS2"])
25 |
26 | myIT2FLS = IT2TSK(product_t_norm, max_s_norm)
27 |
28 | myIT2FLS.add_input_variable("X1")
29 | myIT2FLS.add_input_variable("X2")
30 | myIT2FLS.add_output_variable("Y")
31 |
32 | myIT2FLS.add_rule([("X1", IT2FS1), ("X2", IT2FS1)],
33 | [("Y", {"const":1., "X1":1., "X2":1.}), ])
34 | myIT2FLS.add_rule([("X1", IT2FS1), ("X2", IT2FS2)],
35 | [("Y", {"const":0.5, "X1":1.5, "X2":0.5}), ])
36 | myIT2FLS.add_rule([("X1", IT2FS2), ("X2", IT2FS1)],
37 | [("Y", {"const":-0.2, "X1":2., "X2":0.1}), ])
38 | myIT2FLS.add_rule([("X1", IT2FS2), ("X2", IT2FS2)],
39 | [("Y", {"const":-1., "X1":4., "X2":-0.5}), ])
40 |
41 |
42 | O = zeros(shape=X1.shape)
43 |
44 | for i, x1 in zip(range(len(domain)), domain):
45 | for j, x2 in zip(range(len(domain)), domain):
46 | o = myIT2FLS.evaluate({"X1":x1, "X2":x2})
47 | O[i, j] = o["Y"]
48 |
49 |
50 | fig = plt.figure()
51 | ax = fig.add_subplot(111, projection="3d")
52 | surf = ax.plot_surface(X1, X2, O, cmap=cm.coolwarm,
53 | linewidth=0, antialiased=False)
54 | ax.zaxis.set_major_locator(LinearLocator(10))
55 | ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
56 | fig.colorbar(surf, shrink=0.5, aspect=5)
57 | plt.show()
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
72 |
73 |
--------------------------------------------------------------------------------
/examples/Sphinx docs examples/Ex7.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Fri Nov 22 19:41:48 2024
5 |
6 | @author: arslan
7 | """
8 |
9 |
10 | from pyit2fls import IT2Mamdani, IT2FS_Gaussian_UncertStd, IT2FS_plot, \
11 | min_t_norm, max_s_norm, crisp
12 | from numpy import linspace, meshgrid, zeros
13 | from mpl_toolkits import mplot3d
14 | import matplotlib.pyplot as plt
15 | from matplotlib import cm
16 | from matplotlib.ticker import LinearLocator, FormatStrFormatter
17 |
18 | domain1 = linspace(1., 2., 100)
19 | domain2 = linspace(2., 3., 100)
20 | domain3 = linspace(3., 4., 100)
21 |
22 | Small1 = IT2FS_Gaussian_UncertStd(domain1, [1.0, 0.2, 0.025, 1.])
23 | Small2 = IT2FS_Gaussian_UncertStd(domain2, [2.0, 0.3, 0.025, 1.])
24 | Medium1 = IT2FS_Gaussian_UncertStd(domain1, [1.5, 0.2, 0.025, 1.])
25 | Medium2 = IT2FS_Gaussian_UncertStd(domain2, [2.5, 0.3, 0.025, 1.])
26 | Large1 = IT2FS_Gaussian_UncertStd(domain1, [2.0, 0.2, 0.025, 1.])
27 | Large2 = IT2FS_Gaussian_UncertStd(domain2, [3.0, 0.3, 0.025, 1.])
28 |
29 | IT2FS_plot(Small1, Medium1, Large1,
30 | legends=["Small 1", "Medium 1", "large 1"])
31 | IT2FS_plot(Small2, Medium2, Large2,
32 | legends=["Smal 2l", "Medium 2", "large 2"])
33 |
34 | Low1 = IT2FS_Gaussian_UncertStd(domain3, [3., 0.3, 0.025, 1.])
35 | High1 = IT2FS_Gaussian_UncertStd(domain3, [4., 0.3, 0.025, 1.])
36 |
37 | IT2FS_plot(Low1, High1,
38 | legends=["Low", "High"])
39 |
40 | myIT2FLS = IT2Mamdani(min_t_norm, max_s_norm)
41 |
42 | myIT2FLS.add_input_variable("X1")
43 | myIT2FLS.add_input_variable("X2")
44 |
45 | myIT2FLS.add_output_variable("Y")
46 |
47 | myIT2FLS.add_rule([("X1", Small1), ("X2", Small2)], [("Y", Low1), ])
48 | myIT2FLS.add_rule([("X1", Small1), ("X2", Medium2)], [("Y", Low1), ])
49 | myIT2FLS.add_rule([("X1", Small1), ("X2", Large2)], [("Y", Low1), ])
50 | myIT2FLS.add_rule([("X1", Medium1), ("X2", Small2)], [("Y", Low1), ])
51 | myIT2FLS.add_rule([("X1", Medium1), ("X2", Medium2)], [("Y", Low1), ])
52 | myIT2FLS.add_rule([("X1", Medium1), ("X2", Large2)], [("Y", High1), ])
53 | myIT2FLS.add_rule([("X1", Large1), ("X2", Small2)], [("Y", High1), ])
54 | myIT2FLS.add_rule([("X1", Large1), ("X2", Medium2)], [("Y", High1), ])
55 | myIT2FLS.add_rule([("X1", Large1), ("X2", Large2)], [("Y", High1), ])
56 |
57 | X1, X2 = meshgrid(domain1, domain2)
58 | Z1 = zeros(shape=(len(domain1), len(domain2)))
59 | for i, x1 in zip(range(len(domain1)), domain1):
60 | for j, x2 in zip(range(len(domain2)), domain2):
61 | it2out, tr = myIT2FLS.evaluate({"X1":x1, "X2":x2})
62 | Z1[i, j] = crisp(tr["Y"])
63 |
64 | fig = plt.figure()
65 | ax = fig.add_subplot(111, projection="3d")
66 | surf = ax.plot_surface(X1, X2, Z1, cmap=cm.coolwarm,
67 | linewidth=0, antialiased=False)
68 | ax.zaxis.set_major_locator(LinearLocator(10))
69 | ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
70 | fig.colorbar(surf, shrink=0.5, aspect=5)
71 | plt.show()
72 |
73 |
74 |
75 |
76 |
77 |
78 |
79 |
80 |
81 |
82 |
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
--------------------------------------------------------------------------------
/examples/Sphinx docs examples/Ex8.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Sun Dec 15 17:11:44 2024
5 |
6 | @author: arslan
7 | """
8 |
9 | from pyit2fls import (IT2TSK_ML, IT2FS_Gaussian_UncertMean,
10 | IT2FS_plot, )
11 | from numpy import (linspace, array, abs, pi, sin,
12 | cos, meshgrid, zeros_like, sum,
13 | column_stack, )
14 | from numpy.random import (rand, )
15 | import matplotlib.pyplot as plt
16 | from mpl_toolkits.mplot3d import Axes3D
17 |
18 | x1 = linspace(-pi, pi, 10)
19 | x2 = linspace(-pi, pi, 10)
20 |
21 | X1, X2 = meshgrid(x1, x2)
22 |
23 | X = column_stack((X1.ravel(), X2.ravel()))
24 | y1 = sin(X1) + cos(X2)
25 | noise = 1.0 * (rand(len(X1), len(X2)) - 0.5)
26 | y2 = y1 + noise
27 |
28 | N = 2
29 | M = 4
30 |
31 | # myIT2TSK = IT2TSK_ML(N, M, IT2FS_Gaussian_UncertMean, (-pi, pi),
32 | # algorithm="ICA",
33 | # algorithm_params=[50, 100, 2.0, 0.1])
34 | # myIT2TSK = IT2TSK_ML(N, M, IT2FS_Gaussian_UncertMean, (-pi, pi),
35 | # algorithm="CSO",
36 | # algorithm_params=[50, 200, 0.25, 0.01, ])
37 | # myIT2TSK = IT2TSK_ML(N, M, IT2FS_Gaussian_UncertMean, (-pi, pi),
38 | # algorithm="FFA",
39 | # algorithm_params=[50, 200, 0.2, 1.5, 3.0])
40 | # myIT2TSK = IT2TSK_ML(N, M, IT2FS_Gaussian_UncertMean, (-pi, pi),
41 | # algorithm="WOA",
42 | # algorithm_params=[200, 100, ])
43 | # myIT2TSK = IT2TSK_ML(N, M, IT2FS_Gaussian_UncertMean, (-pi, pi),
44 | # algorithm="GWO",
45 | # algorithm_params=[200, 100, ])
46 | myIT2TSK = IT2TSK_ML(N, M, IT2FS_Gaussian_UncertMean, (-pi, pi),
47 | algorithm="PSO",
48 | algorithm_params=[200, 100, 0.3, 0.3, 2.4])
49 | # myIT2TSK = IT2TSK_ML(N, M, IT2FS_Gaussian_UncertMean, (-pi, pi),
50 | # algorithm="GA",
51 | # algorithm_params=[200, 200, 200, 100, 0.1])
52 | err, conv = myIT2TSK.fit(X, y2.ravel())
53 |
54 | y3 = myIT2TSK.score(X).reshape(X1.shape)
55 |
56 | fig = plt.figure(figsize=(6, 4))
57 | ax = fig.add_subplot(111, projection='3d')
58 | original = ax.plot_surface(X1, X2, y1, cmap="Blues",
59 | vmin=y1.min(), vmax=y1.max())
60 | fig.colorbar(original, ax=ax, shrink=0.5, aspect=10,
61 | label="Original Surface")
62 | ax.view_init(elev=10, azim=-60)
63 | ax.set_xlabel(r"$x_{1}$")
64 | ax.set_ylabel(r"$x_{2}$")
65 |
66 | plt.tight_layout()
67 | plt.savefig("example8_1.png", format="png",
68 | dpi=600, bbox_inches="tight")
69 | plt.show()
70 |
71 |
72 | fig = plt.figure(figsize=(6, 4))
73 | ax = fig.add_subplot(111, projection='3d')
74 | fitted = ax.plot_surface(X1, X2, y2, cmap="Blues",
75 | vmin=y2.min(), vmax=y2.max())
76 | fig.colorbar(fitted, ax=ax, shrink=0.5, aspect=10,
77 | label="Noisy Surface")
78 | ax.view_init(elev=10, azim=-60)
79 | ax.set_xlabel(r"$x_{1}$")
80 | ax.set_ylabel(r"$x_{2}$")
81 |
82 | plt.tight_layout()
83 | plt.savefig("example8_2.png", format="png",
84 | dpi=600, bbox_inches="tight")
85 | plt.show()
86 |
87 |
88 | fig = plt.figure(figsize=(6, 4))
89 | ax = fig.add_subplot(111, projection='3d')
90 | error_surface = ax.plot_surface(X1, X2, abs(y1 - y3),
91 | cmap="Greens", alpha=0.8)
92 | fig.colorbar(error_surface, ax=ax, shrink=0.5, aspect=10,
93 | label="Error Surface")
94 | ax.plot_surface(X1, X2, y3, cmap="Blues", alpha=0.7)
95 | ax.view_init(elev=10, azim=-60)
96 | ax.set_xlabel(r"$x_{1}$")
97 | ax.set_ylabel(r"$x_{2}$")
98 |
99 | plt.tight_layout()
100 | plt.savefig("example8_3.png", format="png",
101 | dpi=600, bbox_inches="tight")
102 | plt.show()
103 |
104 |
105 | systemData = open("data.txt", "w")
106 |
107 | for i, rule in zip(range(len(myIT2TSK.model.it2tsk.rules)),
108 | myIT2TSK.model.it2tsk.rules):
109 | IT2FS_plot(rule[0][0][1], rule[0][1][1], title=f"Rule {i+1}",
110 | legends=[r"$X_{1}$", r"$X_{2}$", ],
111 | filename=f"example8_{i+4}", ext="png")
112 | ruleText = f"Rule {i+1}: IF X1 IS [{rule[0][0][1]}] AND X2 IS [{rule[0][1][1]}] THEN Y IS [{rule[1][0][1]['const']}]"
113 | print(ruleText)
114 | systemData.write(ruleText + "\n")
115 |
116 | systemData.close()
117 |
118 | print(f"Fitting error with respect to original surface: {sum((y1 - y3) ** 2) ** 0.5}")
119 | print(f"Fitting error with respect to noisy surface: {sum((y2 - y3) ** 2) ** 0.5}")
120 |
121 |
122 |
--------------------------------------------------------------------------------
/examples/Sphinx docs examples/Ex9.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Sun Dec 15 17:11:44 2024
5 |
6 | @author: arslan
7 | """
8 |
9 | from pyit2fls import (IT2Mamdani_ML, IT2FS_Gaussian_UncertMean,
10 | IT2FS_plot, )
11 | from numpy import (linspace, array, abs, pi, sin,
12 | cos, meshgrid, zeros_like, sum,
13 | column_stack, )
14 | from numpy.random import (rand, )
15 | import matplotlib.pyplot as plt
16 | from mpl_toolkits.mplot3d import Axes3D
17 |
18 | x1 = linspace(-pi, pi, 10)
19 | x2 = linspace(-pi, pi, 10)
20 |
21 | X1, X2 = meshgrid(x1, x2)
22 |
23 | X = column_stack((X1.ravel(), X2.ravel()))
24 | y1 = sin(X1) + cos(X2)
25 | noise = 1.0 * (rand(len(X1), len(X2)) - 0.5)
26 | y2 = y1 + noise
27 |
28 | N = 2
29 | M = 4
30 |
31 |
32 | myIT2Mamdani = IT2Mamdani_ML(N, M, IT2FS_Gaussian_UncertMean, (-pi, pi),
33 | algorithm="GWO",
34 | algorithm_params=[200, 100, ])
35 |
36 | err, conv = myIT2Mamdani.fit(X, y2.ravel())
37 |
38 | y3 = myIT2Mamdani.score(X).reshape(X1.shape)
39 |
40 | fig = plt.figure(figsize=(6, 4))
41 | ax = fig.add_subplot(111, projection='3d')
42 | original = ax.plot_surface(X1, X2, y1, cmap="Blues",
43 | vmin=y1.min(), vmax=y1.max())
44 | fig.colorbar(original, ax=ax, shrink=0.5, aspect=10,
45 | label="Original Surface")
46 | ax.view_init(elev=10, azim=-60)
47 | ax.set_xlabel(r"$x_{1}$")
48 | ax.set_ylabel(r"$x_{2}$")
49 |
50 | plt.tight_layout()
51 | plt.savefig("example9_1.png", format="png",
52 | dpi=600, bbox_inches="tight")
53 | plt.show()
54 |
55 |
56 | fig = plt.figure(figsize=(6, 4))
57 | ax = fig.add_subplot(111, projection='3d')
58 | fitted = ax.plot_surface(X1, X2, y2, cmap="Blues",
59 | vmin=y2.min(), vmax=y2.max())
60 | fig.colorbar(fitted, ax=ax, shrink=0.5, aspect=10,
61 | label="Noisy Surface")
62 | ax.view_init(elev=10, azim=-60)
63 | ax.set_xlabel(r"$x_{1}$")
64 | ax.set_ylabel(r"$x_{2}$")
65 |
66 | plt.tight_layout()
67 | plt.savefig("example9_2.png", format="png",
68 | dpi=600, bbox_inches="tight")
69 | plt.show()
70 |
71 |
72 | fig = plt.figure(figsize=(6, 4))
73 | ax = fig.add_subplot(111, projection='3d')
74 | error_surface = ax.plot_surface(X1, X2, abs(y1 - y3),
75 | cmap="Greens", alpha=0.8)
76 | fig.colorbar(error_surface, ax=ax, shrink=0.5, aspect=10,
77 | label="Error Surface")
78 | ax.plot_surface(X1, X2, y3, cmap="Blues", alpha=0.7)
79 | ax.view_init(elev=10, azim=-60)
80 | ax.set_xlabel(r"$x_{1}$")
81 | ax.set_ylabel(r"$x_{2}$")
82 |
83 | plt.tight_layout()
84 | plt.savefig("example9_3.png", format="png",
85 | dpi=600, bbox_inches="tight")
86 | plt.show()
87 |
88 |
89 |
90 | systemData = open("data_Ex9.txt", "w")
91 |
92 | for i, rule in zip(range(len(myIT2Mamdani.model.it2mamdani.rules)),
93 | myIT2Mamdani.model.it2mamdani.rules):
94 | IT2FS_plot(rule[0][0][1], rule[0][1][1], rule[1][0][1], title=f"Rule {i+1}",
95 | legends=[r"$X_{1}$", r"$X_{2}$", r"$Y$", ],
96 | filename=f"example8_{i+4}", ext="png")
97 | ruleText = f"Rule {i+1}: IF X1 IS [{rule[0][0][1]}] AND X2 IS [{rule[0][1][1]}] THEN Y IS [{rule[1][0][1]}]"
98 | print(ruleText)
99 | systemData.write(ruleText + "\n")
100 |
101 | systemData.close()
102 |
103 |
104 | print(f"Fitting error with respect to original surface: {sum((y1 - y3) ** 2) ** 0.5}")
105 | print(f"Fitting error with respect to noisy surface: {sum((y2 - y3) ** 2) ** 0.5}")
106 |
107 |
--------------------------------------------------------------------------------
/examples/ddeintlib.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | This module implements ddeint, a simple Differential Delay Equation
5 | solver built on top of Scipy's odeint
6 | Created by @Zulko, https://github.com/Zulko/ddeint
7 | Improved by @Haghrah, https://github.com/Haghrah/ddeint
8 | """
9 | # REQUIRES Numpy and Scipy.
10 | import numpy as np
11 | import scipy.integrate
12 | import scipy.interpolate
13 |
14 | class ddeVar:
15 | """
16 | The instances of this class are special function-like
17 | variables which store their past values in an interpolator and
18 | can be called for any past time: Y(t), Y(t-d).
19 | Very convenient for the integration of DDEs.
20 | """
21 |
22 | def __init__(self,g,tc=0):
23 | """ g(t) = expression of Y(t) for t= 0
93 | Where func can involve past values of Y, like Y(t-d).
94 |
95 | Parameters
96 | -----------
97 |
98 | func
99 | a function Y,t,args -> Y'(t), where args is optional.
100 | The variable Y is an instance of class ddeVars (A class containing
101 | a list of ddeVar objects). It's elements are called like a
102 | function: Y[0](t), Y[0](t-d), etc. Each element of Y represents a
103 | state variable which can have a different delay value. It must be
104 | noticed that, Y[i](t) returns a number.
105 |
106 | gs
107 | The 'list of history functions'. A list of functions g(t) = Y[i](t)
108 | for t<0, g(t) returns a number.
109 |
110 | tt
111 | The vector of times [t0, t1, ...] at which the system must
112 | be solved.
113 | fargs
114 | Additional arguments to be passed to parameter ``func``, if any.
115 | Examples
116 | ---------
117 |
118 | The delay ``d`` is a tunable parameter of the model.
119 | >>> import numpy as np
120 | >>> from ddeint import ddeint
121 | >>>
122 | >>> def model(X, t, d):
123 | >>> x = X[0](t)
124 | >>> xd = X[0](t - d)
125 | >>> y = X[1](t)
126 | >>> yd = X[1](t - d)
127 | >>> return array([0.5 * x * (1 - yd), -0.5 * y * (1 - xd)])
128 | >>>
129 | >>> g1 = lambda t: 1 # 'history' at t<0 for x
130 | >>> g2 = lambda t: 2 # 'history' at t<0 for y
131 | >>> tt = np.linspace(0, 30, 20000) # times for integration
132 | >>> d = 0.5 # set parameter d
133 | >>> yy = ddeint(model, [g1, g2], tt, fargs=(d,)) # solve the DDE !
134 |
135 | """
136 |
137 | dde_ = dde(func)
138 | dde_.set_initial_value(ddeVars(gs,tt[0]))
139 | dde_.set_f_params(fargs if fargs else [])
140 | results = [np.array([g(tt[0]) for g in gs])]
141 | results.extend(dde_.integrate(dde_.t + dt) for dt in np.diff(tt))
142 | return np.array(results)
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
--------------------------------------------------------------------------------
/examples/ex_1.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Sat Apr 27 17:12:04 2019
5 |
6 | @author: arslan
7 | """
8 |
9 |
10 | from pyit2fls import IT2FS, trapezoid_mf, tri_mf
11 | from numpy import linspace
12 |
13 | # Defining an interval type 2 fuzzy set with trapezoidal UMF and triangular LMF
14 | domain = linspace(0., 1., 100) # Domain is defined as discrete space in the
15 | # interval [0, 1] divided to 100 parts.
16 | mySet = IT2FS(domain,
17 | trapezoid_mf, [0, 0.4, 0.6, 1., 1.], # Trapezoidal UMF with
18 | # left = 0.,
19 | # center left = 0.4,
20 | # center right = 0.6,
21 | # right = 1.,
22 | # and height = 1.
23 | tri_mf, [0.25, 0.5, 0.75, 0.6]) # Triangular LMF with
24 | # left = 0.25,
25 | # center = 0.5,
26 | # right = 0.75,
27 | # and height = 0.6.
28 | mySet.plot(filename="mySet") # Plotting the set and saving to the file,
29 | # named mySet.
30 |
31 |
--------------------------------------------------------------------------------
/examples/ex_10.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Sun Sep 13 10:24:56 2020
5 |
6 | @author: arslan
7 | """
8 |
9 | from pyit2fls import IT2Mamdani, IT2FS_Gaussian_UncertStd, IT2FS_plot, \
10 | product_t_norm, max_s_norm, crisp
11 | from numpy import linspace, random, sin, cos, array
12 |
13 | domainX1 = linspace(-1., 1., 101)
14 | domainX2 = linspace(-1., 1., 101)
15 | domainY1 = linspace(-0.5, 1.5, 101)
16 | domainY2 = linspace(-0.5, 1.5, 101)
17 |
18 | X1Small = IT2FS_Gaussian_UncertStd(domainX1, [-1., 0.2, 0.1, 1.])
19 | X1Medium = IT2FS_Gaussian_UncertStd(domainX1, [0., 0.2, 0.1, 1.])
20 | X1Large = IT2FS_Gaussian_UncertStd(domainX1, [1., 0.2, 0.1, 1.])
21 | # IT2FS_plot(X1Small, X1Medium, X1Large)
22 |
23 | X2Small = IT2FS_Gaussian_UncertStd(domainX2, [-1., 0.2, 0.1, 1.])
24 | X2Medium = IT2FS_Gaussian_UncertStd(domainX2, [0., 0.2, 0.1, 1.])
25 | X2Large = IT2FS_Gaussian_UncertStd(domainX2, [1., 0.2, 0.1, 1.])
26 | # IT2FS_plot(X2Small, X2Medium, X2Large)
27 |
28 | Y1Small = IT2FS_Gaussian_UncertStd(domainY1, [-0.5, 0.2, 0.1, 1.])
29 | Y1Medium = IT2FS_Gaussian_UncertStd(domainY1, [0.5, 0.2, 0.1, 1.])
30 | Y1Large = IT2FS_Gaussian_UncertStd(domainY1, [1.5, 0.2, 0.1, 1.])
31 | # IT2FS_plot(Y1Small, Y1Medium, Y1Large)
32 |
33 | Y2Small = IT2FS_Gaussian_UncertStd(domainY2, [-0.5, 0.2, 0.1, 1.])
34 | Y2Medium = IT2FS_Gaussian_UncertStd(domainY2, [0.5, 0.2, 0.1, 1.])
35 | Y2Large = IT2FS_Gaussian_UncertStd(domainY2, [1., 0.2, 0.1, 1.])
36 | # IT2FS_plot(Y2Small, Y2Medium, Y2Large)
37 |
38 | myIT2FLS = IT2Mamdani(product_t_norm, max_s_norm, method="CoSet")
39 | myIT2FLS.add_input_variable("x1")
40 | myIT2FLS.add_input_variable("x2")
41 | myIT2FLS.add_output_variable("y1")
42 | myIT2FLS.add_output_variable("y2")
43 |
44 | nX1 = 3
45 | X1Sets = [X1Small, X1Medium, X1Large]
46 | nX2 = 3
47 | X2Sets = [X2Small, X2Medium, X2Large]
48 | nY1 = 3
49 | Y1Sets = [Y1Small, Y1Medium, Y1Large]
50 | nY2 = 3
51 | Y2Sets = [Y2Small, Y2Medium, Y2Large]
52 |
53 | def generateRuleBase():
54 | Rules = []
55 | for i in range(9):
56 | rule = [i // nX1, i % nX2,
57 | random.randint(nY1), random.randint(nY2)]
58 | Rules.append(rule)
59 | return Rules
60 |
61 |
62 | tt = 2 * (random.rand(20) - 0.5)
63 | Data = array([sin(tt),
64 | cos(tt),
65 | sin(tt) + cos(tt),
66 | cos(tt) - sin(tt)])
67 |
68 | def error(R, D):
69 | # R: Rules
70 | # D: Data
71 | err = 0.
72 | myIT2FLS.rules = []
73 | for rule in R:
74 | myIT2FLS.add_rule([("x1", X1Sets[rule[0]]), ("x2", X2Sets[rule[1]])],
75 | [("y1", Y1Sets[rule[2]]), ("y2", Y2Sets[rule[3]])])
76 | for i in range(D.shape[1]):
77 | tr = myIT2FLS.evaluate({"x1":D[0, i], "x2":D[1, i]})
78 | err += (crisp(tr["y1"]) - D[2, i]) ** 2 + (crisp(tr["y2"]) - D[3, i]) ** 2
79 | return err
80 |
81 | if __name__ == "__main__":
82 | myRules = [[0, 0, 0, 1],
83 | [0, 1, 0, 2],
84 | [0, 2, 1, 2],
85 | [1, 0, 0, 0],
86 | [1, 1, 1, 1],
87 | [1, 2, 2, 2],
88 | [2, 0, 1, 0],
89 | [2, 1, 2, 0],
90 | [2, 2, 2, 1]]
91 | minErr = float("inf")
92 | minRules = []
93 | for i in range(100):
94 | rule = generateRuleBase()
95 | err = error(rule, Data)
96 | if err < minErr:
97 | minErr = err
98 | minRules = rule
99 | print(str(i) + ".", err)
100 |
101 | print("Best generated rule base:")
102 | print(minRules)
103 | print("Minimum error:", minErr)
104 |
105 | print("Rule base defined by expert:")
106 | print(myRules)
107 | print("Error:", error(myRules, Data))
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
126 |
127 |
128 |
129 |
130 |
131 |
132 |
133 |
134 |
135 |
136 |
--------------------------------------------------------------------------------
/examples/ex_11.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Sat Nov 14 18:16:26 2020
5 |
6 | @author: arslan
7 | """
8 |
9 | from pyit2fls import IT2FS_Gaussian_UncertMean, meet, IT2FS_plot, \
10 | min_t_norm, product_t_norm, lukasiewicz_t_norm, \
11 | drastic_t_norm, nilpotent_minimum_t_norm, hamacher_product_t_norm
12 | from numpy import linspace
13 |
14 |
15 | domain = linspace(-1., 7., 8001)
16 | A1 = IT2FS_Gaussian_UncertMean(domain, [0., 0.2, 0.5, 1.])
17 | A2 = IT2FS_Gaussian_UncertMean(domain, [1., 0.2, 0.5, 1.])
18 | A3 = IT2FS_Gaussian_UncertMean(domain, [2., 0.2, 0.5, 1.])
19 | A4 = IT2FS_Gaussian_UncertMean(domain, [3., 0.2, 0.5, 1.])
20 | A5 = IT2FS_Gaussian_UncertMean(domain, [4., 0.2, 0.5, 1.])
21 | A6 = IT2FS_Gaussian_UncertMean(domain, [5., 0.2, 0.5, 1.])
22 | A7 = IT2FS_Gaussian_UncertMean(domain, [6., 0.2, 0.5, 1.])
23 | IT2FS_plot(A1, A2, A3, A4, A5, A6, A7, title="Sets",
24 | legends=["Set 1", "Set 2", "Set 3", "Set 4",
25 | "Set 5", "Set 6", "Set 7"])
26 |
27 | M1 = meet(domain, A1, A2, min_t_norm)
28 | M2 = meet(domain, A2, A3, product_t_norm)
29 | M3 = meet(domain, A3, A4, lukasiewicz_t_norm)
30 | M4 = meet(domain, A4, A5, drastic_t_norm)
31 | M5 = meet(domain, A5, A6, nilpotent_minimum_t_norm)
32 | M6 = meet(domain, A6, A7, hamacher_product_t_norm)
33 |
34 | IT2FS_plot(M1, M2, M3, M4, M5, M6,
35 | legends=["Minimum (1, 2)", "Product (2, 3)",
36 | "Lukasiewicz (3, 4)", "Drastic (4, 5)",
37 | "Nilpotent Minimum (5, 6)", "Hamacher Product (6, 7)"])
38 |
39 |
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
--------------------------------------------------------------------------------
/examples/ex_12.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Sat Nov 14 18:16:26 2020
5 |
6 | @author: arslan
7 | """
8 |
9 | from pyit2fls import IT2FS_Gaussian_UncertMean, join, IT2FS_plot, \
10 | max_s_norm, probabilistic_sum_s_norm, bounded_sum_s_norm, \
11 | drastic_s_norm, nilpotent_maximum_s_norm, einstein_sum_s_norm
12 | from numpy import linspace
13 |
14 |
15 | domain = linspace(-1., 7., 8001)
16 | A1 = IT2FS_Gaussian_UncertMean(domain, [0., 0.2, 0.25, 1.])
17 | A2 = IT2FS_Gaussian_UncertMean(domain, [1., 0.2, 0.25, 1.])
18 | A3 = IT2FS_Gaussian_UncertMean(domain, [2., 0.2, 0.25, 1.])
19 | A4 = IT2FS_Gaussian_UncertMean(domain, [3., 0.2, 0.25, 1.])
20 | A5 = IT2FS_Gaussian_UncertMean(domain, [4., 0.2, 0.25, 1.])
21 | A6 = IT2FS_Gaussian_UncertMean(domain, [5., 0.2, 0.25, 1.])
22 | A7 = IT2FS_Gaussian_UncertMean(domain, [6., 0.2, 0.25, 1.])
23 | IT2FS_plot(A1, A2, A3, A4, A5, A6, A7, title="Sets",
24 | legends=["Set 1", "Set 2", "Set 3", "Set 4",
25 | "Set 5", "Set 6", "Set 7"])
26 |
27 | M1 = join(domain, A1, A2, max_s_norm)
28 | M2 = join(domain, A2, A3, probabilistic_sum_s_norm)
29 | M3 = join(domain, A3, A4, bounded_sum_s_norm)
30 | M4 = join(domain, A4, A5, drastic_s_norm)
31 | M5 = join(domain, A5, A6, nilpotent_maximum_s_norm)
32 | M6 = join(domain, A6, A7, einstein_sum_s_norm)
33 |
34 | IT2FS_plot(M1, M3, M5,
35 | legends=["Maximum (1, 2)",
36 | "Bounded Sum (3, 4)",
37 | "Nilpotent Maximum (5, 6)", ], )
38 |
39 | IT2FS_plot(M2, M4, M6,
40 | legends=["Probabilistic Sum (2, 3)",
41 | "Drastic (4, 5)",
42 | "Einstein Sum (6, 7)"], )
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
--------------------------------------------------------------------------------
/examples/ex_13.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Fri Nov 27 22:25:30 2020
5 |
6 | @author: arslan
7 | """
8 |
9 | from numpy import (linspace, meshgrid, zeros, )
10 | from pyit2fls import (T1FS, T1Mamdani, T1FS_plot, gaussian_mf, )
11 | from mpl_toolkits import mplot3d
12 | import matplotlib.pyplot as plt
13 | from matplotlib import cm
14 | from matplotlib.ticker import (LinearLocator, FormatStrFormatter, )
15 |
16 | # Defining the domain of the input variable x1.
17 | domain1 = linspace(1., 2., 201)
18 |
19 | # Defining the domain of the input variable x2.
20 | domain2 = linspace(2., 3., 201)
21 |
22 | # Defining the domain of the output variable y1.
23 | domain3 = linspace(3., 4., 201)
24 |
25 | # Defining the domain of the output variable y2.
26 | domain4 = linspace(4., 5., 201)
27 |
28 | SMALL1 = T1FS(domain1, gaussian_mf, [1.0, 0.3, 1.])
29 | MEDIUM1 = T1FS(domain1, gaussian_mf, [1.5, 0.2, 1.])
30 | LARGE1 = T1FS(domain1, gaussian_mf, [2.0, 0.5, 1.])
31 |
32 | T1FS_plot(SMALL1, MEDIUM1, LARGE1, legends=["Small", "Medium", "Large"])
33 |
34 | SMALL2 = T1FS(domain2, gaussian_mf, [2.0, 0.5, 1.])
35 | MEDIUM2 = T1FS(domain2, gaussian_mf, [2.5, 0.2, 1.])
36 | LARGE2 = T1FS(domain2, gaussian_mf, [3.0, 0.3, 1.])
37 |
38 | T1FS_plot(SMALL2, MEDIUM2, LARGE2, legends=["Small", "Medium", "Large"])
39 |
40 | LOW1 = T1FS(domain3, gaussian_mf, [3.0, 0.3, 1.])
41 | HIGH1 = T1FS(domain3, gaussian_mf, [4.0, 0.6, 1.])
42 |
43 | T1FS_plot(LOW1, HIGH1, legends=["Low", "High"])
44 |
45 | LOW2 = T1FS(domain4, gaussian_mf, [4.0, 0.6, 1.])
46 | HIGH2 = T1FS(domain4, gaussian_mf, [5.0, 0.3, 1.])
47 |
48 | T1FS_plot(LOW2, HIGH2, legends=["Low", "High"])
49 |
50 | SYS = T1Mamdani(engine="Product", defuzzification="CoG")
51 | SYS.add_input_variable("x1")
52 | SYS.add_input_variable("x2")
53 | SYS.add_output_variable("y1")
54 | SYS.add_output_variable("y2")
55 |
56 | SYS.add_rule([("x1", SMALL1), ("x2", SMALL2)], [("y1", LOW1), ("y2", LOW2)])
57 | SYS.add_rule([("x1", SMALL1), ("x2", MEDIUM2)], [("y1", LOW1), ("y2", HIGH2)])
58 | SYS.add_rule([("x1", SMALL1), ("x2", LARGE2)], [("y1", LOW1), ("y2", LOW2)])
59 | SYS.add_rule([("x1", MEDIUM1), ("x2", SMALL2)], [("y1", HIGH1), ("y2", LOW2)])
60 | SYS.add_rule([("x1", MEDIUM1), ("x2", MEDIUM2)], [("y1", LOW1), ("y2", HIGH2)])
61 | SYS.add_rule([("x1", MEDIUM1), ("x2", LARGE2)], [("y1", HIGH1), ("y2", LOW2)])
62 | SYS.add_rule([("x1", LARGE1), ("x2", SMALL2)], [("y1", HIGH1), ("y2", HIGH2)])
63 | SYS.add_rule([("x1", LARGE1), ("x2", MEDIUM2)], [("y1", LOW1), ("y2", LOW2)])
64 | SYS.add_rule([("x1", LARGE1), ("x2", LARGE2)], [("y1", HIGH1), ("y2", HIGH2)])
65 |
66 | X1, X2 = meshgrid(domain1, domain2)
67 | Z1 = zeros(shape=(len(domain1), len(domain2)))
68 | Z2 = zeros(shape=(len(domain1), len(domain2)))
69 | for i, x1 in zip(range(len(domain1)), domain1):
70 | for j, x2 in zip(range(len(domain2)), domain2):
71 | s, c = SYS.evaluate({"x1":x1, "x2":x2})
72 | Z1[i, j], Z2[i, j] = c["y1"], c["y2"]
73 |
74 | fig = plt.figure()
75 | ax = fig.add_subplot(111, projection="3d")
76 | surf = ax.plot_surface(X1, X2, Z1, cmap=cm.coolwarm,
77 | linewidth=0, antialiased=False)
78 | ax.zaxis.set_major_locator(LinearLocator(10))
79 | ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
80 | fig.colorbar(surf, shrink=0.5, aspect=5)
81 | plt.show()
82 |
83 | fig = plt.figure()
84 | ax = fig.add_subplot(111, projection="3d")
85 | surf = ax.plot_surface(X1, X2, Z2, cmap=cm.coolwarm,
86 | linewidth=0, antialiased=False)
87 | ax.zaxis.set_major_locator(LinearLocator(10))
88 | ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
89 | fig.colorbar(surf, shrink=0.5, aspect=5)
90 | plt.show()
91 |
92 |
93 |
--------------------------------------------------------------------------------
/examples/ex_14.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Sat Nov 28 10:32:55 2020
5 |
6 | @author: arslan
7 | """
8 |
9 |
10 | from pyit2fls import T1FS, gaussian_mf, T1FS_plot, T1TSK
11 | from mpl_toolkits import mplot3d
12 | import matplotlib.pyplot as plt
13 | from matplotlib import cm
14 | from matplotlib.ticker import LinearLocator, FormatStrFormatter
15 | from numpy import linspace, meshgrid, zeros
16 | from time import time
17 |
18 | #%%
19 | # The universe of discourse for all input variables are same -> [0, 1)
20 | domain = linspace(0., 1., 100)
21 |
22 |
23 | #%%
24 | # The fuzzy system will be evaluated in the [0, 1) x [0, 1) space.
25 | X1, X2 = meshgrid(domain, domain)
26 |
27 |
28 | # %%
29 | # Eight functions are defined, that are used in consequence
30 | # part of the rules in the fuzzy rule-base.
31 | def y11(x1, x2):
32 | return x1 + x2 + 1.
33 |
34 | def y12(x1, x2):
35 | return 2. * x1 - x2 + 1.
36 |
37 | def y21(x1, x2):
38 | return 1.5 * x1 + 0.5 * x2 + 0.5
39 |
40 | def y22(x1, x2):
41 | return 1.5 * x1 - 0.5 * x2 + 0.5
42 |
43 | def y31(x1, x2):
44 | return 2. * x1 + 0.1 * x2 - 0.2
45 |
46 | def y32(x1, x2):
47 | return 0.5 * x1 + 0.1 * x2 + 0.
48 |
49 | def y41(x1, x2):
50 | return 4. * x1 - 0.5 * x2 - 1.
51 |
52 | def y42(x1, x2):
53 | return -0.5 * x1 + x2 - 0.5
54 |
55 |
56 | # %%
57 | # Defined surfaces for being used in consequence part of rules are
58 | # evaluated and plotted here:
59 | Y11 = y11(X1, X2)
60 | Y12 = y12(X1, X2)
61 | Y21 = y21(X1, X2)
62 | Y22 = y22(X1, X2)
63 | Y31 = y31(X1, X2)
64 | Y32 = y32(X1, X2)
65 | Y41 = y41(X1, X2)
66 | Y42 = y42(X1, X2)
67 |
68 | fig = plt.figure(figsize=plt.figaspect(0.25))
69 | ax = fig.add_subplot(1, 4, 1, projection="3d")
70 | surf = ax.plot_surface(X1, X2, Y11, cmap=cm.coolwarm,
71 | linewidth=0, antialiased=False)
72 | ax = fig.add_subplot(1, 4, 2, projection="3d")
73 | surf = ax.plot_surface(X1, X2, Y21, cmap=cm.coolwarm,
74 | linewidth=0, antialiased=False)
75 | ax = fig.add_subplot(1, 4, 3, projection="3d")
76 | surf = ax.plot_surface(X1, X2, Y31, cmap=cm.coolwarm,
77 | linewidth=0, antialiased=False)
78 | ax = fig.add_subplot(1, 4, 4, projection="3d")
79 | surf = ax.plot_surface(X1, X2, Y41, cmap=cm.coolwarm,
80 | linewidth=0, antialiased=False)
81 | plt.show()
82 |
83 | fig = plt.figure(figsize=plt.figaspect(0.25))
84 | ax = fig.add_subplot(1, 4, 1, projection="3d")
85 | surf = ax.plot_surface(X1, X2, Y12, cmap=cm.coolwarm,
86 | linewidth=0, antialiased=False)
87 | ax = fig.add_subplot(1, 4, 2, projection="3d")
88 | surf = ax.plot_surface(X1, X2, Y22, cmap=cm.coolwarm,
89 | linewidth=0, antialiased=False)
90 | ax = fig.add_subplot(1, 4, 3, projection="3d")
91 | surf = ax.plot_surface(X1, X2, Y32, cmap=cm.coolwarm,
92 | linewidth=0, antialiased=False)
93 | ax = fig.add_subplot(1, 4, 4, projection="3d")
94 | surf = ax.plot_surface(X1, X2, Y42, cmap=cm.coolwarm,
95 | linewidth=0, antialiased=False)
96 | plt.show()
97 |
98 |
99 | # %%
100 | # The fuzzy sets representing the universe of discourse of the
101 | # fuzzy system are defined and plotted here:
102 | Small = T1FS(domain, gaussian_mf, [0, 0.15, 1.])
103 | Big = T1FS(domain, gaussian_mf, [1., 0.15, 1.])
104 |
105 | T1FS_plot(Small, Big, title="Sets",
106 | legends=["Small", "Big"])
107 |
108 | # The fuzzy system is created using the T1TSK class:
109 | SYS = T1TSK()
110 |
111 | # Input and output variables are defined and added to the fuzzy system.
112 | SYS.add_input_variable("x1")
113 | SYS.add_input_variable("x2")
114 | SYS.add_output_variable("y1")
115 | SYS.add_output_variable("y2")
116 |
117 | # Rule-base of the fuzzy system is defined here:
118 | # The previously defined functions (yij) are used here.
119 | SYS.add_rule([("x1", Small), ("x2", Small)],
120 | [("y1", y11),
121 | ("y2", y12)])
122 | SYS.add_rule([("x1", Small), ("x2", Big)],
123 | [("y1", y21),
124 | ("y2", y22)])
125 | SYS.add_rule([("x1", Big), ("x2", Small)],
126 | [("y1", y31),
127 | ("y2", y32)])
128 | SYS.add_rule([("x1", Big), ("x2", Big)],
129 | [("y1", y41),
130 | ("y2", y42)])
131 |
132 |
133 | # %%
134 | # The output planes of the fuzzy system are evaluated and plotted here:
135 | Z1 = zeros(shape=X1.shape)
136 | Z2 = zeros(shape=X1.shape)
137 |
138 | for i, x1 in zip(range(len(domain)), domain):
139 | for j, x2 in zip(range(len(domain)), domain):
140 | # The params input of the evaluate function indicates the inputs of
141 | # the functions given in the consequence part of the rules.
142 | z = SYS.evaluate({"x1":x1, "x2":x2}, params=(x1, x2))
143 | Z1[i, j], Z2[i, j] = z["y1"], z["y2"]
144 |
145 |
146 | fig = plt.figure()
147 | ax = fig.add_subplot(111, projection="3d")
148 | surf = ax.plot_surface(X1, X2, Z1, cmap=cm.coolwarm,
149 | linewidth=0, antialiased=False)
150 | ax.zaxis.set_major_locator(LinearLocator(10))
151 | ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
152 | fig.colorbar(surf, shrink=0.5, aspect=5)
153 | plt.show()
154 |
155 | fig = plt.figure()
156 | ax = fig.add_subplot(111, projection="3d")
157 | surf = ax.plot_surface(X1, X2, Z2, cmap=cm.coolwarm,
158 | linewidth=0, antialiased=False)
159 | ax.zaxis.set_major_locator(LinearLocator(10))
160 | ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
161 | fig.colorbar(surf, shrink=0.5, aspect=5)
162 | plt.show()
163 |
164 |
165 |
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 |
--------------------------------------------------------------------------------
/examples/ex_15.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Fri Apr 9 20:10:33 2021
5 |
6 | @author: arslan
7 | """
8 |
9 | from pyit2fls import (IT2FS_Gaussian_UncertMean, IT2FS_Emphasize, IT2FS_plot,
10 | T1FS, gaussian_mf, T1FS_Emphasize, T1FS_plot)
11 | from numpy import linspace
12 |
13 | domain = linspace(0., 1., 101)
14 |
15 |
16 | IT2mySet = IT2FS_Gaussian_UncertMean(domain, [0.5, 0.1, 0.2, 1.], check_set=True)
17 | IT2Emphasized_mySet = IT2FS_Emphasize(IT2mySet, m=3.)
18 | IT2FS_plot(IT2mySet, IT2Emphasized_mySet, legends=["Simple", "Emphasized"])
19 |
20 |
21 | T1mySet = T1FS(domain, mf=gaussian_mf, params=[0.5, 0.1, 1.])
22 | T1Emphasized_mySet = T1FS_Emphasize(T1mySet, m=3.)
23 | T1FS_plot(T1mySet, T1Emphasized_mySet, legends=["Simple", "Emphasized"])
24 |
25 |
26 |
27 |
28 |
--------------------------------------------------------------------------------
/examples/ex_16.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Sat May 1 02:51:58 2021
5 |
6 | @author: arslan
7 | """
8 | from numpy import (array, random, linspace, )
9 | from pyit2fls import (T1FS, gaussian_mf, min_t_norm, max_s_norm,
10 | product_t_norm, T1FMatrix, T1FMatrix_Intersection,
11 | T1FMatrix_Union, Minmax, Maxmin, T1FSoftMatrix,
12 | T1FMatrix_Complement, T1FSoftMatrix_Product)
13 |
14 | matrix = random.rand(3, 3)
15 | domain = linspace(0., 1., 101)
16 | A = T1FS(domain, mf=gaussian_mf, params=[0.6, 0.2, 1.])
17 | B = T1FS(domain, mf=gaussian_mf, params=[0.4, 0.2, 1.])
18 | t1fmatrix1 = T1FMatrix(matrix, A)
19 | t1fmatrix2 = T1FMatrix(matrix, B)
20 | print("Matrix 1:\n", t1fmatrix1)
21 | print("Matrix 2:\n", t1fmatrix2)
22 | print("-------------------")
23 | print("Intersection of matrices:\n", T1FMatrix_Intersection(t1fmatrix1, t1fmatrix2, min_t_norm))
24 | print("Union of matrices:\n", T1FMatrix_Union(t1fmatrix1, t1fmatrix2, max_s_norm))
25 | print("-------------------")
26 | print("Minimum-Maximum of matrices:\n", Minmax(t1fmatrix1, t1fmatrix2))
27 | print("Maximum-Minimum of matrices:\n", Maxmin(t1fmatrix1, t1fmatrix2))
28 | print("-------------------")
29 |
30 | t1fsoftmatrix = T1FSoftMatrix([0.1, 0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8, 0.9],
31 | [A, B])
32 | print(t1fsoftmatrix)
33 | print(T1FMatrix_Complement(t1fsoftmatrix))
34 | print("-------------------")
35 |
36 | A1 = array([[0.3, 0.2, 0.1],
37 | [0.5, 0.4, 0.2],
38 | [0.6, 0.5, 0.7],
39 | [0.4, 0.6, 0.8],
40 | [0.8, 0.6, 0.3]])
41 | A2 = array([[0.7, 0.2, 0.5],
42 | [0.6, 0.4, 0.9],
43 | [0.7, 0.8, 0.6],
44 | [0.5, 0.6, 1.0],
45 | [0.4, 0.5, 0.7]])
46 | A3 = array([[0.5, 0.4, 0.6],
47 | [0.4, 0.7, 0.6],
48 | [0.6, 0.5, 0.5],
49 | [0.8, 0.6, 0.4],
50 | [0.5, 0.6, 0.5]])
51 | print(T1FSoftMatrix_Product(5, 3, product_t_norm, A1, A2, A3))
52 | print("-------------------")
53 |
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
--------------------------------------------------------------------------------
/examples/ex_17.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Sun Jun 20 11:51:49 2021
5 |
6 | @author: arslan
7 | """
8 |
9 |
10 | from pyit2fls import (IT2FS_Gaussian_UncertStd, IT2FS_LGaussian_UncertStd,
11 | IT2FS_RGaussian_UncertStd, IT2Mamdani, product_t_norm,
12 | probabilistic_sum_s_norm, IT2FS_plot, crisp, )
13 |
14 | from numpy import (random, linspace, array, zeros, shape, sort,
15 | maximum, minimum, )
16 | from scipy.optimize import (differential_evolution, minimize, basinhopping, )
17 | from PyIT2FLSPSO import PyPSO
18 |
19 | class Classifier:
20 |
21 | def normalizeParameters(self, parameters, n=3):
22 | p = zeros(shape=(3 * n + 2 + 3 ** n, ))
23 |
24 | for i in range(n):
25 | p[3 * i:3 * (i + 1)] = sort(parameters[3 * i:3 * (i + 1)])
26 |
27 | p[3 * n:3 * n + 2] = maximum(0., minimum(1., sort(parameters[3 * n:3 * n + 2])))
28 |
29 | p[3 * n + 2:] = parameters[3 * n + 2:] > 0
30 |
31 | return p
32 |
33 | def __init__(self, attributes, decisions, parameters, n=3):
34 | self.attributes = attributes
35 | self.decisions = decisions
36 | self.p = self.normalizeParameters(parameters)
37 |
38 | self.idomain = linspace(-1.0, 1.0, 1001)
39 | self.odomain = linspace( 0.0, 1.0, 1001)
40 |
41 | self.att1_s1 = IT2FS_RGaussian_UncertStd(self.idomain, params=[self.p[0],
42 | 0.25, 0.05, 1.0])
43 | self.att1_s2 = IT2FS_Gaussian_UncertStd(self.idomain, params=[self.p[1],
44 | 0.25, 0.05, 1.0])
45 | self.att1_s3 = IT2FS_LGaussian_UncertStd(self.idomain, params=[self.p[2],
46 | 0.25, 0.05, 1.0])
47 | self.ATT1_SETS = [self.att1_s1, self.att1_s2, self.att1_s3]
48 |
49 |
50 | self.att2_s1 = IT2FS_RGaussian_UncertStd(self.idomain, params=[self.p[3],
51 | 0.25, 0.05, 1.0])
52 | self.att2_s2 = IT2FS_Gaussian_UncertStd(self.idomain, params=[self.p[4],
53 | 0.25, 0.05, 1.0])
54 | self.att2_s3 = IT2FS_LGaussian_UncertStd(self.idomain, params=[self.p[5],
55 | 0.25, 0.05, 1.0])
56 | self.ATT2_SETS = [self.att2_s1, self.att2_s2, self.att2_s3]
57 |
58 |
59 | self.att3_s1 = IT2FS_RGaussian_UncertStd(self.idomain, params=[self.p[6],
60 | 0.25, 0.05, 1.0])
61 | self.att3_s2 = IT2FS_Gaussian_UncertStd(self.idomain, params=[self.p[7],
62 | 0.25, 0.05, 1.0])
63 | self.att3_s3 = IT2FS_LGaussian_UncertStd(self.idomain, params=[self.p[8],
64 | 0.25, 0.05, 1.0])
65 | self.ATT3_SETS = [self.att3_s1, self.att3_s2, self.att3_s3]
66 |
67 |
68 | self.deci_s1 = IT2FS_RGaussian_UncertStd(self.odomain, params=[self.p[9],
69 | 0.25, 0.05, 1.0])
70 | self.deci_s2 = IT2FS_LGaussian_UncertStd(self.odomain, params=[self.p[10],
71 | 0.25, 0.05, 1.0])
72 | self.DECI_SETS = [self.deci_s1, self.deci_s2]
73 |
74 |
75 | self.DM = IT2Mamdani(product_t_norm, probabilistic_sum_s_norm)
76 |
77 | self.DM.add_input_variable("ATT1")
78 | self.DM.add_input_variable("ATT2")
79 | self.DM.add_input_variable("ATT3")
80 |
81 | self.DM.add_output_variable("DECI")
82 |
83 |
84 | for i in range(3):
85 | for j in range(3):
86 | for k in range(3):
87 | self.DM.add_rule([("ATT1", self.ATT1_SETS[i]),
88 | ("ATT2", self.ATT2_SETS[j]),
89 | ("ATT3", self.ATT3_SETS[k])],
90 | [("DECI", self.DECI_SETS[int(self.p[11 + i * 9 + j * 3 + k])])])
91 |
92 | def __call__(self, att1, att2, att3):
93 | o, tr = self.DM.evaluate({"ATT1": att1, "ATT2": att2, "ATT3": att3})
94 | return crisp(tr["DECI"])
95 |
96 | def error(self):
97 | err = 0.
98 | for attribute, decision in zip(self.attributes, self.decisions):
99 | o = self.__call__(*attribute)
100 | if o > 0.51 and decision != 1:
101 | err += o - 0.51
102 | elif o < 0.49 and decision != 0:
103 | err += 0.49 - o
104 | return err / len(self.decisions)
105 |
106 | if __name__ == "__main__":
107 |
108 | def parametersGenerator(n=3):
109 | return 2 * (random.rand(3 * n + 2 + 3 ** n) - 0.5)
110 |
111 | def velocityGenerator(n=3):
112 | return 4. * (random.rand(3 * n + 2 + 3 ** n) - 0.5)
113 |
114 |
115 | attributes = array([[-0.4, -0.3, -0.5],
116 | [-0.4, 0.2, -0.1],
117 | [-0.3, -0.4, -0.3],
118 | [ 0.3, -0.3, 0.0],
119 | [ 0.2, -0.3, 0.0],
120 | [ 0.2, 0.0, 0.0]])
121 | decisions = array([1, 0, 1, 0, 0, 1])
122 |
123 | def error(p):
124 | myClassifier = Classifier(attributes, decisions, p)
125 | return myClassifier.error()
126 |
127 | mySolver= PyPSO(error, 5, 100, parametersGenerator, velocityGenerator)
128 | mySolver.solve()
129 |
130 | p = mySolver.best_known_position
131 |
132 | myClassifier = Classifier(attributes, decisions, p)
133 | IT2FS_plot(myClassifier.att1_s1, myClassifier.att1_s2, myClassifier.att1_s3)
134 | IT2FS_plot(myClassifier.att2_s1, myClassifier.att2_s2, myClassifier.att2_s3)
135 | IT2FS_plot(myClassifier.att3_s1, myClassifier.att3_s2, myClassifier.att3_s3)
136 | IT2FS_plot(myClassifier.deci_s1, myClassifier.deci_s2)
137 |
138 | print(myClassifier.error())
139 |
140 |
141 |
142 |
143 |
144 |
145 |
146 |
147 |
148 |
149 |
150 |
151 |
152 |
153 |
154 |
155 |
156 |
157 |
158 |
159 |
160 |
161 |
162 |
163 |
164 |
165 |
166 |
167 |
--------------------------------------------------------------------------------
/examples/ex_18.py:
--------------------------------------------------------------------------------
1 | from pyit2fls import (T1TSK_ML, T1FS_plot, )
2 | from numpy import (linspace, array, abs, pi, sin, cos, meshgrid, zeros_like, )
3 | from scipy.optimize import (Bounds, )
4 | import matplotlib.pyplot as plt
5 | from mpl_toolkits.mplot3d import Axes3D
6 |
7 | X1 = linspace(-pi, pi, 10)
8 | X2 = linspace(-pi, pi, 10)
9 |
10 | X = []
11 | y = []
12 | for x1 in X1:
13 | for x2 in X2:
14 | X.append([x1, x2])
15 | y.append(sin(x1) + cos(x2))
16 | X = array(X)
17 |
18 | N = 2
19 | M = 4
20 | myTSK = T1TSK_ML(N, M, (-4., 4.), algorithm="PSO",
21 | algorithm_params=[200, 200, 0.3, 0.3, 1.8])
22 | print(myTSK.fit(X, y))
23 |
24 | x1, x2 = meshgrid(X1, X2)
25 | y1 = sin(x1) + cos(x2)
26 | y2 = zeros_like(y1)
27 | for i in range(10):
28 | for j in range(10):
29 | y2[i, j] = myTSK.score(array([X1[j], X2[i], ]))
30 |
31 |
32 | fig = plt.figure()
33 | ax = fig.add_subplot(111, projection="3d")
34 | original = ax.plot_surface(x1, x2, y1, cmap="viridis", vmin=y1.min(), vmax=y1.max())
35 | fig.colorbar(original, ax=ax, shrink=0.5, aspect=10, )
36 | ax.set_title("Original function")
37 | plt.show()
38 |
39 | fig = plt.figure()
40 | ax = fig.add_subplot(111, projection="3d")
41 | fitted = ax.plot_surface(x1, x2, y2, cmap="viridis", vmin=y1.min(), vmax=y1.max())
42 | fig.colorbar(fitted, ax=ax, shrink=0.5, aspect=10, )
43 | ax.set_title("Fitted function")
44 | plt.show()
45 |
46 | fig = plt.figure()
47 | ax = fig.add_subplot(111, projection="3d")
48 | error_surface = ax.plot_surface(x1, x2, abs(y2 - y1), cmap="Greens", alpha=0.8)
49 | fig.colorbar(error_surface, ax=ax, shrink=0.5, aspect=10,
50 | label="Error")
51 | ax.plot_surface(x1, x2, y1, cmap="Blues", alpha=0.7)
52 | ax.set_title("3D Surface Plot")
53 | plt.show()
54 |
55 |
56 | achievedSystem = myTSK.get_T1TSK()
57 | for r, rule in zip(range(M), achievedSystem.rules):
58 | sets = []
59 | labels = []
60 | for i in range(N):
61 | sets.append(rule[0][i][1])
62 | labels.append(f"X{i}")
63 | T1FS_plot(*sets, title=f"Rule {r+1}", legends=labels)
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
--------------------------------------------------------------------------------
/examples/ex_19.py:
--------------------------------------------------------------------------------
1 | from pyit2fls import (T1Mamdani_ML, T1FS_plot, )
2 | from numpy import (linspace, array, abs, pi, sin, cos, meshgrid, zeros_like, )
3 | from scipy.optimize import (Bounds, )
4 | import matplotlib.pyplot as plt
5 | from mpl_toolkits.mplot3d import Axes3D
6 |
7 | X1 = linspace(-pi, pi, 10)
8 | X2 = linspace(-pi, pi, 10)
9 |
10 | X = []
11 | y = []
12 | for x1 in X1:
13 | for x2 in X2:
14 | X.append([x1, x2])
15 | y.append(sin(x1) + cos(x2))
16 | X = array(X)
17 |
18 | N = 2
19 | M = 4
20 | myMamdani = T1Mamdani_ML(N, M, (-4., 4.), algorithm="GA",
21 | algorithm_params=[200, 200, 100, 100, 0.1])
22 | print(myMamdani.fit(X, y))
23 |
24 | x1, x2 = meshgrid(X1, X2)
25 | y1 = sin(x1) + cos(x2)
26 | y2 = zeros_like(y1)
27 | for i in range(10):
28 | for j in range(10):
29 | y2[i, j] = myMamdani.score(array([X1[j], X2[i], ]))
30 |
31 | fig = plt.figure()
32 | ax = fig.add_subplot(111, projection="3d")
33 | original = ax.plot_surface(x1, x2, y1, cmap="viridis", vmin=y1.min(), vmax=y1.max())
34 | fig.colorbar(original, ax=ax, shrink=0.5, aspect=10, )
35 | ax.set_title("Original function")
36 | plt.show()
37 |
38 | fig = plt.figure()
39 | ax = fig.add_subplot(111, projection="3d")
40 | fitted = ax.plot_surface(x1, x2, y2, cmap="viridis", vmin=y1.min(), vmax=y1.max())
41 | fig.colorbar(fitted, ax=ax, shrink=0.5, aspect=10, )
42 | ax.set_title("Fitted function")
43 | plt.show()
44 |
45 | fig = plt.figure()
46 | ax = fig.add_subplot(111, projection="3d")
47 | error_surface = ax.plot_surface(x1, x2, abs(y2 - y1), cmap="Greens", alpha=0.8)
48 | fig.colorbar(error_surface, ax=ax, shrink=0.5, aspect=10,
49 | label="Error")
50 | ax.plot_surface(x1, x2, y1, cmap="Blues", alpha=0.7)
51 | ax.set_title("3D Surface Plot")
52 | plt.show()
53 |
54 | achievedSystem = myMamdani.get_T1Mamdani()
55 | for r, rule in zip(range(M), achievedSystem.rules):
56 | sets = []
57 | labels = []
58 | for i in range(N):
59 | sets.append(rule[0][i][1])
60 | labels.append(f"X{i}")
61 | sets.append(rule[1][0][1])
62 | labels.append("Y")
63 | T1FS_plot(*sets, title=f"Rule {r+1}", legends=labels)
64 |
65 |
66 |
67 |
68 |
69 |
70 |
71 |
--------------------------------------------------------------------------------
/examples/ex_2.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Tue May 14 18:56:00 2019
5 |
6 | @author: arslan
7 | """
8 |
9 | from pyit2fls import IT2FS_Gaussian_UncertMean, IT2FS_plot, meet, \
10 | join, min_t_norm, max_s_norm
11 | from numpy import linspace
12 |
13 |
14 | # Defining three interval type 2 fuzzy sets for testing the meet and join
15 | # functions.
16 |
17 | # Domain is defined as discrete space in the interval [0, 1] divided to 100 parts.
18 | domain = linspace(0., 1., 100)
19 |
20 | # The first IT2FLS is defined as a Gaussian set with uncertain mean value.
21 | # Center of the mean = 0.25,
22 | # Spread of the mean = 0.1,
23 | # Standard deviation = 0.1, and
24 | # Height = 1.
25 | A = IT2FS_Gaussian_UncertMean(domain, [0.25, 0.1, 0.1, 1.])
26 |
27 | # The second IT2FLS is defined as a Gaussian set with uncertain mean value.
28 | # Center of the mean = 0.5,
29 | # Spread of the mean = 0.1,
30 | # Standard deviation = 0.1, and
31 | # Height = 1.
32 | B = IT2FS_Gaussian_UncertMean(domain, [0.5, 0.1, 0.1, 1.])
33 |
34 | # The third IT2FLS is defined as a Gaussian set with uncertain mean value.
35 | # Center of the mean = 0.75,
36 | # Spread of the mean = 0.1,
37 | # Standard deviation = 0.1, and
38 | # Height = 1.
39 | C = IT2FS_Gaussian_UncertMean(domain, [0.75, 0.1, 0.1, 1.])
40 |
41 | # All the three sets are plotted in the same figure with legends and the ouput is saved
42 | # to a file named multiSet.pdf.
43 | IT2FS_plot(A, B, C, title="", legends=["Small","Medium","Large"], filename="multiSet")
44 |
45 | # The meet of two sets A and B is calculated as the set AB, and plotted.
46 | # T-norm used in the meet operation is minimum T-norm.
47 | AB = meet(domain, A, B, min_t_norm)
48 | AB.plot(filename="meet")
49 |
50 | # The join of two sets B and C is calculated as the set BC, and plotted.
51 | # S-norm used in the join operation is maximum S-norm.
52 | BC = join(domain, B, C, max_s_norm)
53 | BC.plot(filename="join")
54 |
--------------------------------------------------------------------------------
/examples/ex_20.py:
--------------------------------------------------------------------------------
1 | from pyit2fls import (IT2TSK_ML, IT2FS_Gaussian_UncertMean, IT2FS_plot, )
2 | from numpy import (linspace, array, abs, pi, sin, cos, meshgrid, zeros_like, )
3 | import matplotlib.pyplot as plt
4 | from mpl_toolkits.mplot3d import Axes3D
5 |
6 | X1 = linspace(-pi, pi, 10)
7 | X2 = linspace(-pi, pi, 10)
8 |
9 | X = []
10 | y = []
11 | for x1 in X1:
12 | for x2 in X2:
13 | X.append([x1, x2])
14 | y.append(sin(x1) + cos(x2))
15 | X = array(X)
16 |
17 | N = 2
18 | M = 4
19 | myIT2TSK = IT2TSK_ML(N, M, IT2FS_Gaussian_UncertMean, (-2.0, 2.0),
20 | algorithm="GA", algorithm_params=[50, 100, 500, 50, 0.1])
21 | print(myIT2TSK.fit(X, y))
22 |
23 | x1, x2 = meshgrid(X1, X2)
24 | y1 = sin(x1) + cos(x2)
25 | y2 = zeros_like(y1)
26 | for i in range(10):
27 | for j in range(10):
28 | y2[i, j] = myIT2TSK.score(array([X1[j], X2[i], ]))
29 |
30 | fig = plt.figure()
31 | ax = fig.add_subplot(111, projection="3d")
32 | original = ax.plot_surface(x1, x2, y1, cmap="viridis", vmin=y1.min(), vmax=y1.max())
33 | fig.colorbar(original, ax=ax, shrink=0.5, aspect=10,
34 | label="Original Plane")
35 | ax.set_title("3D Surface Plot")
36 | plt.show()
37 |
38 | fig = plt.figure()
39 | ax = fig.add_subplot(111, projection="3d")
40 | fitted = ax.plot_surface(x1, x2, y2, cmap="viridis", vmin=y1.min(), vmax=y1.max())
41 | fig.colorbar(fitted, ax=ax, shrink=0.5, aspect=10,
42 | label="Fitted Plane")
43 | ax.set_title("3D Surface Plot")
44 | plt.show()
45 |
46 | fig = plt.figure()
47 | ax = fig.add_subplot(111, projection="3d")
48 | error_surface = ax.plot_surface(x1, x2, abs(y2 - y1), cmap="Greens", alpha=0.8)
49 | fig.colorbar(error_surface, ax=ax, shrink=0.5, aspect=10,
50 | label="Error")
51 | ax.plot_surface(x1, x2, y1, cmap="Blues", alpha=0.7)
52 | ax.set_title("3D Surface Plot")
53 | plt.show()
54 |
55 |
56 |
57 |
58 |
--------------------------------------------------------------------------------
/examples/ex_21.py:
--------------------------------------------------------------------------------
1 | from pyit2fls import (IT2Mamdani_ML, IT2FS_Gaussian_UncertStd, )
2 | from numpy import (linspace, array, abs, pi, sin, cos, meshgrid, zeros_like, )
3 | import matplotlib.pyplot as plt
4 | from mpl_toolkits.mplot3d import Axes3D
5 |
6 | X1 = linspace(-pi, pi, 10)
7 | X2 = linspace(-pi, pi, 10)
8 |
9 | X = []
10 | y = []
11 | for x1 in X1:
12 | for x2 in X2:
13 | X.append([x1, x2])
14 | y.append(sin(x1) + cos(x2))
15 | X = array(X)
16 |
17 | N = 2
18 | M = 4
19 | myIT2Mamdani = IT2Mamdani_ML(N, M, IT2FS_Gaussian_UncertStd, (-4., 4.),
20 | algorithm="PSO", algorithm_params=[200, 200, 0.3, 0.3, 2.4])
21 | print(myIT2Mamdani.fit(X, y))
22 |
23 | x1, x2 = meshgrid(X1, X2)
24 | y1 = sin(x1) + cos(x2)
25 | y2 = zeros_like(y1)
26 | for i in range(10):
27 | for j in range(10):
28 | y2[i, j] = myIT2Mamdani.score(array([X1[j], X2[i], ]))
29 |
30 | fig = plt.figure()
31 | ax = fig.add_subplot(111, projection="3d")
32 | original = ax.plot_surface(x1, x2, y1, cmap="viridis", vmin=y1.min(), vmax=y1.max())
33 | fig.colorbar(original, ax=ax, shrink=0.5, aspect=10,
34 | label="Original Plane")
35 | ax.set_title("3D Surface Plot")
36 | plt.show()
37 |
38 | fig = plt.figure()
39 | ax = fig.add_subplot(111, projection="3d")
40 | fitted = ax.plot_surface(x1, x2, y2, cmap="viridis", vmin=y1.min(), vmax=y1.max())
41 | fig.colorbar(fitted, ax=ax, shrink=0.5, aspect=10,
42 | label="Fitted Plane")
43 | ax.set_title("3D Surface Plot")
44 | plt.show()
45 |
46 | fig = plt.figure()
47 | ax = fig.add_subplot(111, projection="3d")
48 | error_surface = ax.plot_surface(x1, x2, abs(y2 - y1), cmap="Greens", alpha=0.8)
49 | fig.colorbar(error_surface, ax=ax, shrink=0.5, aspect=10,
50 | label="Error")
51 | ax.plot_surface(x1, x2, y1, cmap="Blues", alpha=0.7)
52 | ax.set_title("3D Surface Plot")
53 | plt.show()
54 |
55 |
56 |
57 |
58 |
59 |
60 |
61 |
--------------------------------------------------------------------------------
/examples/ex_22.py:
--------------------------------------------------------------------------------
1 | from numpy import (array, linspace, )
2 | from numpy.random import (rand, )
3 | from scipy.integrate import (solve_ivp, )
4 | import matplotlib.pyplot as plt
5 | from pyit2fls import (Linear_System, T1_TS_Model, rtri_mf, ltri_mf, )
6 | import matplotlib.pyplot as plt
7 |
8 |
9 | A1 = array([[-1., 1., ],
10 | [ 0., -1., ], ])
11 | A2 = array([[ 1., 1., ],
12 | [ 0., 1., ], ])
13 | A3 = array([[ 1., 1., ],
14 | [ 0., 1., ], ])
15 | A4 = array([[-1., 1., ],
16 | [ 0., -2., ], ])
17 |
18 | B1 = array([[ 1., ],
19 | [-1., ], ])
20 | B2 = array([[ 2., ],
21 | [ 0., ], ])
22 | B3 = array([[ 2., ],
23 | [-1., ], ])
24 | B4 = array([[ 1., ],
25 | [ 0., ], ])
26 |
27 | C1 = array([1., 0.5, ])
28 | C2 = array([2., 0.1, ])
29 | C3 = array([2., 0.1, ])
30 | C4 = array([1., 0.5, ])
31 |
32 | D1 = array([[0.1, ], ])
33 | D2 = array([[0.2, ], ])
34 | D3 = array([[0.2, ], ])
35 | D4 = array([[0.1, ], ])
36 |
37 |
38 | linearSystem1 = Linear_System(A1, B1, C1, D1)
39 | linearSystem2 = Linear_System(A2, B2, C2, D2)
40 | linearSystem3 = Linear_System(A3, B3, C3, D3)
41 | linearSystem4 = Linear_System(A4, B4, C4, D4)
42 |
43 | mfList = [[rtri_mf, # Rule 1: The fuzzy set corresponded with x1
44 | rtri_mf, ], # Rule 1: The fuzzy set corresponded with x2
45 | [rtri_mf, # Rule 2: The fuzzy set corresponded with x1
46 | ltri_mf, ], # Rule 2: The fuzzy set corresponded with x2
47 | [ltri_mf, # Rule 3: The fuzzy set corresponded with x1
48 | rtri_mf, ], # Rule 3: The fuzzy set corresponded with x2
49 | [ltri_mf, # Rule 4: The fuzzy set corresponded with x1
50 | ltri_mf, ], ] # Rule 4: The fuzzy set corresponded with x2
51 | mfParamsList = [[[-1., 0., 1., ], # Rule 1: Parameters of the fuzzy set corresponded with x1
52 | [-1., 0., 1., ], ], # Rule 1: Parameters of the fuzzy set corresponded with x2
53 | [[-1., 0., 1., ], # Rule 2: Parameters of the fuzzy set corresponded with x1
54 | [ 1., 0., 1., ], ], # Rule 2: Parameters of the fuzzy set corresponded with x2
55 | [[ 1., 0., 1., ], # Rule 3: Parameters of the fuzzy set corresponded with x1
56 | [-1., 0., 1., ], ], # Rule 3: Parameters of the fuzzy set corresponded with x2
57 | [[ 1., 0., 1., ], # Rule 4: Parameters of the fuzzy set corresponded with x1
58 | [ 1., 0., 1., ], ], ] # Rule 4: Parameters of the fuzzy set corresponded with x2
59 | myTakagiSugeno = T1_TS_Model(mfList, mfParamsList,
60 | [linearSystem1,
61 | linearSystem2,
62 | linearSystem3,
63 | linearSystem4],
64 | 4, 2, 1, 1)
65 |
66 | def U(t, X):
67 | return array([[5.8 * X[0] + 18.5 * X[1] ], ])
68 |
69 | # X0 = 4. * (rand(2) - 0.5)
70 | X0 = array([-1., 2., ])
71 | dt = 0.001
72 | T = 10.
73 | t = linspace(0., T, int(T / dt))
74 | X = solve_ivp(myTakagiSugeno, [0., T], X0, args=(U, ),
75 | method="RK45", t_eval=t, dense_output=True).y
76 |
77 | plt.figure()
78 | plt.plot(t, X[0, :], label=r"$x_{1}$")
79 | plt.plot(t, X[1, :], label=r"$x_{2}$")
80 | plt.legend()
81 | plt.grid(True)
82 | plt.show()
83 |
84 |
85 |
86 |
87 |
88 |
89 |
90 |
91 |
92 |
93 |
94 |
95 |
96 |
--------------------------------------------------------------------------------
/examples/ex_23.py:
--------------------------------------------------------------------------------
1 | from numpy import (array, linspace, )
2 | from numpy.random import (rand, )
3 | from scipy.integrate import (solve_ivp, )
4 | import matplotlib.pyplot as plt
5 | from pyit2fls import (Linear_System, IT2_TS_Model, rtri_mf, ltri_mf, )
6 | import matplotlib.pyplot as plt
7 |
8 |
9 | A1 = array([[-1., 1., ],
10 | [ 0., -1., ], ])
11 | A2 = array([[ 1., 1., ],
12 | [ 0., 1., ], ])
13 | A3 = array([[ 1., 1., ],
14 | [ 0., 1., ], ])
15 | A4 = array([[-1., 1., ],
16 | [ 0., -2., ], ])
17 |
18 | B1 = array([[ 1., ],
19 | [-1., ], ])
20 | B2 = array([[ 2., ],
21 | [ 0., ], ])
22 | B3 = array([[ 2., ],
23 | [-1., ], ])
24 | B4 = array([[ 1., ],
25 | [ 0., ], ])
26 |
27 | C1 = array([1., 0.5, ])
28 | C2 = array([2., 0.1, ])
29 | C3 = array([2., 0.1, ])
30 | C4 = array([1., 0.5, ])
31 |
32 | D1 = array([[0.1, ], ])
33 | D2 = array([[0.2, ], ])
34 | D3 = array([[0.2, ], ])
35 | D4 = array([[0.1, ], ])
36 |
37 |
38 | linearSystem1 = Linear_System(A1, B1, C1, D1)
39 | linearSystem2 = Linear_System(A2, B2, C2, D2)
40 | linearSystem3 = Linear_System(A3, B3, C3, D3)
41 | linearSystem4 = Linear_System(A4, B4, C4, D4)
42 |
43 | lmfList = [[rtri_mf, # Rule 1: The LMF corresponded with x1
44 | rtri_mf, ], # Rule 1: The LMF corresponded with x2
45 | [rtri_mf, # Rule 2: The LMF corresponded with x1
46 | ltri_mf, ], # Rule 2: The LMF corresponded with x2
47 | [ltri_mf, # Rule 3: The LMF corresponded with x1
48 | rtri_mf, ], # Rule 3: The LMF corresponded with x2
49 | [ltri_mf, # Rule 4: The LMF corresponded with x1
50 | ltri_mf, ], ] # Rule 4: The LMF corresponded with x2
51 | lmfParamsList = [[[-0.8, +0.2, 0.8, ], # Rule 1: Parameters of the LMF corresponded with x1
52 | [-0.8, +0.2, 0.5, ], ], # Rule 1: Parameters of the LMF corresponded with x2
53 | [[-0.8, +0.2, 0.9, ], # Rule 2: Parameters of the LMF corresponded with x1
54 | [ 0.8, -0.4, 0.5, ], ], # Rule 2: Parameters of the LMF corresponded with x2
55 | [[ 0.8, -0.4, 0.8, ], # Rule 3: Parameters of the LMF corresponded with x1
56 | [-0.8, +0.2, 0.6, ], ], # Rule 3: Parameters of the LMF corresponded with x2
57 | [[ 0.8, -0.4, 0.3, ], # Rule 4: Parameters of the LMF corresponded with x1
58 | [ 0.8, -0.4, 0.8, ], ], ] # Rule 4: Parameters of the LMF corresponded with x2
59 | umfList = [[rtri_mf, # Rule 1: The UMF corresponded with x1
60 | rtri_mf, ], # Rule 1: The UMF corresponded with x2
61 | [rtri_mf, # Rule 2: The UMF corresponded with x1
62 | ltri_mf, ], # Rule 2: The UMF corresponded with x2
63 | [ltri_mf, # Rule 3: The UMF corresponded with x1
64 | rtri_mf, ], # Rule 3: The UMF corresponded with x2
65 | [ltri_mf, # Rule 4: The UMF corresponded with x1
66 | ltri_mf, ], ] # Rule 4: The UMF corresponded with x2
67 | umfParamsList = [[[-1., +0.2, 1.0, ], # Rule 1: Parameters of the UMF corresponded with x1
68 | [-1., +0.2, 1.0, ], ], # Rule 1: Parameters of the UMF corresponded with x2
69 | [[-1., +0.2, 1.0, ], # Rule 2: Parameters of the UMF corresponded with x1
70 | [ 1., -0.4, 1.0, ], ], # Rule 2: Parameters of the UMF corresponded with x2
71 | [[ 1., -0.4, 1.0, ], # Rule 3: Parameters of the UMF corresponded with x1
72 | [-1., +0.2, 1.0, ], ], # Rule 3: Parameters of the UMF corresponded with x2
73 | [[ 1., -0.4, 1.0, ], # Rule 4: Parameters of the UMF corresponded with x1
74 | [ 1., -0.4, 1.0, ], ], ] # Rule 4: Parameters of the UMF corresponded with x2
75 |
76 |
77 | myTakagiSugeno = IT2_TS_Model(lmfList, lmfParamsList,
78 | umfList, umfParamsList,
79 | [linearSystem1,
80 | linearSystem2,
81 | linearSystem3,
82 | linearSystem4],
83 | 4, 2, 1, 1)
84 |
85 | def U(t, X):
86 | return array([[5.8 * X[0] + 18.5 * X[1] ], ])
87 |
88 | # X0 = 4. * (rand(2) - 0.5)
89 | X0 = array([-1., 2., ])
90 | dt = 0.001
91 | T = 10.
92 | t = linspace(0., T, int(T / dt))
93 | X = solve_ivp(myTakagiSugeno, [0., T], X0, args=(U, ),
94 | method="RK45", t_eval=t, dense_output=True).y
95 |
96 | plt.figure()
97 | plt.plot(t, X[0, :], label=r"$x_{1}$")
98 | plt.plot(t, X[1, :], label=r"$x_{2}$")
99 | plt.legend()
100 | plt.grid(True)
101 | plt.show()
102 |
103 |
104 |
105 |
106 |
107 |
108 |
109 |
110 |
111 |
112 |
113 |
114 |
115 |
--------------------------------------------------------------------------------
/examples/ex_24.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Tue May 14 18:56:00 2019
5 |
6 | @author: arslan
7 | """
8 |
9 | from pyit2fls import (IT2FS_Gaussian_UncertMean, IT2FS_plot, MEET, \
10 | JOIN, min_t_norm, max_s_norm, )
11 | from numpy import linspace
12 |
13 |
14 | # Defining three interval type 2 fuzzy sets for testing the meet and join
15 | # functions.
16 |
17 | # Domain is defined as discrete space in the interval [0, 1] divided to 100 parts.
18 | domain = linspace(0., 1., 100)
19 |
20 | # The first IT2FLS is defined as a Gaussian set with uncertain mean value.
21 | # Center of the mean = 0.25,
22 | # Spread of the mean = 0.1,
23 | # Standard deviation = 0.1, and
24 | # Height = 1.
25 | A = IT2FS_Gaussian_UncertMean(domain, [0.25, 0.1, 0.1, 1.])
26 |
27 | # The second IT2FLS is defined as a Gaussian set with uncertain mean value.
28 | # Center of the mean = 0.5,
29 | # Spread of the mean = 0.1,
30 | # Standard deviation = 0.1, and
31 | # Height = 1.
32 | B = IT2FS_Gaussian_UncertMean(domain, [0.5, 0.1, 0.1, 1.])
33 |
34 | # The third IT2FLS is defined as a Gaussian set with uncertain mean value.
35 | # Center of the mean = 0.75,
36 | # Spread of the mean = 0.1,
37 | # Standard deviation = 0.1, and
38 | # Height = 1.
39 | C = IT2FS_Gaussian_UncertMean(domain, [0.75, 0.1, 0.1, 1.])
40 |
41 | # All the three sets are plotted in the same figure with legends and the ouput is saved
42 | # to a file named multiSet.pdf.
43 | IT2FS_plot(A, B, C, title="", legends=["Small","Medium","Large"], filename="multiSet")
44 |
45 | # The meet of two sets A and B is calculated as the set AB, and plotted.
46 | # T-norm used in the meet operation is minimum T-norm.
47 | AB = MEET(domain, min_t_norm, A, B, C)
48 | AB.plot(filename="meet")
49 |
50 | # The join of two sets B and C is calculated as the set BC, and plotted.
51 | # S-norm used in the join operation is maximum S-norm.
52 | BC = JOIN(domain, max_s_norm, A, B, C)
53 | BC.plot(filename="join")
54 |
--------------------------------------------------------------------------------
/examples/ex_3.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Wed May 15 02:40:21 2019
5 |
6 | @author: arslan
7 | """
8 |
9 | from pyit2fls import IT2Mamdani, IT2FS_Gaussian_UncertStd, IT2FS_plot, \
10 | min_t_norm, max_s_norm, TR_plot, crisp
11 | from numpy import linspace
12 |
13 | domain = linspace(0., 1., 100) # Domain is defined as discrete space in the
14 | # interval [0, 1] divided to 100 parts.
15 |
16 | # The Small set is defined as a Guassian IT2FS with uncertain standard deviation
17 | # value. The mean, the standard deviation center, the standard deviation spread,
18 | # and the height of the set are set to 0., 0.15, 0.1, and 1., respectively.
19 | Small = IT2FS_Gaussian_UncertStd(domain, [0, 0.15, 0.05, 1.])
20 |
21 | # The Medium set is defined as a Guassian IT2FS with uncertain standard deviation
22 | # value. The mean, the standard deviation center, the standard deviation spread,
23 | # and the height of the set are set to 0.5, 0.15, 0.1, and 1., respectively.
24 | Medium = IT2FS_Gaussian_UncertStd(domain, [0.5, 0.15, 0.05, 1.])
25 |
26 | # The Large set is defined as a Guassian IT2FS with uncertain standard deviation
27 | # value. The mean, the standard deviation center, the standard deviation spread,
28 | # and the height of the set are set to 1., 0.15, 0.1, and 1., respectively.
29 | Large = IT2FS_Gaussian_UncertStd(domain, [1., 0.15, 0.05, 1.])
30 |
31 | # Three sets, Small, Medium, and Large are plotted using the function IT2FS_plot.
32 | IT2FS_plot(Small, Medium, Large, legends=["Small", "Medium", "large"], filename="simp_ex_sets")
33 |
34 | # An Interval Type 2 Fuzzy Logic System is created. To evaluate the defined
35 | # IT2 Mamdani FLS the minimum t-norm and maximum s-norm are used. The centroid
36 | # method is selected for evaluating the IF-THEN rules and the KM algorithm is
37 | # selected as type reduction algorithm.
38 | # The variables and output variables are defined. As it can be seen, the
39 | # system has two inputs and two outputs.
40 | myIT2FLS = IT2Mamdani(min_t_norm, max_s_norm,
41 | method="Centroid", algorithm="KM")
42 | myIT2FLS.add_input_variable("x1")
43 | myIT2FLS.add_input_variable("x2")
44 | myIT2FLS.add_output_variable("y1")
45 | myIT2FLS.add_output_variable("y2")
46 |
47 | # Now we are going to add the fuzzy IF-THEN rules.
48 | # There are three rules to add:
49 | # 1. IF x1 is Small AND x2 is Small THEN y1 is Small AND y2 is Large
50 | myIT2FLS.add_rule([("x1", Small), ("x2", Small)], [("y1", Small), ("y2", Large)])
51 | # 2. IF x1 is Medium AND x2 is Medium THEN y1 is Medium AND y2 is Small
52 | myIT2FLS.add_rule([("x1", Medium), ("x2", Medium)], [("y1", Medium), ("y2", Small)])
53 | # 3. IF x1 is Large AND x2 is Large THEN y1 is Large AND y2 is Small
54 | myIT2FLS.add_rule([("x1", Large), ("x2", Large)], [("y1", Large), ("y2", Small)])
55 |
56 | # The first input is 0.923 and the second one is 0.745.
57 | it2out, tr = myIT2FLS.evaluate({"x1":0.923, "x2":0.745})
58 |
59 | # Here the output IT2FSs and their type reduced versions are plotted.
60 | # The crisp output is also calculated and printed.
61 | it2out["y1"].plot(filename="y1_out")
62 | TR_plot(domain, tr["y1"], filename="y1_tr")
63 | print(crisp(tr["y1"]))
64 |
65 | it2out["y2"].plot(filename="y2_out")
66 | TR_plot(domain, tr["y2"], filename="y2_tr")
67 | print(crisp(tr["y2"]))
68 |
69 |
70 |
71 |
72 |
73 |
--------------------------------------------------------------------------------
/examples/ex_4.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Sat May 18 13:13:55 2019
5 |
6 | @author: arslan
7 | """
8 | import numpy as np
9 | import matplotlib.pyplot as plt
10 | from pyit2fls import (IT2FS_Gaussian_UncertStd, IT2Mamdani, min_t_norm, max_s_norm, )
11 | import PyIT2FLSPSO
12 | from time import time
13 |
14 | def mackey_glass(tav, n, beta, gamma, step):
15 | x = [np.random.random() for i in range(tav)]
16 | for i in range(step):
17 | x.append(x[-1] + beta * x[-tav] / (1 + x[-tav] ** n) - gamma * x[-1])
18 | return x[tav:]
19 |
20 | mg = mackey_glass(2, 9.65, 2., 1., 1000)
21 |
22 | # plt.figure()
23 | # plt.plot(mg[200:600])
24 | # plt.xticks([40 * i for i in range(11)], [str(40 * i + 200) for i in range(11)])
25 | # plt.ylim(bottom=0, top=1.8)
26 | # plt.legend(["Mackey-Glass dynamics\n" + r"$\gamma$=1, $\beta$=2, $\tau$=2, and $n$=9.65"])
27 | # plt.grid(True)
28 | # plt.savefig("mackey_glass_1.eps", format="eps", dpi=500, bbox_inches="tight")
29 | # plt.show()
30 |
31 | domain = np.linspace(0., 1.5, 15)
32 | L = 100 # Learning set length
33 | LearningSet = []
34 | for i in range(200, 200 + L):
35 | LearningSet.append([[mg[i], mg[i - 1], mg[i - 2]], mg[i + 1]])
36 |
37 | it2fls = IT2Mamdani(t_norm=min_t_norm, s_norm=max_s_norm,
38 | method="Height", algorithm="EIASC")
39 | it2fls.add_input_variable("A")
40 | it2fls.add_input_variable("B")
41 | it2fls.add_input_variable("C")
42 | it2fls.add_output_variable("O")
43 |
44 | it2fls.add_rule([("A", ), ("B", ), ("C", )], [("O", )])
45 | it2fls.add_rule([("A", ), ("B", ), ("C", )], [("O", )])
46 | it2fls.add_rule([("A", ), ("B", ), ("C", )], [("O", )])
47 |
48 | def calculate(x, i):
49 | A1 = IT2FS_Gaussian_UncertStd(domain, np.append(x[:3], 1))
50 | A2 = IT2FS_Gaussian_UncertStd(domain, np.append(x[3:6], 1))
51 | A3 = IT2FS_Gaussian_UncertStd(domain, np.append(x[6:9], 1))
52 |
53 | B1 = IT2FS_Gaussian_UncertStd(domain, np.append(x[9:12], 1))
54 | B2 = IT2FS_Gaussian_UncertStd(domain, np.append(x[12:15], 1))
55 | B3 = IT2FS_Gaussian_UncertStd(domain, np.append(x[15:18], 1))
56 |
57 | C1 = IT2FS_Gaussian_UncertStd(domain, np.append(x[18:21], 1))
58 | C2 = IT2FS_Gaussian_UncertStd(domain, np.append(x[21:24], 1))
59 | C3 = IT2FS_Gaussian_UncertStd(domain, np.append(x[24:27], 1))
60 |
61 | O1 = IT2FS_Gaussian_UncertStd(domain, np.append(x[27:30], 1))
62 | O2 = IT2FS_Gaussian_UncertStd(domain, np.append(x[30:33], 1))
63 | O3 = IT2FS_Gaussian_UncertStd(domain, np.append(x[33:36], 1))
64 |
65 | it2fls.rules[0] = ([("A", A1), ("B", B1), ("C", C1)], [("O", O1)])
66 | it2fls.rules[1] = ([("A", A2), ("B", B2), ("C", C2)], [("O", O2)])
67 | it2fls.rules[2] = ([("A", A3), ("B", B3), ("C", C3)], [("O", O3)])
68 |
69 | tr = it2fls.evaluate({"A":i[0], "B":i[1], "C":i[2]})
70 | o = tr["O"]
71 | return (o[0] + o[1]) / 2
72 |
73 | def cost_func(x):
74 | A1 = IT2FS_Gaussian_UncertStd(domain, np.append(x[:3], 1))
75 | A2 = IT2FS_Gaussian_UncertStd(domain, np.append(x[3:6], 1))
76 | A3 = IT2FS_Gaussian_UncertStd(domain, np.append(x[6:9], 1))
77 |
78 | B1 = IT2FS_Gaussian_UncertStd(domain, np.append(x[9:12], 1))
79 | B2 = IT2FS_Gaussian_UncertStd(domain, np.append(x[12:15], 1))
80 | B3 = IT2FS_Gaussian_UncertStd(domain, np.append(x[15:18], 1))
81 |
82 | C1 = IT2FS_Gaussian_UncertStd(domain, np.append(x[18:21], 1))
83 | C2 = IT2FS_Gaussian_UncertStd(domain, np.append(x[21:24], 1))
84 | C3 = IT2FS_Gaussian_UncertStd(domain, np.append(x[24:27], 1))
85 |
86 | O1 = IT2FS_Gaussian_UncertStd(domain, np.append(x[27:30], 1))
87 | O2 = IT2FS_Gaussian_UncertStd(domain, np.append(x[30:33], 1))
88 | O3 = IT2FS_Gaussian_UncertStd(domain, np.append(x[33:36], 1))
89 |
90 | it2fls.rules[0] = ([("A", A1), ("B", B1), ("C", C1)], [("O", O1)])
91 | it2fls.rules[1] = ([("A", A2), ("B", B2), ("C", C2)], [("O", O2)])
92 | it2fls.rules[2] = ([("A", A3), ("B", B3), ("C", C3)], [("O", O3)])
93 |
94 | err = 0
95 | for L in LearningSet:
96 | tr = it2fls.evaluate({"A":L[0][0], "B":L[0][1], "C":L[0][2]})
97 | o = tr["O"]
98 | err += ((o[0] + o[1]) / 2 - L[1]) ** 2
99 | return err / len(LearningSet)
100 |
101 |
102 | def solution_generator():
103 | return 3.5 * (np.random.rand(12 * 3) - 0.5)
104 |
105 | def velocity_generator():
106 | return 6.0 * (np.random.rand(12 * 3) - 0.5)
107 |
108 | mySolver = PyIT2FLSPSO.PyPSO(cost_func, 200, 100, solution_generator, velocity_generator)
109 | t = time()
110 | conv = mySolver.solve()
111 | print(time() - t)
112 |
113 | plt.figure()
114 | plt.plot(conv)
115 | plt.grid(which="major", linestyle="-", linewidth=0.75, color="gray", alpha=0.7)
116 | plt.minorticks_on()
117 | plt.grid(which="minor", linestyle=":", linewidth=0.5, color="lightgray", alpha=0.7)
118 | plt.xlabel("Iteration")
119 | plt.ylabel("MSE")
120 | plt.savefig("convergence.pdf", format="pdf", dpi=300, bbox_inches="tight")
121 | plt.show()
122 |
123 | out = []
124 | correct = []
125 | for i in range(200, 200 + L):
126 | out.append(calculate(mySolver.best_known_position, [mg[i], mg[i - 1], mg[i - 2]]))
127 | correct.append(mg[i + 1])
128 |
129 | out = np.array(out)
130 | correct = np.array(correct)
131 | error = np.abs(out - correct)
132 |
133 | plt.figure()
134 | plt.plot(out, linewidth=1.)
135 | plt.plot(correct, linewidth=1.)
136 | plt.plot(error, linewidth=1.)
137 | plt.grid(True)
138 | plt.legend(["Predicted", "Real", "Error"], loc=1)
139 | plt.xlabel("t")
140 | plt.ylabel("y(t)")
141 | plt.savefig("MackeyGlassSO1.pdf", format="pdf", dpi=300, bbox_inches="tight")
142 | plt.show()
143 |
144 |
145 | out = []
146 | correct = []
147 | for i in range(200 + L, 200 + 2 * L):
148 | out.append(calculate(mySolver.best_known_position, [mg[i], mg[i - 1], mg[i - 2]]))
149 | correct.append(mg[i + 1])
150 | out = np.array(out)
151 | correct = np.array(correct)
152 | error = np.abs(out - correct)
153 |
154 | plt.figure()
155 | plt.plot(out, linewidth=1.)
156 | plt.plot(correct, linewidth=1.)
157 | plt.plot(error, linewidth=1.)
158 | plt.grid(which="major", linestyle="-", linewidth=0.75, color="gray", alpha=0.7)
159 | plt.minorticks_on()
160 | plt.grid(which="minor", linestyle=":", linewidth=0.5, color="lightgray", alpha=0.7)
161 | plt.legend(["Predicted", "Real", "Error"], loc=1)
162 | plt.xlabel("t")
163 | plt.ylabel("y(t)")
164 | plt.savefig("MackeyGlassSO2.pdf", format="pdf", dpi=300, bbox_inches="tight")
165 | plt.show()
166 |
167 |
168 |
169 |
170 |
171 |
172 |
173 |
174 |
175 |
176 |
177 |
178 |
179 |
180 |
181 |
182 |
183 |
--------------------------------------------------------------------------------
/examples/ex_5.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Thu Jun 20 20:19:08 2019
5 |
6 | @author: arslan
7 | """
8 |
9 | import matplotlib.pyplot as plt
10 | from pyit2fls import (IT2FS_Gaussian_UncertStd, IT2Mamdani,
11 | min_t_norm, product_t_norm, max_s_norm, IT2FS_plot, )
12 | from numpy import (linspace, array, where, abs, max, )
13 | from scipy.integrate import (trapezoid, )
14 | from ddeintlib import ddeint
15 |
16 | # %%
17 | def ITAE(a, b, t):
18 | return trapezoid(t * abs(a - b), t)
19 |
20 | def os(y):
21 | return abs(max(y) - y[-1])
22 |
23 | def ts(y, t):
24 | ss = y[-1]
25 | tol = 0.02 * ss
26 | yy = abs(y - ss)[::-1]
27 | return t[t.size - where(yy>tol)[0][0]]
28 |
29 | # %%
30 | def u(t):
31 | return 1. if t > 1. else 0.
32 |
33 | def u_dot(t):
34 | # return 0
35 | a = 10
36 | return (a if 1. < t < (1. + 1./a) else 0)
37 |
38 | # %% Interval Type 2 Fuzzy PID Codes ...
39 | domain = linspace(-1., 1., 201)
40 |
41 | N = IT2FS_Gaussian_UncertStd(domain, [-1., 0.5, 0.1, 1.])
42 | Z = IT2FS_Gaussian_UncertStd(domain, [0., 0.2, 0.025, 1.])
43 | P = IT2FS_Gaussian_UncertStd(domain, [1., 0.5, 0.1, 1.])
44 | IT2FS_plot(N, Z, P, legends=["Negative", "Zero", "Positive"], filename="delay_pid_input_sets")
45 |
46 | NB = IT2FS_Gaussian_UncertStd(domain, [-1., 0.1, 0.05, 1.])
47 | NM = IT2FS_Gaussian_UncertStd(domain, [-0.5, 0.1, 0.05, 1.])
48 | ZZ = IT2FS_Gaussian_UncertStd(domain, [0., 0.1, 0.05, 1.])
49 | PM = IT2FS_Gaussian_UncertStd(domain, [0.5, 0.1, 0.05, 1.])
50 | PB = IT2FS_Gaussian_UncertStd(domain, [1., 0.1, 0.05, 1.])
51 | IT2FS_plot(NB, NM, ZZ, PM, PB, legends=["Negative Big", "Negative Medium",
52 | "Zero", "Positive Medium",
53 | "Positive Big"], filename="delay_pid_output_sets")
54 |
55 | def fuzzySystem(algorithm, algorithm_params=[]):
56 | it2fls = IT2Mamdani(min_t_norm, max_s_norm, method="Centroid",
57 | algorithm=algorithm, algorithm_params=algorithm_params)
58 | it2fls.add_input_variable("I1") # E
59 | it2fls.add_input_variable("I2") # dot E
60 | it2fls.add_output_variable("O")
61 |
62 | it2fls.add_rule([("I1", N), ("I2", N)], [("O", NB)])
63 | it2fls.add_rule([("I1", N), ("I2", Z)], [("O", NM)])
64 | it2fls.add_rule([("I1", N), ("I2", P)], [("O", ZZ)])
65 | it2fls.add_rule([("I1", Z), ("I2", N)], [("O", NM)])
66 | it2fls.add_rule([("I1", Z), ("I2", Z)], [("O", ZZ)])
67 | it2fls.add_rule([("I1", Z), ("I2", P)], [("O", NM)])
68 | it2fls.add_rule([("I1", P), ("I2", N)], [("O", ZZ)])
69 | it2fls.add_rule([("I1", P), ("I2", Z)], [("O", PM)])
70 | it2fls.add_rule([("I1", P), ("I2", P)], [("O", PB)])
71 | return it2fls
72 |
73 | it2fpid_KM = fuzzySystem("KM")
74 | it2fpid_EIASC = fuzzySystem("EIASC")
75 | it2fpid_WM = fuzzySystem("WM")
76 | it2fpid_BMM = fuzzySystem("BMM", algorithm_params=(0.5, 0.5))
77 | it2fpid_NT = fuzzySystem("NT")
78 |
79 | def eval_IT2FPID_KM(i1, i2):
80 | c, TR = it2fpid_KM.evaluate({"I1":i1, "I2":i2})
81 | o = TR["O"]
82 | return (o[0] + o[1]) / 2
83 |
84 | def eval_IT2FPID_EIASC(i1, i2):
85 | c, TR = it2fpid_EIASC.evaluate({"I1":i1, "I2":i2})
86 | o = TR["O"]
87 | return (o[0] + o[1]) / 2
88 |
89 | def eval_IT2FPID_WM(i1, i2):
90 | c, TR = it2fpid_WM.evaluate({"I1":i1, "I2":i2})
91 | o = TR["O"]
92 | return (o[0] + o[1]) / 2
93 |
94 | def eval_IT2FPID_BMM(i1, i2):
95 | c, y = it2fpid_BMM.evaluate({"I1":i1, "I2":i2})
96 | return y["O"]
97 |
98 | def eval_IT2FPID_NT(i1, i2):
99 | c, y = it2fpid_NT.evaluate({"I1":i1, "I2":i2})
100 | return y["O"]
101 |
102 | # %% Overall system
103 | def raw_sys(Y, t, K, T, L):
104 | return array([(-1. / T) * Y[0](t) + (K / T) * u(t - L)])
105 |
106 | def cl_sys(Y, t, K, T, L):
107 | return array([(-1. / T) * Y[0](t) + (K / T) * (u(t - L) - Y[0](t - L))])
108 |
109 | def model_fuzzy(Y, t, K, T, L, Ka, Kb, Ke, Kd, eval_func):
110 | epsilon = 0.001
111 |
112 | y2 = Y[1](t)
113 |
114 | e1 = u(t - L) - Y[0](t - L)
115 | de1 = u_dot(t - L) - Y[1](t - L)
116 | xd1 = eval_func(min(max(Ke * e1, -1), 1), min(max(Kd * de1, -1), 1))
117 |
118 |
119 | e2 = u(t - L - epsilon) - Y[0](t - L - epsilon)
120 | de2 = u_dot(t - L - epsilon) - Y[1](t - L - epsilon)
121 | xd2 = eval_func(min(max(Ke * e2, -1), 1), min(max(Kd * de2, -1), 1))
122 |
123 |
124 |
125 | dxd = (xd1 - xd2) / epsilon
126 |
127 |
128 |
129 | return array([y2, (-1./T) * y2 + (K * Ka / T) * dxd + (K * Kb / T) * xd1])
130 |
131 | g1 = lambda t : 0
132 | g2 = lambda t : 0
133 |
134 | # %%
135 | # Nominal
136 | # K = 1.
137 | # T = 1.
138 | # L = 0.2
139 |
140 | # Perturbed 1.
141 | K = 1.3
142 | T = 1.9
143 | L = 0.4
144 |
145 | #Perturbed 2.
146 | #K = 1.1
147 | #T = 1.3
148 | #L = 0.45
149 |
150 | tt = linspace(0., 20. ,2000)
151 |
152 | y_raw = ddeint(raw_sys, [g1], tt, fargs=(K, T, L, ))
153 | y_cl = ddeint(cl_sys, [g1], tt, fargs=(K, T, L, ))
154 |
155 | print("KM evaluation start!")
156 | y_it2fpid_KM = ddeint(model_fuzzy, [g1, g2], tt,
157 | fargs=(K, T, L, 0.25, 4.25, 0.8, 0.5, eval_IT2FPID_KM, ))
158 |
159 | print("EIASC evaluation start!")
160 | y_it2fpid_EIASC = ddeint(model_fuzzy, [g1, g2], tt,
161 | fargs=(K, T, L, 0.25, 4.25, 0.8, 0.5, eval_IT2FPID_EIASC, ))
162 |
163 | print("WM evaluation start!")
164 | y_it2fpid_WM = ddeint(model_fuzzy, [g1, g2], tt,
165 | fargs=(K, T, L, 0.25, 4.25, 0.8, 0.5, eval_IT2FPID_WM, ))
166 |
167 | print("BMM evaluation start!")
168 | y_it2fpid_BMM = ddeint(model_fuzzy, [g1, g2], tt,
169 | fargs=(K, T, L, 0.25, 4.25, 0.8, 0.5, eval_IT2FPID_BMM, ))
170 |
171 | print("NT evaluation start!")
172 | y_it2fpid_NT = ddeint(model_fuzzy, [g1, g2], tt,
173 | fargs=(K, T, L, 0.25, 4.25, 0.8, 0.5, eval_IT2FPID_NT, ))
174 |
175 | ref = array([u(t) for t in tt])
176 |
177 | plt.figure()
178 | plt.plot(tt, ref, label="Reference")
179 | plt.plot(tt, y_it2fpid_KM[:,0], label="KM", linewidth=1.)
180 | plt.plot(tt, y_it2fpid_EIASC[:,0], label="EIASC", linewidth=1.)
181 | plt.plot(tt, y_it2fpid_WM[:,0], label="WM", linewidth=1.)
182 | plt.plot(tt, y_it2fpid_BMM[:,0], label="BMM", linewidth=1.)
183 | plt.plot(tt, y_it2fpid_NT[:,0], label="NT", linewidth=1.)
184 | plt.legend()
185 | plt.xlabel("Time (s)")
186 | plt.ylabel("System response")
187 | plt.grid(which="major", linestyle="-", linewidth=0.75, color="gray", alpha=0.7)
188 | plt.minorticks_on()
189 | plt.grid(which="minor", linestyle=":", linewidth=0.5, color="lightgray", alpha=0.7)
190 | plt.savefig("delay_pid_case1_comp.pdf", format="pdf", dpi=300, bbox_inches="tight")
191 | plt.show()
192 |
193 |
194 |
195 | print("KM:")
196 | print("ITAE:", ITAE(ref, y_it2fpid_KM[:,0], tt))
197 | print("Overshoot:", 100 * os(y_it2fpid_KM[:,0]))
198 | print("Settling time:", ts(y_it2fpid_KM[:,0], tt))
199 |
200 | print("EIASC:")
201 | print("ITAE:", ITAE(ref, y_it2fpid_EIASC[:,0], tt))
202 | print("Overshoot:", 100 * os(y_it2fpid_EIASC[:,0]))
203 | print("Settling time:", ts(y_it2fpid_EIASC[:,0], tt))
204 |
205 | print("WM:")
206 | print("ITAE:", ITAE(ref, y_it2fpid_WM[:,0], tt))
207 | print("Overshoot:", 100 * os(y_it2fpid_WM[:,0]))
208 | print("Settling time:", ts(y_it2fpid_WM[:,0], tt))
209 |
210 | print("BMM:")
211 | print("ITAE:", ITAE(ref, y_it2fpid_BMM[:,0], tt))
212 | print("Overshoot:", 100 * os(y_it2fpid_BMM[:,0]))
213 | print("Settling time:", ts(y_it2fpid_BMM[:,0], tt))
214 |
215 | print("NT:")
216 | print("ITAE:", ITAE(ref, y_it2fpid_NT[:,0], tt))
217 | print("Overshoot:", 100 * os(y_it2fpid_NT[:,0]))
218 | print("Settling time:", ts(y_it2fpid_NT[:,0], tt))
219 |
--------------------------------------------------------------------------------
/examples/ex_6.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Wed Mar 11 13:09:12 2020
5 |
6 | @author: arslan
7 | """
8 |
9 | from pyit2fls import (IT2FS, tri_mf, const_mf, rtri_mf, ltri_mf,
10 | trapezoid_mf, gaussian_mf, IT2FS_Gaussian_UncertMean,
11 | IT2FS_Gaussian_UncertStd, R_IT2FS_Gaussian_UncertStd,
12 | L_IT2FS_Gaussian_UncertStd, IT2FS_plot)
13 | from numpy import linspace
14 |
15 | domain = linspace(0, 1, 1001)
16 |
17 | Const = IT2FS(domain, const_mf, [0.6], const_mf, [0.4], check_set=True)
18 |
19 | Tri = IT2FS(domain, tri_mf, [0.1, 0.5, 0.9, 1], tri_mf, [0.3, 0.5, 0.7, 0.7], check_set=True)
20 |
21 | RTri = IT2FS(domain, rtri_mf, [0.85, 0.2, 1], rtri_mf, [0.75, 0.1, 1.], check_set=True)
22 |
23 | LTri = IT2FS(domain, ltri_mf, [0.15, 0.8, 1], ltri_mf, [0.25, 0.9, 1.], check_set=True)
24 |
25 | IT2FS_plot(Const, Tri,
26 | legends = ["Const Set",
27 | "Triangular Set"])
28 | IT2FS_plot(RTri, LTri,
29 | legends = ["Right Triangular Set",
30 | "Left Triangular Set"])
31 |
32 | Trapezoid = IT2FS(domain,
33 | trapezoid_mf, [0.1, 0.35, 0.65, 0.9, 1.0],
34 | trapezoid_mf, [0.2, 0.4, 0.6, 0.8, 0.8],
35 | check_set=True)
36 |
37 | Trapezoid.plot(legends="Trapezoid IT2FS")
38 |
39 | Gaussian = IT2FS(domain,
40 | gaussian_mf, [0.5, 0.1, 1.0],
41 | gaussian_mf, [0.5, 0.05, 0.8],
42 | check_set=True)
43 |
44 | Gaussian.plot(legends="Gaussian IT2FS")
45 |
46 | Gaussian_UncertMean = IT2FS_Gaussian_UncertMean(domain, [0.5, 0.1, 0.1, 1.])
47 | Gaussian_UncertMean.plot(legends="Gaussian IT2FS with Uncertain Mean")
48 |
49 | Gaussian_UncertStd = IT2FS_Gaussian_UncertStd(domain, [0.5, 0.1, 0.05, 0.75])
50 | Gaussian_UncertStd.plot(legends="Gaussian IT2FS with Uncertain Std")
51 |
52 | RGaussian_UncertStd = R_IT2FS_Gaussian_UncertStd(domain, [0.5, 0.1, 0.05, 0.8])
53 | RGaussian_UncertStd.plot(legends="Right Gaussian IT2FS with Uncertain Std")
54 |
55 | LGaussian_UncertStd = L_IT2FS_Gaussian_UncertStd(domain, [0.5, 0.1, 0.05, 0.8])
56 | LGaussian_UncertStd.plot(legends="Left Gaussian IT2FS with Uncertain Std")
57 |
58 |
59 |
60 |
61 |
62 |
63 |
64 |
65 |
66 |
--------------------------------------------------------------------------------
/examples/ex_7.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Fri Jun 19 13:22:01 2020
5 |
6 | @author: arslan
7 | """
8 |
9 | from pyit2fls import (IT2TSK, IT2FS_Gaussian_UncertStd, IT2FS_plot, \
10 | product_t_norm, max_s_norm, )
11 |
12 | from numpy import linspace
13 | from time import time
14 |
15 | domain = linspace(0., 1., 100)
16 |
17 | Small = IT2FS_Gaussian_UncertStd(domain, [0, 0.15, 0.05, 1.])
18 | Medium = IT2FS_Gaussian_UncertStd(domain, [0.5, 0.15, 0.05, 1.])
19 | Large = IT2FS_Gaussian_UncertStd(domain, [1., 0.15, 0.05, 1.])
20 |
21 | myIT2FLS = IT2TSK(product_t_norm, max_s_norm)
22 |
23 | myIT2FLS.add_input_variable("x1")
24 | myIT2FLS.add_input_variable("x2")
25 | myIT2FLS.add_output_variable("y1")
26 | myIT2FLS.add_output_variable("y2")
27 |
28 | # IF x1 is Small AND x2 is Small
29 | # THEN y1 = x1 + 2.3 x2 + 0.5 AND y2 = 1.2 x1 + 1.5 x2 + 1.
30 | myIT2FLS.add_rule([("x1", Small), ("x2", Small)],
31 | [("y1", {"const":0.5, "x1":1., "x2":2.3}),
32 | ("y2", {"const":1., "x1":1.2, "x2":1.5})])
33 |
34 | # IF x1 is Medium AND x2 is Medium
35 | # THEN y1 = 2.7 x1 + 1.9 x2 + 1. AND y2 = 2.5 x1 + 2. x2 + 1.
36 | myIT2FLS.add_rule([("x1", Medium), ("x2", Medium)],
37 | [("y1", {"const":1., "x1":2.7, "x2":1.9}),
38 | ("y2", {"const":1., "x1":2.5, "x2":2.})])
39 |
40 | # IF x1 is Large AND x2 is Large
41 | # THEN y1 = 2. x1 + 3. x2 + 1. AND y2 = x1 + x2 + 2.
42 | myIT2FLS.add_rule([("x1", Large), ("x2", Large)],
43 | [("y1", {"const":1., "x1":2., "x2":3.}),
44 | ("y2", {"const":2., "x1":1., "x2":1.})])
45 |
46 | print(myIT2FLS.evaluate({"x1":0.9, "x2":0.9}))
47 |
48 |
--------------------------------------------------------------------------------
/examples/ex_8.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Thu Jul 2 11:35:28 2020
5 |
6 | @author: arslan
7 | """
8 |
9 |
10 | from pyit2fls import (IT2TSK, IT2FS_Gaussian_UncertStd, IT2FS_plot, \
11 | product_t_norm, max_s_norm, )
12 | from mpl_toolkits import mplot3d
13 | import matplotlib.pyplot as plt
14 | from matplotlib import cm
15 | from matplotlib.ticker import (LinearLocator, FormatStrFormatter, )
16 | from numpy import linspace, meshgrid, zeros
17 | from time import time
18 |
19 | domain = linspace(0., 1., 100)
20 |
21 | X1, X2 = meshgrid(domain, domain)
22 | Y11 = X1 + X2 + 1.
23 | Y12 = 2. * X1 - X2 + 1.
24 | Y21 = 1.5 * X1 + 0.5 * X2 + 0.5
25 | Y22 = 1.5 * X1 - 0.5 * X2 + 0.5
26 | Y31 = 2. * X1 + 0.1 * X2 - 0.2
27 | Y32 = 0.5 * X1 + 0.1 * X2 + 0.
28 | Y41 = 4. * X1 - 0.5 * X2 - 1.
29 | Y42 = -0.5 * X1 + X2 - 0.5
30 |
31 | fig = plt.figure(figsize=plt.figaspect(0.25))
32 | ax = fig.add_subplot(1, 4, 1, projection="3d")
33 | surf = ax.plot_surface(X1, X2, Y11, cmap=cm.coolwarm,
34 | linewidth=0, antialiased=False)
35 | ax = fig.add_subplot(1, 4, 2, projection="3d")
36 | surf = ax.plot_surface(X1, X2, Y21, cmap=cm.coolwarm,
37 | linewidth=0, antialiased=False)
38 | ax = fig.add_subplot(1, 4, 3, projection="3d")
39 | surf = ax.plot_surface(X1, X2, Y31, cmap=cm.coolwarm,
40 | linewidth=0, antialiased=False)
41 | ax = fig.add_subplot(1, 4, 4, projection="3d")
42 | surf = ax.plot_surface(X1, X2, Y41, cmap=cm.coolwarm,
43 | linewidth=0, antialiased=False)
44 | plt.show()
45 |
46 | fig = plt.figure(figsize=plt.figaspect(0.25))
47 | ax = fig.add_subplot(1, 4, 1, projection="3d")
48 | surf = ax.plot_surface(X1, X2, Y12, cmap=cm.coolwarm,
49 | linewidth=0, antialiased=False)
50 | ax = fig.add_subplot(1, 4, 2, projection="3d")
51 | surf = ax.plot_surface(X1, X2, Y22, cmap=cm.coolwarm,
52 | linewidth=0, antialiased=False)
53 | ax = fig.add_subplot(1, 4, 3, projection="3d")
54 | surf = ax.plot_surface(X1, X2, Y32, cmap=cm.coolwarm,
55 | linewidth=0, antialiased=False)
56 | ax = fig.add_subplot(1, 4, 4, projection="3d")
57 | surf = ax.plot_surface(X1, X2, Y42, cmap=cm.coolwarm,
58 | linewidth=0, antialiased=False)
59 | plt.show()
60 |
61 |
62 | Small = IT2FS_Gaussian_UncertStd(domain, [0, 0.15, 0.1, 1.])
63 | Big = IT2FS_Gaussian_UncertStd(domain, [1., 0.15, 0.1, 1.])
64 | # IT2FS_plot(Small, Big, title="Sets",
65 | # legends=["Small", "Big"])
66 |
67 | myIT2FLS = IT2TSK(product_t_norm, max_s_norm)
68 |
69 | myIT2FLS.add_input_variable("x1")
70 | myIT2FLS.add_input_variable("x2")
71 | myIT2FLS.add_output_variable("y1")
72 | myIT2FLS.add_output_variable("y2")
73 |
74 | myIT2FLS.add_rule([("x1", Small), ("x2", Small)],
75 | [("y1", {"const":1., "x1":1., "x2":1.}),
76 | ("y2", {"const":1., "x1":2., "x2":-1.})])
77 | myIT2FLS.add_rule([("x1", Small), ("x2", Big)],
78 | [("y1", {"const":0.5, "x1":1.5, "x2":0.5}),
79 | ("y2", {"const":0.5, "x1":1.5, "x2":-0.5})])
80 | myIT2FLS.add_rule([("x1", Big), ("x2", Small)],
81 | [("y1", {"const":-0.2, "x1":2., "x2":0.1}),
82 | ("y2", {"const":0., "x1":0.5, "x2":0.1})])
83 | myIT2FLS.add_rule([("x1", Big), ("x2", Big)],
84 | [("y1", {"const":-1., "x1":4., "x2":-0.5}),
85 | ("y2", {"const":-0.5, "x1":-0.5, "x2":1.})])
86 |
87 |
88 | Z1 = zeros(shape=X1.shape)
89 | Z2 = zeros(shape=X1.shape)
90 |
91 | for i, x1 in zip(range(len(domain)), domain):
92 | for j, x2 in zip(range(len(domain)), domain):
93 | z = myIT2FLS.evaluate({"x1":x1, "x2":x2})
94 | Z1[i, j], Z2[i, j] = z["y1"], z["y2"]
95 |
96 |
97 | fig = plt.figure()
98 | ax = fig.add_subplot(111, projection="3d")
99 | surf = ax.plot_surface(X1, X2, Z1, cmap=cm.coolwarm,
100 | linewidth=0, antialiased=False)
101 | ax.zaxis.set_major_locator(LinearLocator(10))
102 | ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
103 | fig.colorbar(surf, shrink=0.5, aspect=5)
104 | plt.show()
105 |
106 | fig = plt.figure()
107 | ax = fig.add_subplot(111, projection="3d")
108 | surf = ax.plot_surface(X1, X2, Z2, cmap=cm.coolwarm,
109 | linewidth=0, antialiased=False)
110 | ax.zaxis.set_major_locator(LinearLocator(10))
111 | ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
112 | fig.colorbar(surf, shrink=0.5, aspect=5)
113 | plt.show()
114 |
115 |
116 |
117 |
118 |
119 |
120 |
121 |
122 |
123 |
124 |
125 |
--------------------------------------------------------------------------------
/examples/ex_9.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Sat Jul 25 00:11:49 2020
5 |
6 | @author: arslan
7 | """
8 |
9 | from pyit2fls import (IT2Mamdani, IT2FS_Gaussian_UncertStd, IT2FS_plot, \
10 | product_t_norm, max_s_norm, crisp, )
11 | from numpy import (linspace, meshgrid, zeros, )
12 | from mpl_toolkits import mplot3d
13 | import matplotlib.pyplot as plt
14 | from matplotlib import cm
15 | from matplotlib.ticker import (LinearLocator, FormatStrFormatter, )
16 |
17 | # Defining the domain of the input variable x1.
18 | domain1 = linspace(1., 2., 100)
19 |
20 | # Defining the domain of the input variable x2.
21 | domain2 = linspace(2., 3., 100)
22 |
23 | # Defining the domain of the output variable y1.
24 | domain3 = linspace(3., 4., 100)
25 |
26 | # Defining the domain of the output variable y2.
27 | domain4 = linspace(4., 5., 100)
28 |
29 | # Defining the Small set for the input variable x1.
30 | Small1 = IT2FS_Gaussian_UncertStd(domain1, [1., 0.2, 0.025, 1.])
31 |
32 | # Defining the Medium set for the input variable x1.
33 | Medium1 = IT2FS_Gaussian_UncertStd(domain1, [1.5, 0.3, 0.025, 1.])
34 |
35 | # Defining the Large set for the input variable x1.
36 | Large1 = IT2FS_Gaussian_UncertStd(domain1, [2., 0.4, 0.025, 1.])
37 |
38 | # Plotting the sets defined for the input variable x1.
39 | IT2FS_plot(Small1, Medium1, Large1,
40 | legends=["Small", "Medium", "large"])
41 |
42 |
43 | # Defining the Small set for the input variable x2.
44 | Small2 = IT2FS_Gaussian_UncertStd(domain2, [2., 0.4, 0.025, 1.])
45 |
46 | # Defining the Medium set for the input variable x2.
47 | Medium2 = IT2FS_Gaussian_UncertStd(domain2, [2.5, 0.3, 0.025, 1.])
48 |
49 | # Defining the Large set for the input variable x1.
50 | Large2 = IT2FS_Gaussian_UncertStd(domain2, [3., 0.2, 0.025, 1.])
51 |
52 | # Plotting the sets defined for the input variable x1.
53 | IT2FS_plot(Small2, Medium2, Large2,
54 | legends=["Small", "Medium", "large"])
55 |
56 | # Defining the Low set for the output variable y1
57 | Low1 = IT2FS_Gaussian_UncertStd(domain3, [3., 0.5, 0.025, 1.])
58 |
59 | # Defining the High set for the output variable y1
60 | High1 = IT2FS_Gaussian_UncertStd(domain3, [4., 0.5, 0.025, 1.])
61 |
62 | # Plotting the sets defined for the output variable y1.
63 | IT2FS_plot(Low1, High1,
64 | legends=["Low", "High"])
65 |
66 |
67 | # Defining the Low set for the output variable y2
68 | Low2 = IT2FS_Gaussian_UncertStd(domain4, [4., 0.5, 0.025, 1.])
69 |
70 | # Defining the High set for the output variable y2
71 | High2 = IT2FS_Gaussian_UncertStd(domain4, [5., 0.5, 0.025, 1.])
72 |
73 | # Plotting the sets defined for the output variable y2.
74 | IT2FS_plot(Low2, High2,
75 | legends=["Low", "High"])
76 |
77 | # Defining the mamdani interval type 2 fuzzy logic system
78 | myIT2FLS = IT2Mamdani(product_t_norm, max_s_norm)
79 |
80 | # Adding the input variables to the myIT2FLS
81 | myIT2FLS.add_input_variable("x1")
82 | myIT2FLS.add_input_variable("x2")
83 |
84 | # Adding the output variables to the myIT2FLS
85 | myIT2FLS.add_output_variable("y1")
86 | myIT2FLS.add_output_variable("y2")
87 |
88 | # Defining the rule base of the MyIT2FLS
89 | myIT2FLS.add_rule([("x1", Small1), ("x2", Small2)], [("y1", Low1), ("y2", Low2)])
90 | myIT2FLS.add_rule([("x1", Small1), ("x2", Medium2)], [("y1", Low1), ("y2", Low2)])
91 | myIT2FLS.add_rule([("x1", Small1), ("x2", Large2)], [("y1", Low1), ("y2", High2)])
92 | myIT2FLS.add_rule([("x1", Medium1), ("x2", Small2)], [("y1", Low1), ("y2", Low2)])
93 | myIT2FLS.add_rule([("x1", Medium1), ("x2", Medium2)], [("y1", Low1), ("y2", Low2)])
94 | myIT2FLS.add_rule([("x1", Medium1), ("x2", Large2)], [("y1", High1), ("y2", High2)])
95 | myIT2FLS.add_rule([("x1", Large1), ("x2", Small2)], [("y1", High1), ("y2", Low2)])
96 | myIT2FLS.add_rule([("x1", Large1), ("x2", Medium2)], [("y1", High1), ("y2", High2)])
97 | myIT2FLS.add_rule([("x1", Large1), ("x2", Large2)], [("y1", High1), ("y2", High2)])
98 |
99 | # Evaluating the outputs of the myIT2FLS for the points in the input domain,
100 | # and plotting the output surfaces.
101 | X1, X2 = meshgrid(domain1, domain2)
102 | Z1 = zeros(shape=(len(domain1), len(domain2)))
103 | Z2 = zeros(shape=(len(domain1), len(domain2)))
104 | for i, x1 in zip(range(len(domain1)), domain1):
105 | for j, x2 in zip(range(len(domain2)), domain2):
106 | it2out, tr = myIT2FLS.evaluate({"x1":x1, "x2":x2})
107 | Z1[i, j], Z2[i, j] = crisp(tr["y1"]), crisp(tr["y2"])
108 |
109 | fig = plt.figure()
110 | ax = fig.add_subplot(111, projection="3d")
111 | surf = ax.plot_surface(X1, X2, Z1, cmap=cm.coolwarm,
112 | linewidth=0, antialiased=False)
113 | ax.zaxis.set_major_locator(LinearLocator(10))
114 | ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
115 | fig.colorbar(surf, shrink=0.5, aspect=5)
116 | plt.show()
117 |
118 | fig = plt.figure()
119 | ax = fig.add_subplot(111, projection="3d")
120 | surf = ax.plot_surface(X1, X2, Z2, cmap=cm.coolwarm,
121 | linewidth=0, antialiased=False)
122 | ax.zaxis.set_major_locator(LinearLocator(10))
123 | ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))
124 | fig.colorbar(surf, shrink=0.5, aspect=5)
125 | plt.show()
126 |
127 |
128 |
129 |
130 |
131 |
132 |
--------------------------------------------------------------------------------
/examples/images/10_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/10_1.png
--------------------------------------------------------------------------------
/examples/images/10_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/10_2.png
--------------------------------------------------------------------------------
/examples/images/10_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/10_3.png
--------------------------------------------------------------------------------
/examples/images/10_4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/10_4.png
--------------------------------------------------------------------------------
/examples/images/10_5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/10_5.png
--------------------------------------------------------------------------------
/examples/images/10_6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/10_6.png
--------------------------------------------------------------------------------
/examples/images/11_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/11_1.png
--------------------------------------------------------------------------------
/examples/images/11_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/11_2.png
--------------------------------------------------------------------------------
/examples/images/12_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/12_1.png
--------------------------------------------------------------------------------
/examples/images/12_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/12_2.png
--------------------------------------------------------------------------------
/examples/images/12_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/12_3.png
--------------------------------------------------------------------------------
/examples/images/13_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/13_1.png
--------------------------------------------------------------------------------
/examples/images/13_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/13_2.png
--------------------------------------------------------------------------------
/examples/images/13_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/13_3.png
--------------------------------------------------------------------------------
/examples/images/13_4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/13_4.png
--------------------------------------------------------------------------------
/examples/images/13_5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/13_5.png
--------------------------------------------------------------------------------
/examples/images/13_6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/13_6.png
--------------------------------------------------------------------------------
/examples/images/14_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/14_1.png
--------------------------------------------------------------------------------
/examples/images/14_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/14_2.png
--------------------------------------------------------------------------------
/examples/images/14_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/14_3.png
--------------------------------------------------------------------------------
/examples/images/14_4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/14_4.png
--------------------------------------------------------------------------------
/examples/images/14_5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/14_5.png
--------------------------------------------------------------------------------
/examples/images/15_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/15_1.png
--------------------------------------------------------------------------------
/examples/images/15_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/15_2.png
--------------------------------------------------------------------------------
/examples/images/18_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/18_1.png
--------------------------------------------------------------------------------
/examples/images/18_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/18_2.png
--------------------------------------------------------------------------------
/examples/images/18_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/18_3.png
--------------------------------------------------------------------------------
/examples/images/18_4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/18_4.png
--------------------------------------------------------------------------------
/examples/images/18_5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/18_5.png
--------------------------------------------------------------------------------
/examples/images/18_6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/18_6.png
--------------------------------------------------------------------------------
/examples/images/18_7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/18_7.png
--------------------------------------------------------------------------------
/examples/images/19_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/19_1.png
--------------------------------------------------------------------------------
/examples/images/19_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/19_2.png
--------------------------------------------------------------------------------
/examples/images/19_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/19_3.png
--------------------------------------------------------------------------------
/examples/images/19_4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/19_4.png
--------------------------------------------------------------------------------
/examples/images/19_5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/19_5.png
--------------------------------------------------------------------------------
/examples/images/19_6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/19_6.png
--------------------------------------------------------------------------------
/examples/images/19_7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/19_7.png
--------------------------------------------------------------------------------
/examples/images/1_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/1_1.png
--------------------------------------------------------------------------------
/examples/images/20_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/20_3.png
--------------------------------------------------------------------------------
/examples/images/21_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/21_3.png
--------------------------------------------------------------------------------
/examples/images/22_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/22_1.png
--------------------------------------------------------------------------------
/examples/images/23_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/23_1.png
--------------------------------------------------------------------------------
/examples/images/24_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/24_1.png
--------------------------------------------------------------------------------
/examples/images/24_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/24_2.png
--------------------------------------------------------------------------------
/examples/images/24_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/24_3.png
--------------------------------------------------------------------------------
/examples/images/2_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/2_1.png
--------------------------------------------------------------------------------
/examples/images/2_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/2_2.png
--------------------------------------------------------------------------------
/examples/images/2_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/2_3.png
--------------------------------------------------------------------------------
/examples/images/3_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/3_1.png
--------------------------------------------------------------------------------
/examples/images/3_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/3_2.png
--------------------------------------------------------------------------------
/examples/images/3_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/3_3.png
--------------------------------------------------------------------------------
/examples/images/3_4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/3_4.png
--------------------------------------------------------------------------------
/examples/images/3_5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/3_5.png
--------------------------------------------------------------------------------
/examples/images/4_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/4_2.png
--------------------------------------------------------------------------------
/examples/images/4_4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/4_4.png
--------------------------------------------------------------------------------
/examples/images/5_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/5_1.png
--------------------------------------------------------------------------------
/examples/images/5_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/5_2.png
--------------------------------------------------------------------------------
/examples/images/5_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/5_3.png
--------------------------------------------------------------------------------
/examples/images/5_4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/5_4.png
--------------------------------------------------------------------------------
/examples/images/5_block.jpg:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/5_block.jpg
--------------------------------------------------------------------------------
/examples/images/6_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/6_1.png
--------------------------------------------------------------------------------
/examples/images/6_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/6_2.png
--------------------------------------------------------------------------------
/examples/images/6_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/6_3.png
--------------------------------------------------------------------------------
/examples/images/6_4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/6_4.png
--------------------------------------------------------------------------------
/examples/images/6_5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/6_5.png
--------------------------------------------------------------------------------
/examples/images/6_6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/6_6.png
--------------------------------------------------------------------------------
/examples/images/6_7.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/6_7.png
--------------------------------------------------------------------------------
/examples/images/6_8.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/6_8.png
--------------------------------------------------------------------------------
/examples/images/8_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/8_1.png
--------------------------------------------------------------------------------
/examples/images/8_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/8_2.png
--------------------------------------------------------------------------------
/examples/images/8_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/8_3.png
--------------------------------------------------------------------------------
/examples/images/8_4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/8_4.png
--------------------------------------------------------------------------------
/examples/images/9_1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/9_1.png
--------------------------------------------------------------------------------
/examples/images/9_2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/9_2.png
--------------------------------------------------------------------------------
/examples/images/9_3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/9_3.png
--------------------------------------------------------------------------------
/examples/images/9_4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/9_4.png
--------------------------------------------------------------------------------
/examples/images/9_5.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/9_5.png
--------------------------------------------------------------------------------
/examples/images/9_6.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/9_6.png
--------------------------------------------------------------------------------
/examples/images/IT2TSKFLSY1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/IT2TSKFLSY1.png
--------------------------------------------------------------------------------
/examples/images/IT2TSKFLSY2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/examples/images/IT2TSKFLSY2.png
--------------------------------------------------------------------------------
/markdown docs/MIT2FLS.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | ## Defining Interval Type 2 Mamdani Fuzzy Logic Systems
4 | One of the most common models of the fuzzy systems is Mamdani model. In constrast with TSK model, both of the inputs and outputs of the system in Mamdani model are fuzzy sets. There are two ways to create interval type 2 Mamdani fuzzy systems using PyIT2FLS:
5 |
6 | 1. Using **_Mamdani_** class
7 | 2. Using **_IT2FLS_** class
8 |
9 | In the following, it will be introduced how to use these two classes.
10 |
11 | ### **_Mamdani_** class
12 | The constructor function of the **_Mamdani_** class has six inputs:
13 |
14 | 1. **_t_norm_**: Function
15 | 2. **_s_norm_**: Function
16 | 3. **_method_**: String with Centroid default value
17 | 4. **_method_params_**: List with **_None_** default value
18 | 5. **_algorithm_**: Function with EIASC_algorithm default value
19 | 6. **_algorithm_params_**: List with **_None_** default value
20 |
21 | The **_t_norm_** and **_s_norm_** inputs can be selected from the t-norm and s-norm functions provided by the PyIT2FLS. The **_method_** can be one the methods listed below:
22 |
23 | 1. **_Centroid_**: Centroid method
24 | 2. **_CoSet_**: Center of sets method
25 | 3. **_CoSum_**: Center of sum method
26 | 4. **_Height_**: Height method
27 | 5. **_ModiHe_**: Modified height method
28 |
29 | The only method that needs a parameter is the **_ModiHe_** method. The **_method_params_** of the **_ModiHe_** method is a list of spread values corresponding with the IT2FSs. (For more details about this method, please refer to the type two fuzzy logic reference books.)
30 |
31 | The **_algorithm_** defines the type reduction algorithm, and can be selected from the algorithms listed below:
32 |
33 | 1. **_KM_algorithm_**
34 | 2. **_EKM_algorithm_**
35 | 3. **_WEKM_algorithm_**
36 | 4. **_TWEKM_algorithm_**
37 | 5. **_EIASC_algorithm_**
38 | 6. **_WM_algorithm_**
39 | 7. **_BMM_algorithm_**
40 | 8. **_LBMM_algorithm_**
41 | 9. **_NT_algorithm_**
42 |
43 | It must be noticed that the items of the above list are function names and must be imported from PyIT2FLS before using. Of these nine algorithms, only **_WEKM_algorithm_**, **_BMM_algorithm_**, and **_LBMM_algorithm_** algorithms need **_algorithm_params_**. **_algorithm_params_** should be defined as a list of floating point numbers. (For more details about these algorithms, please refer to the type two fuzzy logic reference books.)
44 |
45 | The **_Mamdani_** class has four functions embedded:
46 |
47 | 1. **_add_input_variable_**
48 | 2. **_add_output_variable_**
49 | 3. **_add_rule_**
50 | 4. **_evaluate_**
51 |
52 | And, it has three parameters:
53 |
54 | 1. **_inputs_**: List of strings
55 | 2. **_outputs_**: List of strings
56 | 3. **_rules_**: List of tuples
57 |
58 | #### Functions:
59 | **_add_input_variable_** function: This function has a single input of type string, which is the name of a input variable. All the input variables must be defined for the system using this function. The variable name given to this function will be stored in the **_inputs_** list.
60 |
61 | **_add_output_variable_** function: As the previous function, the only input of the **_add_output_variable_** is a string. Similarly, all the input variables must be defined for the system using this function. The variable name given to this function will be stored in the **_outputs_** list.
62 |
63 | **_add_rule_** function: This function has two inputs, **_antecedent_** and **_consequent_**, which are lists of tuples. Each tuple in the **_antecedent_** list, expresses the assignment of an input variable to a fuzzy set. So, the length of the **_antecedent_** list must be equal with **_inputs_** list. Similarly, the constitutive tuples of the **_consequent_** express the assignment of output variables to fuzzy sets. Also, the length of the **_consequent_** list must be equal with **_outputs_** list. Let's see an example of using the **_add_rule_** function. Assume that our system has two input variables named x1 and x2, and two output variables named y1 and y2. Also, assume that we have three fuzzy sets Small, Medium, and Large, and the rule base of our system is as below.
64 |
65 | 1. IF x1 is Small AND x2 is Small THEN y1 is Small AND y2 is Large
66 | 2. IF x1 is Medium AND x2 is Medium THEN y1 is Medium AND y2 is Small
67 | 3. IF x1 is Large AND x2 is Large THEN y1 is Large AND y2 is Small
68 |
69 | We can add these rule to the rule-base of the system using the code below:
70 |
71 | ```python
72 | mySys.add_rule([("x1", Small), ("x2", Small)], [("y1", Small), ("y2", Large)])
73 | mySys.add_rule([("x1", Medium), ("x2", Medium)], [("y1", Medium), ("y2", Small)])
74 | mySys.add_rule([("x1", Large), ("x2", Large)], [("y1", Large), ("y2", Small)])
75 | ```
76 |
77 | **_evaluate_** function: This function has a single input variable of type dictionary. The keys of this dictionary must be the input variable names added to the **_inputs_** list of the Mamdani class, and the values corresponded with the input variables must be their value to evaluate the system. Let's see an example of calling the **_evaluate_** function.
78 |
79 | ```python
80 | it2out, tr = mySys.evaluate({"x1":0.923, "x2":0.745})
81 | ```
82 |
83 | Evaluating the system using the **_Centroid_** method will return two outputs, interval type 2 output sets and type reduced outputs. These two outputs are of type dictionary. The keys of these dictionaries are output variable names, nd the values are **_IT2FSs_** and type reduced intervals. In order to calculate the crisp output using the outputs, the **_crisp_** function can be used. Also, **_TR_plot_** function can plot the type reduced outputs.
84 |
85 | ```python
86 | it2out["y1"].plot(filename="y1_out")
87 | TR_plot(domain, tr["y1"], filename="y1_tr")
88 | print(crisp(tr["y1"]))
89 | ```
90 |
91 | Evaluating the system using methods other than **_Centroid_** will return only type reduced outputs as a dictionary.
92 |
93 | ### **_IT2FLS_** class
94 | The constructor function of the **_IT2FLS_** class has no input parameters. The **_IT2FLS_** class has four functions embedded:
95 |
96 | 1. **_add_input_variable_**
97 | 2. **_add_output_variable_**
98 | 3. **_add_rule_**
99 | 4. **_evaluate_**
100 |
101 | And, it has three parameters:
102 |
103 | 1. **_inputs_**: List of strings
104 | 2. **_outputs_**: List of strings
105 | 3. **_rules_**: List of tuples
106 |
107 | The only difference between the functions of the **_IT2FLS_** class and **_Mamdani_** class is the inputs of the **_evaluate_** function. The inputs of the evaluate function are listed as below:
108 |
109 | 1. **_inputs_**: Dictionary
110 | 2. **_t_norm_**: Function
111 | 3. **_s_norm_**: Function
112 | 4. **_method_**: String with **_Centroid_** default value
113 | 5. **_method_params_**: List with **_None_** default value
114 | 6. **_algorithm_**: String with **_EIASC_** default value
115 | 7. **_algorithm_params_**: List with **_None_** default value
116 |
117 | The first input is similar to the only input of the Mamdani's **_evaluate_** function. The **_t_norm_** and the **_s_norm_** can be selected from the t-nomrs and s-norms provided by the PyIT2FLS. The **_method_** and the **_method_params_** are similar to the inputs of the constructor function of the **_Mamdani_** class. The **_algorithm_** is a string from the below list:
118 |
119 | 1. **_KM_**
120 | 2. **_EKM_**
121 | 3. **_WEKM_**
122 | 4. **_TWEKM_**
123 | 5. **_EIASC_**
124 | 6. **_WM_**
125 | 7. **_BMM_**
126 | 8. **_LBMM_**
127 | 9. **_NT_**
128 |
129 | Finally, the **_algorithm_params_** is similar to the **_algorithm_params_** input of the constructor function of the **_Mamdani_** class.
130 |
131 |
132 |
133 |
134 |
135 |
--------------------------------------------------------------------------------
/markdown docs/MT1FLS.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | ## Defining Type 1 Mamdani Fuzzy Logic Systems
4 | The **_T1Mamdani_** class is provided in PyIT2FLS for creating Type 1 Mamdani Fuzzy Logic Systems. The constructor function of the **_T1Mamdani_** class has two inputs:
5 |
6 | 1. **_engine_**: A string, indicating the inference engine of the system. The default value of this input is **_Product_**, but it can be selected among the engines Product, Minimum, Lukasiewicz, Zadeh, and Dienes-Rescher.
7 | 2. **_defuzzification_**: A string, indicating the defuzzification method of the system. The default value is **_CoG_**, which indicates the center of gravity defuzzification method. If the engine of the system is **_Product_** or **_Minimum_**, the defuzzification can be selected among **_CoG_** and **_CoA_**.
8 |
9 | The **_T1Mamdani_** class has four functions embedded:
10 |
11 | 1. **_add_input_variable_**
12 | 2. **_add_output_variable_**
13 | 3. **_add_rule_**
14 | 4. **_evaluate_**
15 |
16 | And, it has three parameters:
17 |
18 | 1. **_inputs_**: List of strings
19 | 2. **_outputs_**: List of strings
20 | 3. **_rules_**: List of tuples
21 | 4. **_engine_**: String
22 | 5. **_defuzzification_**: String
23 |
24 | #### Functions:
25 |
26 | **_add_input_variable_** function: This function has a single input of type string, which is the name of a input variable. All the input variables must be defined for the system using this function. The variable name given to this function will be stored in the **_inputs_** list.
27 |
28 | **_add_output_variable_** function: As the previous function, the only input of the **_add_output_variable_** is a string. Similarly, all the input variables must be defined for the system using this function. The variable name given to this function will be stored in the **_outputs_** list.
29 |
30 | **_add_rule_** function: This function has two inputs, **_antecedent_** and **_consequent_**, which are lists of tuples. Each tuple in the **_antecedent_** list, expresses the assignment of an input variable to a fuzzy set. So, the length of the **_antecedent_** list must be equal with **_inputs_** list. Similarly, the constitutive tuples of the **_consequent_** express the assignment of output variables to fuzzy sets. Also, the length of the **_consequent_** list must be equal with **_outputs_** list. Let's see an example of using the **_add_rule_** function. Assume that our system has two input variables named x1 and x2, and two output variables named y1 and y2. Also, assume that we have three fuzzy sets Small, Medium, and Large, and the rule base of our system is as below.
31 |
32 | 1. IF x1 is Small AND x2 is Small THEN y1 is Small AND y2 is Large
33 | 2. IF x1 is Medium AND x2 is Medium THEN y1 is Medium AND y2 is Small
34 | 3. IF x1 is Large AND x2 is Large THEN y1 is Large AND y2 is Small
35 |
36 | We can add these rule to the rule-base of the system using the code below:
37 |
38 | ```python
39 | mySys.add_rule([("x1", Small), ("x2", Small)], [("y1", Small), ("y2", Large)])
40 | mySys.add_rule([("x1", Medium), ("x2", Medium)], [("y1", Medium), ("y2", Small)])
41 | mySys.add_rule([("x1", Large), ("x2", Large)], [("y1", Large), ("y2", Small)])
42 | ```
43 |
44 | **_evaluate_** function: This function has a single input variable of type dictionary. The keys of this dictionary must be the input variable names added to the **_inputs_** list of the Mamdani class, and the values corresponded with the input variables must be their value to evaluate the system. Let's see an example of calling the **_evaluate_** function.
45 |
46 | ```python
47 | s, c = mySys.evaluate({"x1":0.923, "x2":0.745})
48 | ```
49 |
50 | The output of the **_evaluate_** function depends on the defuzzification method selected. For **_CoG_** defuzzification method, the output is a tuple, which the first item is a dictionary of the output fuzzy sets and the second is a dictionary of the crisp outputs of the system. For other defuzzification methods, the output will only be a dictionary of crisp numbers. It must be noticed that the keys of the output dictionaries are the output names defined previously.
51 |
52 |
53 |
54 |
--------------------------------------------------------------------------------
/markdown docs/README.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | # PyIT2FLS
4 | Some extra explanations and examples about the PyIT2FLS are provided on the pages below:
5 |
6 | 1. [General description about the PyIT2FLS.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/overview.md)
7 | 2. [Defining different Type 1 Fuzzy Sets.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/defT1FS.md)
8 | 3. [Defining different Interval Type 2 Fuzzy Sets.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/defIT2FS.md)
9 | 4. [T-norms ans s-norms.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/Xnorm.md)
10 | 5. [Using the AND and OR operators for T1FSs](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/T1FSOp.md)
11 | 6. [Using the Meet and Join operators for IT2FLSs.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/meetjoin.md)
12 | 7. [Defining new t-norms and s-norms.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/defXnorm.md)
13 | 8. [Defining Type 1 Mamdani Fuzzy Logic Systems.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/MT1FLS.md)
14 | 9. [Defining Type 1 TSK Fuzzy Logic Systems.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/TSKT1FLS.md)
15 | 10. [Type reduction algorithms.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/typereduction.md)
16 | 11. [Defining Interval Type 2 Mamdani Fuzzy Logic Systems.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/MIT2FLS.md)
17 | 12. [Defining Interval Type 2 TSK Fuzzy Logic Systems.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/TSKIT2FLS.md)
18 | 13. [Using Different IT2 FLS evaluation methods.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/evalMethods.md)
19 | 14. [Examples for using the PyIT2FLS in science and engineering problems.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/examples.md)
20 |
--------------------------------------------------------------------------------
/markdown docs/T1FSOp.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | ## Type I Fuzzy Logic Operators
4 | Two essential operators in Type I Fuzzy Logic, are the AND and OR operators. These operators are defined in PyIY2FLS as two functions **_T1FS_AND_** and **_T1FS_OR_**. Both functions have four inputs. For these functions, the first three inputs are common, the universe of discourse, first **_T1FS_**, and second **_T1FS_**. The 4th input of the **_T1FS_AND_** function is the desired t-norm, and for the **_T1FS_OR_** function, is the desired s-norm.
5 |
6 | The t-norms and s-norms provided by the PyIT2FLS are introduced in previous sections of the documentations.
7 |
8 | It must be noted that the users can define new t-norms and s-norms, too. The user defined t-norm or s-norm functions must follow the structure below:
9 |
10 | ```python
11 | def userdefined_norm(a, b)
12 | return some_calculations(a, b)
13 | ```
14 |
15 | ### Example
16 | In this example we are going to apply the AND and OR operators on T1FSs and plot the outputs.
17 |
18 | ```python
19 | from pyit2fls import T1FS, gaussian_mf, T1FS_plot, T1FS_AND, T1FS_OR, min_t_norm, max_s_norm
20 | from numpy import linspace
21 |
22 | domain = linspace(0., 1., 1000)
23 | A = T1FS(domain, gaussian_mf, [0., 0.1, 1.])
24 | B = T1FS(domain, gaussian_mf, [0.5, 0.1, 1.])
25 | C = T1FS(domain, gaussian_mf, [1., 0.1, 1.])
26 | T1FS_plot(A, B, C, legends=["Small","Medium","Large"])
27 |
28 | AB = T1FS_AND(domain, A, B, min_t_norm)
29 | AB.plot()
30 |
31 | BC = T1FS_OR(domain, B, C, max_s_norm)
32 | BC.plot()
33 | ```
34 |
35 | The output plots of this example are represented as below.
36 |
37 | | **_SMALL_**, **_MEDIUM_**, and **_LARGE_** sets | AND of **_SMALL_** and **_MEDIUM_** | OR of **_MEDIUM_** and **_LARGE_** |
38 | |:---------------------:|:-----------:|:------------------:|
39 | |
|
|
|
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
55 |
56 |
--------------------------------------------------------------------------------
/markdown docs/TSKIT2FLS.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | ## Defining TSK Interval Type 2 Fuzzy Logic Systems
4 |
5 | TSK Fuzzy systems are used in a wide range of the scientific and engineering applications. The difference between TSK model and Mamdani model is the outputs of the systems. In the TSK model, outputs are not fuzzy sets but some functions. The PyIT2FLS toolkit provides the **_IT2TSK_** class for creating IT2 TSK FLSs. The **_IT2TSK_** class is designed based on the reference:
6 |
7 | Mendel, Jerry, et al. Introduction to type-2 fuzzy logic control: theory and applications. John Wiley & Sons, 2014.
8 |
9 | ### **_IT2TSK_** class
10 | The constructor function of the **_IT2TSK_** class has two inputs:
11 |
12 | 1. **_t_norm_**: Function
13 | 2. **_s_norm_**: Function
14 |
15 | The **_t_norm_** and **_s_norm_** inputs can be selected from the t-norm and s-norm functions provided by the PyIT2FLS.
16 |
17 | The **_IT2TSK_** class has four functions embedded:
18 |
19 | 1. **_add_input_variable_**
20 | 2. **_add_output_variable_**
21 | 3. **_add_rule_**
22 | 4. **_evaluate_**
23 |
24 | And, it has three parameters:
25 |
26 | 1. **_inputs_**: List of strings
27 | 2. **_outputs_**: List of strings
28 | 3. **_rules_**: List of tuples
29 |
30 | #### Functions:
31 | **_add_input_variable_** function: This function has a single input of type string, which is the name of a input variable. All the input variables must be defined for the system using this function. The variable name given to this function will be stored in the **_inputs_** list.
32 |
33 | **_add_output_variable_** function: As the previous function, the only input of the **_add_output_variable_** is a string. Similarly, all the input variables must be defined for the system using this function. The variable name given to this function will be stored in the **_outputs_** list.
34 |
35 | **_add_rule_** function: This function has two inputs, **_antecedent_** and **_consequent_**, which are lists of tuples. Each tuple in the **_antecedent_** list, expresses the assignment of an input variable to a fuzzy set. So, the length of the **_antecedent_** list must be equal with **_inputs_** list. The constitutive tuples of the **_consequent_** express the assignment of output variables to output states. The second element of the tuples in **_consequent_** list, must be a dictionary. This dictionary shows the output polynomial in the case of the rule. For example let an output polynomial be as 2 x1 + 4 x2 + 5. Then the dictionary for this case would be {"const":5., "x1":2., "x2":4.}. Note that this is written for an IT2 TSK FLS with two inputs, named x1 and x2. Also, the length of the **_consequent_** list must be equal with **_outputs_** list. Let's see an example of using the **_add_rule_** function. Assume that our system has two input variables named x1 and x2, and two output variables named y1 and y2. Also, assume that we have two fuzzy sets Small and Big, and the rule base of our system is as below.
36 |
37 | 1. IF x1 is Small AND x2 is Small THEN y1 = x1 + x2 + 1 AND y2 = 2 x1 - x2 + 1
38 | 2. IF x1 is Small AND x2 is Big THEN y1 = 1.5 x1 + 0.5 x2 + 0.5 AND y2 = 1.5 x1 - 0.5 x2 + 0.5
39 | 3. IF x1 is Big AND x2 is Small THEN y1 = 2 x1 + 0.1 x2 - 0.2 AND y2 = 0.5 x1 + 0.1 x2
40 | 4. IF x1 is Big AND x2 is Big THEN y1 = 4 x1 - 0.5 x2 - 1 AND y2 = -0.5 x1 + x2 - 0.5
41 |
42 | We can add these rule to the rule-base of the system using the code below:
43 |
44 | ```python
45 | mySys.add_rule([("x1", Small), ("x2", Small)],
46 | [("y1", {"const":1., "x1":1., "x2":1.}),
47 | ("y2", {"const":1., "x1":2., "x2":-1.})])
48 | mySys.add_rule([("x1", Small), ("x2", Big)],
49 | [("y1", {"const":0.5, "x1":1.5, "x2":0.5}),
50 | ("y2", {"const":0.5, "x1":1.5, "x2":-0.5})])
51 | mySys.add_rule([("x1", Big), ("x2", Small)],
52 | [("y1", {"const":-0.2, "x1":2., "x2":0.1}),
53 | ("y2", {"const":0., "x1":0.5, "x2":0.1})])
54 | mySys.add_rule([("x1", Big), ("x2", Big)],
55 | [("y1", {"const":-1., "x1":4., "x2":-0.5}),
56 | ("y2", {"const":-0.5, "x1":-0.5, "x2":1.})])
57 | ```
58 |
59 | **_evaluate_** function: This function has a single input variable of type dictionary. The keys of this dictionary must be the input variable names previously added to the **_inputs_** list of the **_IT2TSK_** class. The values corresponded with the input variables in the dictionary must be their values to evaluate the system. Let's see an example of calling the **_evaluate_** function.
60 |
61 | ```python
62 | y = mySys.evaluate({"x1":0.923, "x2":0.745})
63 | print(y["y1"], y["y2"])
64 | ```
65 |
66 |
67 |
68 |
69 |
--------------------------------------------------------------------------------
/markdown docs/TSKT1FLS.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | ## Defining TSK Type 1 Fuzzy Logic Systems
4 | In the TSK model, outputs are not fuzzy sets but some functions. The PyIT2FLS toolkit provides the **_T1TSK_** class for creating T1 TSK FLSs. The **_T1TSK_** class is designed based on the reference:
5 |
6 | Wang, Li-Xin. A course in fuzzy systems and control. Prentice-Hall, Inc., 1996.
7 |
8 | ### **_T1TSK_** class
9 | The constructor function of the **_T1TSK_** class has no inputs.
10 |
11 | The **_T1TSK_** class has four functions embedded:
12 |
13 | 1. **_add_input_variable_**
14 | 2. **_add_output_variable_**
15 | 3. **_add_rule_**
16 | 4. **_evaluate_**
17 |
18 | And, it has three parameters:
19 |
20 | 1. **_inputs_**: List of strings
21 | 2. **_outputs_**: List of strings
22 | 3. **_rules_**: List of tuples
23 |
24 | #### Functions:
25 | **_add_input_variable_** function: This function has a single input of type string, which is the name of a input variable. All the input variables must be defined for the system using this function. The variable name given to this function will be stored in the **_inputs_** list.
26 |
27 | **_add_output_variable_** function: As the previous function, the only input of the **_add_output_variable_** is a string. Similarly, all the input variables must be defined for the system using this function. The variable name given to this function will be stored in the **_outputs_** list.
28 |
29 | **_add_rule_** function: This function has two inputs, **_antecedent_** and **_consequent_**, which are lists of tuples. Each tuple in the **_antecedent_** list, expresses the assignment of an input variable to a fuzzy set. So, the length of the **_antecedent_** list must be equal with **_inputs_** list. The constitutive tuples of the **_consequent_** express the assignment of output variables to output functions. So the second element of the tuples in **_consequent_** list, must be a function (or more generally a callable object). These functions can have input variables, too, and they are passed when the evaluate function of the **_T1TSK_** class is called. The length of the **_consequent_** list must be equal with **_outputs_** list. Let's see an example of using the **_add_rule_** function. Assume that our system has two input variables named x1 and x2, and eight output functions named yij, i=1, ..., 4, j = 1, 2. Also, assume that we have two fuzzy sets Small and Big, and the rule base of our system is as below.
30 |
31 | 1. IF x1 is Small AND x2 is Small THEN y1 = y11(x1, x2) AND y2 = y12(x1, x2)
32 | 2. IF x1 is Small AND x2 is Big THEN y1 = y21(x1, x2) AND y2 = y22(x1, x2)
33 | 3. IF x1 is Big AND x2 is Small THEN y1 = y31(x1, x2) AND y2 = y32(x1, x2)
34 | 4. IF x1 is Big AND x2 is Big THEN y1 = y41(x1, x2) AND y2 = y42(x1, x2)
35 |
36 | ```python
37 | SYS.add_rule([("x1", Small), ("x2", Small)],
38 | [("y1", y11),
39 | ("y2", y12)])
40 | SYS.add_rule([("x1", Small), ("x2", Big)],
41 | [("y1", y21),
42 | ("y2", y22)])
43 | SYS.add_rule([("x1", Big), ("x2", Small)],
44 | [("y1", y31),
45 | ("y2", y32)])
46 | SYS.add_rule([("x1", Big), ("x2", Big)],
47 | [("y1", y41),
48 | ("y2", y42)])
49 | ```
50 |
51 | **_evaluate_** function: This function has two inputs. The first one is of type dictionary. The keys of this dictionary must be the input variable names previously added to the **_inputs_** list of the **_T1TSK_** class. The values corresponded with the input variables in the dictionary must be their values to evaluate the system. The second input of the function is a tuple, which indicates the parameters of the functions given as the consequent of the fuzzy rules. Let's see an example of calling the **_evaluate_** function.
52 |
53 | ```python
54 | y = mySys.evaluate({"x1":0.923, "x2":0.745}, params=(2, 4))
55 | print(y["y1"], y["y2"])
56 | ```
57 |
58 | The only output of the **_evaluate_** function is a dictionary, which keys are output variable names and the values are the outputs.
59 |
60 |
61 |
--------------------------------------------------------------------------------
/markdown docs/Xnorm.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | ## T-norms
4 | T-norms defined in the PyIT2FLS are listed as below. All these functions have two inputs and one output.
5 |
6 | | T-norm | Function |
7 | |:--------------------------:|:------------------------:|
8 | | Minimum t-norm | min_t_norm |
9 | | Product t-norm | product_t_norm |
10 | | Lukasiewicz t-norm | lukasiewicz_t_norm |
11 | | Drastic t-norm | drastic_t_norm |
12 | | Nilpotent minimum t-norm | nilpotent_minimum_t_norm |
13 | | Hamacher product t-norm | hamacher_product_t_norm |
14 |
15 | ## S-norms
16 | S-norms defined in the PyIT2FLS are listed as below. All these functions have two inputs and one output.
17 |
18 | | S-norm | Function |
19 | |:--------------------------:|:------------------------:|
20 | | Maximum s-norm | max_s_norm |
21 | | Probabilistic sum s-norm | probabilistic_sum_s_norm |
22 | | Bounded sum s-norm | bounded_sum_s_norm |
23 | | Drastic s-norm | drastic_s_norm |
24 | | Nilpotent maximum s-norm | nilpotent_maximum_s_norm |
25 | | Einstein sum s-norm | einstein_sum_s_norm |
26 |
--------------------------------------------------------------------------------
/markdown docs/_config.yml:
--------------------------------------------------------------------------------
1 | theme: jekyll-theme-leap-day
2 | title: PyIT2FLS
3 | description: Interval Type 2 Fuzzy Logic Systems in Python
4 | show_downloads: true
5 | google_analytics:
6 |
--------------------------------------------------------------------------------
/markdown docs/defXnorm.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | ## Defining new t-norms and s-norms
4 | Defining new t-norms and s-norms will be explained using examples. The first example is about defining a new s-norm and using it in join operator. We are going to define the probabilistic sum s-norm, which is defined as below:
5 |
6 |
7 |
8 | ```python
9 | from pyit2fls import IT2FS_Gaussian_UncertMean, join, IT2FS_plot
10 | from numpy import linspace
11 |
12 | def probabilistic_sum_s_norm(a, b):
13 | return a + b - a * b
14 |
15 | domain = linspace(0., 1., 1000)
16 | A = IT2FS_Gaussian_UncertMean(domain, [0., 0.1, 0.25, 1.])
17 | B = IT2FS_Gaussian_UncertMean(domain, [1., 0.1, 0.25, 1.])
18 | IT2FS_plot(A, B, legends=["Small","Large"])
19 |
20 | AB = join(domain, A, B, probabilistic_sum_s_norm)
21 | AB.plot()
22 | ```
23 |
24 | The output plots of this example are represented as below.
25 |
26 | | The **_SMALL_** and **_LARGE_** sets | Join of the two sets |
27 | |:---------------------:|:-----------:|
28 | |
|
|
29 |
30 | In the next example we are going to define a new t-norm an use it in meet operator. Let's define Łukasiewicz t-norm defined by the formula below:
31 |
32 |
33 |
34 |
35 | ```python
36 | from pyit2fls import IT2FS_Gaussian_UncertMean, meet, IT2FS_plot
37 | from numpy import linspace, maximum
38 |
39 | def Lukasiewicz_t_norm(a, b):
40 | return maximum(0, a + b - 1)
41 |
42 | domain = linspace(0., 1., 1000)
43 | A = IT2FS_Gaussian_UncertMean(domain, [0., 0.1, 0.4, 1.])
44 | B = IT2FS_Gaussian_UncertMean(domain, [1., 0.1, 0.4, 1.])
45 | IT2FS_plot(A, B, legends=["Small","Large"])
46 |
47 | AB = meet(domain, A, B, Lukasiewicz_t_norm)
48 | AB.plot()
49 | ```
50 |
51 | The output plots of this example are represented as below.
52 |
53 | | The **_SMALL_** and **_LARGE_** sets | Meet of the two sets |
54 | |:---------------------:|:-----------:|
55 | |
|
|
56 |
57 |
58 |
59 |
--------------------------------------------------------------------------------
/markdown docs/evalMethods.md:
--------------------------------------------------------------------------------
1 | 
2 |
--------------------------------------------------------------------------------
/markdown docs/examples.md:
--------------------------------------------------------------------------------
1 | 
2 |
--------------------------------------------------------------------------------
/markdown docs/images/1.1._.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/markdown docs/images/1.1._.png
--------------------------------------------------------------------------------
/markdown docs/images/1.1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/markdown docs/images/1.1.png
--------------------------------------------------------------------------------
/markdown docs/images/1.2._.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/markdown docs/images/1.2._.png
--------------------------------------------------------------------------------
/markdown docs/images/1.2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/markdown docs/images/1.2.png
--------------------------------------------------------------------------------
/markdown docs/images/1.3._.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/markdown docs/images/1.3._.png
--------------------------------------------------------------------------------
/markdown docs/images/1.3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/markdown docs/images/1.3.png
--------------------------------------------------------------------------------
/markdown docs/images/2.1._.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/markdown docs/images/2.1._.png
--------------------------------------------------------------------------------
/markdown docs/images/2.1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/markdown docs/images/2.1.png
--------------------------------------------------------------------------------
/markdown docs/images/2.2._.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/markdown docs/images/2.2._.png
--------------------------------------------------------------------------------
/markdown docs/images/2.2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/markdown docs/images/2.2.png
--------------------------------------------------------------------------------
/markdown docs/images/2.3._.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/markdown docs/images/2.3._.png
--------------------------------------------------------------------------------
/markdown docs/images/2.3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/markdown docs/images/2.3.png
--------------------------------------------------------------------------------
/markdown docs/images/3.1.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/markdown docs/images/3.1.png
--------------------------------------------------------------------------------
/markdown docs/images/3.2.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/markdown docs/images/3.2.png
--------------------------------------------------------------------------------
/markdown docs/images/3.3.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/markdown docs/images/3.3.png
--------------------------------------------------------------------------------
/markdown docs/images/3.4.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/markdown docs/images/3.4.png
--------------------------------------------------------------------------------
/markdown docs/images/InvPenCon.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/markdown docs/images/InvPenCon.png
--------------------------------------------------------------------------------
/markdown docs/images/InvPenSets.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/markdown docs/images/InvPenSets.png
--------------------------------------------------------------------------------
/markdown docs/images/InvPenSt.png:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/Haghrah/PyIT2FLS/bb635bd11561bad154a5dc7a3a52d6bd8b89a6ae/markdown docs/images/InvPenSt.png
--------------------------------------------------------------------------------
/markdown docs/index.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | # PyIT2FLS
4 | Some extra explanations and examples about the PyIT2FLS are provided on the pages below:
5 |
6 | 1. [General description about the PyIT2FLS.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/overview.md)
7 | 2. [Defining different Type 1 Fuzzy Sets.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/defT1FS.md)
8 | 3. [Defining different Interval Type 2 Fuzzy Sets.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/defIT2FS.md)
9 | 4. [T-norms ans s-norms.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/Xnorm.md)
10 | 5. [Using the AND and OR operators for T1FSs](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/T1FSOp.md)
11 | 6. [Using the Meet and Join operators for IT2FLSs.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/meetjoin.md)
12 | 7. [Defining new t-norms and s-norms.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/defXnorm.md)
13 | 8. [Defining Type 1 Mamdani Fuzzy Logic Systems.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/MT1FLS.md)
14 | 9. [Defining Type 1 TSK Fuzzy Logic Systems.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/TSKT1FLS.md)
15 | 10. [Type reduction algorithms.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/typereduction.md)
16 | 11. [Defining Interval Type 2 Mamdani Fuzzy Logic Systems.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/MIT2FLS.md)
17 | 12. [Defining Interval Type 2 TSK Fuzzy Logic Systems.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/TSKIT2FLS.md)
18 | 13. [Using Different IT2 FLS evaluation methods.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/evalMethods.md)
19 | 14. [Examples for using the PyIT2FLS in science and engineering problems.](https://github.com/Haghrah/PyIT2FLS/blob/master/markdown%20docs/examples.md)
20 |
--------------------------------------------------------------------------------
/markdown docs/meetjoin.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | ## Interval Type II Fuzzy Logic Operators
4 | Two essential operators in Interval Type 2 Fuzzy Logic, are the meet and join operators. These operators are defined in PyIY2FLS as two functions **_meet_** and **_join_**. Both functions have four inputs. For these functions, the first three inputs are common, the universe of discourse, the first **_IT2FS_**, and the second **_IT2FS_**. The 4th input of the **_meet_** function is the desired t-norm, and for the **_join_** function, is the desired s-norm.
5 |
6 | The t-norms and s-norms provided by the PyIT2FLS are introduced in previous sections of the documentations.
7 |
8 | It must be noted that the users can define new t-norms and s-norms, too. The user defined t-norm or s-norm functions must follow the structure below:
9 |
10 | ```python
11 | def userdefined_norm(a, b)
12 | return some_calculations(a, b)
13 | ```
14 |
15 | ### Example
16 | In this example we are going to apply the meet and join operators on IT2FSs and plot the outputs.
17 |
18 | ```python
19 | from pyit2fls import IT2FS_Gaussian_UncertMean, IT2FS_plot, meet, join, min_t_norm, max_s_norm
20 | from numpy import linspace
21 |
22 | domain = linspace(0., 1., 1000)
23 | A = IT2FS_Gaussian_UncertMean(domain, [0., 0.1, 0.1, 1.])
24 | B = IT2FS_Gaussian_UncertMean(domain, [0.5, 0.1, 0.1, 1.])
25 | C = IT2FS_Gaussian_UncertMean(domain, [1., 0.1, 0.1, 1.])
26 | IT2FS_plot(A, B, C, legends=["Small","Medium","Large"])
27 |
28 | AB = meet(domain, A, B, min_t_norm)
29 | AB.plot()
30 |
31 | BC = join(domain, B, C, max_s_norm)
32 | BC.plot()
33 | ```
34 |
35 | The output plots of this example are represented as below.
36 |
37 | | **_SMALL_**, **_MEDIUM_**, and **_LARGE_** sets | Meet of **_SMALL_** and **_MEDIUM_** | Join of **_MEDIUM_** and **_LARGE_** |
38 | |:---------------------:|:-----------:|:------------------:|
39 | |
|
|
|
40 |
41 |
42 |
43 |
44 |
45 |
46 |
47 |
48 |
49 |
50 |
51 |
52 |
53 |
54 |
--------------------------------------------------------------------------------
/markdown docs/typereduction.md:
--------------------------------------------------------------------------------
1 | 
2 |
3 | ## Type reduction algorithms
4 | Type reduction algorithms have a key role in obtaining crisp numbers from type 2 fuzzy sets. Well-known type reduction algorithms, which are also supported by PyIT2FLS are listed as below:
5 |
6 | | Type Reduction Algorithm | Corresponding Function in PyIT2FLS |
7 | |:-----------------------------:|:----------------------------------:|
8 | | Karnik-Mendel algorithm | KM_algorithm |
9 | | Enhanced KM algorithm | EKM_algorithm |
10 | | Weighted EKM algorithm | WEKM_algorithm |
11 | | Trapezoidal WEKM algorithm | TWEKM_algorithm |
12 | | Enhanced IASC algorithm | EIASC_algorithm |
13 | | Wu-Mendel algorithm | WM_algorithm |
14 | | Begian-Melek-Mendel algorithm | BMM_algorithm |
15 | | BMM algorithm edited by Li et al.| LBMM_algorithm |
16 | | Nie-Tan algorithm | NT_algorithm |
17 |
18 | Users do not need to be directly involved with these functions and will only use them. How to use these algorithms will be explained in other sections.
19 |
20 |
--------------------------------------------------------------------------------
/pyit2fls/__init__.py:
--------------------------------------------------------------------------------
1 | from .pyit2fls import *
2 | from .fuzzymatrix import *
3 | from .learning import *
4 |
--------------------------------------------------------------------------------
/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup
2 |
3 |
4 | from os import path
5 | this_directory = path.abspath(path.dirname(__file__))
6 | with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
7 | long_description = f.read()
8 |
9 | setup(name='pyit2fls',
10 | version='0.8.6',
11 | description='Type 1 and Interval Type 2 Fuzzy Logic Systems in Python',
12 | long_description=long_description,
13 | long_description_content_type='text/markdown',
14 | url='https://github.com/Haghrah/PyIT2FLS',
15 | author='Amir Arslan Haghrah',
16 | author_email='arslan.haghrah@gmail.com',
17 | license='MIT',
18 | license_file='LICENSE',
19 | packages=['pyit2fls'],
20 | install_requires=['numpy', 'scipy', 'matplotlib', ],
21 | python_requires='>=3.6',
22 | zip_safe=False)
23 |
--------------------------------------------------------------------------------
/typereduction/MANIFEST:
--------------------------------------------------------------------------------
1 | # file GENERATED by distutils, do NOT edit
2 | setup.py
3 | typereduction/__init__.py
4 | typereduction/makefile
5 | typereduction/typereduction.c
6 | typereduction/typereduction.py
7 |
--------------------------------------------------------------------------------
/typereduction/MANIFEST.in:
--------------------------------------------------------------------------------
1 | include typereduction/makefile
2 | include typereduction/typereduction.c
3 |
--------------------------------------------------------------------------------
/typereduction/README.md:
--------------------------------------------------------------------------------
1 | Typereduction
2 | =============
3 |
4 | Typereduction library contains Ctypes-based implementation of the type reduction algorithms ONLY for IT2FSs. It should be noted that some parts of the original type reduction algorithms have been edited for improving the execution speed.
5 |
6 | ### Installation
7 |
8 | Typereduction can be installed by unzipping the source code in a directory and using this command inside the typereduction folder:
9 |
10 | pip3 install .
11 |
12 | Or you can install from PyPI:
13 |
14 | pip3 install --upgrade typereduction
15 |
16 | **Note that typereduction has only been tested with GNU C compiler on Linux. Please report any compatibility issues.**
17 |
18 | ### Connecting with PyIT2FLS
19 |
20 | PyIT2FLS automatically detects whether the typereduction toolkit has been installed or not and uses it in computations if installed.
21 |
22 |
23 |
24 |
25 |
--------------------------------------------------------------------------------
/typereduction/examples/ex_1.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Sun Apr 18 00:29:35 2021
5 |
6 | @author: arslan
7 | """
8 |
9 | from numpy import random, column_stack
10 | import typereduction
11 | from pyit2fls import EIASC_algorithm, KM_algorithm, EKM_algorithm, WM_algorithm
12 | from time import time
13 |
14 | # intervals = array([[0.1, 0.3, 0., 0.],
15 | # [0.2, 0.4, 0., 0.],
16 | # [0.3, 0.5, 0., 0.],
17 | # [0.4, 0.6, 0., 0.],
18 | # [0.5, 0.7, 3., 4.],
19 | # [0.6, 0.8, 4., 5.],
20 | # [0.7, 0.9, 5., 6.],
21 | # [0.8, 1.0, 6., 7.],
22 | # [0.9, 1.1, 0., 0.],
23 | # [1.0, 1.2, 0., 0.],
24 | # [1.1, 1.3, 0., 0.],
25 | # [0.0, 1.4, 10., 10.], ])
26 |
27 | N = 1001
28 | M = 100
29 | x = random.rand(N)
30 | fl = random.rand(N)
31 | fh = fl + random.rand(N)
32 | intervals = column_stack((x, x, fl, fh))
33 |
34 |
35 |
36 | t_ = 0
37 | for _ in range(M):
38 | t = time()
39 | EIASC_algorithm(intervals)
40 | t_ += time() - t
41 |
42 | print("EIASC python implementation:", t_)
43 |
44 | t_ = 0
45 | for _ in range(M):
46 | t = time()
47 | eiasc = typereduction.EIASC_algorithm(intervals)
48 | t_ += time() - t
49 |
50 | print("EIASC C implementation:", t_)
51 |
52 | t_ = 0
53 | for _ in range(M):
54 | t = time()
55 | KM_algorithm(intervals)
56 | t_ += time() - t
57 |
58 | print("KM python implementation:", t_)
59 |
60 | t_ = 0
61 | for _ in range(M):
62 | t = time()
63 | km = typereduction.KM_algorithm(intervals)
64 | t_ += time() - t
65 |
66 | print("KM C implementation:", t_)
67 |
68 | t_ = 0
69 | for _ in range(M):
70 | t = time()
71 | EKM_algorithm(intervals)
72 | t_ += time() - t
73 |
74 | print("EKM python implementation:", t_)
75 |
76 | t_ = 0
77 | for _ in range(M):
78 | t = time()
79 | ekm = typereduction.EKM_algorithm(intervals)
80 | t_ += time() - t
81 |
82 | print("EKM C implementation:", t_)
83 |
84 | t_ = 0
85 | for _ in range(M):
86 | t = time()
87 | WM_algorithm(intervals)
88 | t_ += time() - t
89 |
90 | print("WM python implementation:", t_)
91 |
92 | t_ = 0
93 | for _ in range(M):
94 | t = time()
95 | wm = typereduction.WM_algorithm(intervals)
96 | t_ += time() - t
97 |
98 | print("WM C implementation:", t_)
99 |
100 |
101 | print("KM:", km)
102 | print("EKM:", ekm)
103 | print("EIASC:", eiasc)
104 | print("WM:", wm)
105 |
106 |
107 |
--------------------------------------------------------------------------------
/typereduction/setup.py:
--------------------------------------------------------------------------------
1 | from setuptools import setup, Extension
2 | from setuptools.command.build_ext import build_ext
3 | from setuptools.command.build_py import build_py
4 | import subprocess
5 | import os
6 |
7 |
8 | class CustomBuildExt(build_ext):
9 | def run(self):
10 | # Run the Makefile to build your C extension
11 | if not os.path.exists('build'):
12 | os.makedirs('build')
13 | subprocess.check_call(['make']) # Adjust if your Makefile has specific targets
14 | super().run()
15 |
16 |
17 | class CustomBuildPy(build_py):
18 | def run(self):
19 | # Ensure `make` runs before building Python package
20 | subprocess.check_call(['make'])
21 | super().run()
22 |
23 | typreduction = Extension('typereduction', sources = ['typereduction/typereduction.c'])
24 |
25 | from os import path
26 | this_directory = path.abspath(path.dirname(__file__))
27 | with open(path.join(this_directory, 'README.md'), encoding='utf-8') as f:
28 | long_description = f.read()
29 |
30 | setup(name='typereduction',
31 | version='0.2.2',
32 | description='Implementation of CTypes-based type reduction algorithms for using with PyIT2FLS',
33 | long_description=long_description,
34 | long_description_content_type='text/markdown',
35 | ext_modules = [typreduction],
36 | url='https://github.com/Haghrah/PyIT2FLS/tree/master/typereduction',
37 | author='Amir Arslan Haghrah',
38 | author_email='arslan.haghrah@gmail.com',
39 | license='MIT',
40 | packages=['typereduction'],
41 | # zip_safe=False,
42 | )
43 |
44 |
--------------------------------------------------------------------------------
/typereduction/typereduction/__init__.py:
--------------------------------------------------------------------------------
1 | from .typereduction import *
2 |
--------------------------------------------------------------------------------
/typereduction/typereduction/makefile:
--------------------------------------------------------------------------------
1 | all:
2 | gcc -c -fPIC typereduction.c -o typereduction.o
3 | gcc -shared -Wl,-soname,libtypereduction.so -o libtypereduction.so typereduction.o
4 |
--------------------------------------------------------------------------------
/typereduction/typereduction/typereduction.py:
--------------------------------------------------------------------------------
1 | #!/usr/bin/env python3
2 | # -*- coding: utf-8 -*-
3 | """
4 | Created on Sun Apr 18 00:29:35 2021
5 |
6 | @author: arslan
7 | """
8 |
9 | from numpy import array, zeros, double
10 | import numpy.ctypeslib as npct
11 | from ctypes import c_int
12 | import pathlib
13 |
14 | array_2d_double = npct.ndpointer(dtype=double, ndim=2, flags="CONTIGUOUS")
15 | array_1d_double = npct.ndpointer(dtype=double, ndim=1, flags="CONTIGUOUS")
16 |
17 | # load the library, using numpy mechanisms
18 | path = pathlib.Path(__file__).parent.parent.absolute()
19 | libcd = npct.load_library("typereduction", str(path))
20 |
21 | # setup the return types and argument types
22 | libcd.EIASC_algorithm.restype = None
23 | libcd.EIASC_algorithm.argtypes = [array_2d_double, array_1d_double, c_int, array_1d_double]
24 |
25 | libcd.KM_algorithm.restype = None
26 | libcd.KM_algorithm.argtypes = [array_2d_double, array_1d_double, c_int, array_1d_double]
27 |
28 | libcd.EKM_algorithm.restype = None
29 | libcd.EKM_algorithm.argtypes = [array_2d_double, array_1d_double, c_int, array_1d_double]
30 |
31 | libcd.WM_algorithm.restype = None
32 | libcd.WM_algorithm.argtypes = [array_2d_double, array_1d_double, c_int, array_1d_double]
33 |
34 | def EIASC_algorithm(intervals, params=[]):
35 | o = zeros(shape=(2, ))
36 | libcd.EIASC_algorithm(intervals, array(params), len(intervals), o)
37 | return o
38 |
39 | def KM_algorithm(intervals, params=[]):
40 | o = zeros(shape=(2, ))
41 | libcd.KM_algorithm(intervals, array(params), len(intervals), o)
42 | return o
43 |
44 | def EKM_algorithm(intervals, params=[]):
45 | o = zeros(shape=(2, ))
46 | libcd.EKM_algorithm(intervals, array(params), len(intervals), o)
47 | return o
48 |
49 | def WM_algorithm(intervals, params=[]):
50 | o = zeros(shape=(2, ))
51 | libcd.WM_algorithm(intervals, array(params), len(intervals), o)
52 | return o
53 |
54 |
55 |
56 |
57 |
58 |
59 |
--------------------------------------------------------------------------------