Note
Go to the end to download the full example code or to run this example in your browser via Binder.
From the MATLAB toolbox: the popu workflow#
EASY-IEC users wrote a user function that draws one individual into a
column of subplots, created a population with popu_init and started the
loop with ies_main. easyiec.compat keeps this workflow so that old
MATLAB examples port line by line. Without an evaluator ies_main opens the
clickable matplotlib gallery; here a metric replaces the person so that the
example runs unattended.
A user function in the EASY-IEC style#
The classical demonstration: tune the three parameters of a damped sine so that it follows noisy measurements. The user function draws the model and the data on the axis it receives.
import matplotlib.pyplot as plt
import numpy as np
from easyiec.compat import UserFunctionProblem, ies_main, popu_init
from easyiec.evaluators import MetricEvaluator
t = np.linspace(0, 10, 60)
rng = np.random.default_rng(0)
data = 1.6 * np.exp(-0.25 * t) * np.sin(1.3 * t) + 0.08 * rng.standard_normal(t.size)
def model(chrom):
a, d, w = chrom
return a * np.exp(-d * t) * np.sin(w * t)
def userfun(chrom, axes):
ax = axes[0]
ax.plot(t, data, ".", color="0.6", ms=3)
ax.plot(t, model(chrom), color="#285780", lw=2)
ax.set_xticks([]), ax.set_yticks([])
LB, UB = [0.2, 0.0, 0.3], [3.0, 1.0, 3.0]
popu = popu_init(LB, UB, nind=9, seed=1)
problem = UserFunctionProblem(LB, UB, userfun) # only for the evaluator
fit = MetricEvaluator(problem, lambda c: -np.mean((model(c) - data) ** 2), noise=0.002, seed=1)
popu = ies_main(popu, 1, userfun, evaluator=fit, generations=15, seed=1)
print("generation", popu["generation"], "best chromosome", np.round(popu["chrom"][0], 3))
generation 16 best chromosome [1.519 0.368 1.272]
The final population as the toolbox showed it#
fig, axes = plt.subplots(1, 9, figsize=(11, 1.4))
for k, ax in enumerate(axes):
userfun(popu["chrom"][k], [ax])
ax.set_title(f"#{k + 1}", fontsize=8)
fig.suptitle("population after 15 generations (true parameters 1.6, 0.25, 1.3)", fontsize=9, y=1.2)
plt.show()

Total running time of the script: (0 minutes 0.102 seconds)