Open In Colab

#Algoritmo Genético

#Bibliotecas e módulos

!pip install pygad
!pip install control
Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/

Collecting pygad

  Downloading pygad-2.18.1-py3-none-any.whl (56 kB)

     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 56.3/56.3 KB 4.9 MB/s eta 0:00:00

Requirement already satisfied: matplotlib in /usr/local/lib/python3.8/dist-packages (from pygad) (3.2.2)

Requirement already satisfied: numpy in /usr/local/lib/python3.8/dist-packages (from pygad) (1.21.6)

Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.8/dist-packages (from matplotlib->pygad) (3.0.9)

Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.8/dist-packages (from matplotlib->pygad) (1.4.4)

Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.8/dist-packages (from matplotlib->pygad) (2.8.2)

Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.8/dist-packages (from matplotlib->pygad) (0.11.0)

Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.8/dist-packages (from python-dateutil>=2.1->matplotlib->pygad) (1.15.0)

Installing collected packages: pygad

Successfully installed pygad-2.18.1

Looking in indexes: https://pypi.org/simple, https://us-python.pkg.dev/colab-wheels/public/simple/

Collecting control

  Downloading control-0.9.3.post2-py3-none-any.whl (432 kB)

     ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 432.8/432.8 KB 13.0 MB/s eta 0:00:00

Requirement already satisfied: matplotlib in /usr/local/lib/python3.8/dist-packages (from control) (3.2.2)

Requirement already satisfied: scipy>=1.3 in /usr/local/lib/python3.8/dist-packages (from control) (1.7.3)

Requirement already satisfied: numpy in /usr/local/lib/python3.8/dist-packages (from control) (1.21.6)

Requirement already satisfied: cycler>=0.10 in /usr/local/lib/python3.8/dist-packages (from matplotlib->control) (0.11.0)

Requirement already satisfied: python-dateutil>=2.1 in /usr/local/lib/python3.8/dist-packages (from matplotlib->control) (2.8.2)

Requirement already satisfied: pyparsing!=2.0.4,!=2.1.2,!=2.1.6,>=2.0.1 in /usr/local/lib/python3.8/dist-packages (from matplotlib->control) (3.0.9)

Requirement already satisfied: kiwisolver>=1.0.1 in /usr/local/lib/python3.8/dist-packages (from matplotlib->control) (1.4.4)

Requirement already satisfied: six>=1.5 in /usr/local/lib/python3.8/dist-packages (from python-dateutil>=2.1->matplotlib->control) (1.15.0)

Installing collected packages: control

Successfully installed control-0.9.3.post2
import numpy as np
import pygad
import control as ct
import matplotlib.pyplot as plt
from matplotlib import rcParams
from matplotlib import animation, rc
from control.matlab import *
from control import matlab
from mpl_toolkits.mplot3d import axes3d
from pylab import *
from IPython.display import HTML
from control import place
from scipy import integrate


plt.rcParams['figure.figsize'] = [8, 8]
plt.rcParams.update({'font.size': 18})

#Função de Transferência

# Função de transferência
dt = 0.1
s = ct.tf('s')
num = [1]
den = [1,1,1,0]
G = ct.tf(num,den)

bode (G)
print(G)
plt.show()

      1
-------------
s^3 + s^2 + s

# Entrada ao degrau
def Step(system):
    plt.figure()
    yout, T = ct.step_response(system)
    plt.plot(T, yout)

Step(G)

#Função Custo

def PID(parms):
    global G, dt
    s = ct.tf('s')

    Kp = parms[0]
    Ti = parms[1]
    Td = parms[2]
    K = Kp*(1 + 1/(Ti*s) + Td*s/(0.001*s + 1))

    T0 = 0
    N = 600
    t = np.arange(T0,N*dt, dt)

    c = ct.series(K, G)
    Hy = ct.feedback(c, 1)

    t1, yout = ct.step_response(Hy, t)
    uout, t2, xout = lsim(K, U=1-yout, T=t)

    Q = 1
    R = 0.001

    J = dt*sum(Q*(1-yout[:])**2 + R*uout[:]**2)

    # # Plot saída
    # plt.plot(t,yout)
    # plt.title("Indivíduos")
    # plt.grid()
    # plt.show()
    
    return J, t, yout, uout, K
def fitness_func(solution, solution_idx):
    J, t,  yout, uout, K= PID(solution)
    return -J
def callback_gen(ga_instance):
  print("Generation: ", ga_instance.generations_completed)
  print("Fitness of the best solution: ", ga_instance.best_solution()[1])
  print(ga_instance.population)
last_fitness = 0
def on_generation(ga_instance):
    global last_fitness
    print("Generation = {generation}".format(generation=ga_instance.generations_completed))
    print("Fitness    = {fitness}".format(fitness=ga_instance.best_solution(pop_fitness=ga_instance.last_generation_fitness)[1]))
    print("Change     = {change}".format(change=ga_instance.best_solution(pop_fitness=ga_instance.last_generation_fitness)[1] - last_fitness))
    last_fitness = ga_instance.best_solution(pop_fitness=ga_instance.last_generation_fitness)[1]

#AG - Algorítimo Genético

#  Configuração dos Parâmetros do AG
fitness_function = fitness_func
# Definição da população e dos indivíduos
num_generations = 25
num_parents_mating = 2
num_pop = 25
num_genes = 3

init_range_low = 0.1
init_range_high = 10
# Elitismo
parent_selection_type = "sss"
keep_parents = 1
# Cruzamento
crossover_type = "two_points"
# Mutação
mutation_type = "random"
mutation_percent_genes = 0.01
mutation_num_genes = 1
ga_instance = pygad.GA(num_generations=num_generations,
                       num_parents_mating=num_parents_mating,
                       fitness_func=fitness_function,
                       sol_per_pop=num_pop,
                       num_genes=num_genes,
                       init_range_low=init_range_low,
                       init_range_high=init_range_high,
                       parent_selection_type=parent_selection_type,
                       keep_parents=keep_parents,
                       crossover_type=crossover_type,
                       mutation_type=mutation_type,
                       mutation_percent_genes=mutation_percent_genes,
                       callback_generation=callback_gen,
                       save_best_solutions=True,
                       save_solutions=True,
                       mutation_num_genes=mutation_num_genes,
                       allow_duplicate_genes=False,
                       stop_criteria="saturate_10",
                       on_generation=on_generation)
/usr/local/lib/python3.8/dist-packages/pygad/pygad.py:764: UserWarning: Starting from PyGAD 2.6.0, the callback_generation parameter is deprecated and will be removed in a later release of PyGAD. Please use the on_generation parameter instead.
  if not self.suppress_warnings: warnings.warn("Starting from PyGAD 2.6.0, the callback_generation parameter is deprecated and will be removed in a later release of PyGAD. Please use the on_generation parameter instead.")
/usr/local/lib/python3.8/dist-packages/pygad/pygad.py:820: UserWarning: Use the 'save_best_solutions' parameter with caution as it may cause memory overflow when either the number of generations or number of genes is large.
  if not self.suppress_warnings: warnings.warn("Use the 'save_best_solutions' parameter with caution as it may cause memory overflow when either the number of generations or number of genes is large.")
/usr/local/lib/python3.8/dist-packages/pygad/pygad.py:828: UserWarning: Use the 'save_solutions' parameter with caution as it may cause memory overflow when either the number of generations, number of genes, or number of solutions in population is large.
  if not self.suppress_warnings: warnings.warn("Use the 'save_solutions' parameter with caution as it may cause memory overflow when either the number of generations, number of genes, or number of solutions in population is large.")
ga_instance.run()
/usr/local/lib/python3.8/dist-packages/control/timeresp.py:935: UserWarning: return_x specified for a transfer function system. Internal conversion to state space used; results may meaningless.
  warnings.warn(
Generation:  1
Fitness of the best solution:  -180.97871163439666
[[2.07459768 7.03652983 1.23170834]
 [3.16142278 7.03652983 1.28872698]
 [2.07459768 2.85730182 1.04453088]
 [2.07459768 1.14480045 1.23170834]
 [3.16142278 7.03652983 1.82949451]
 [2.75005406 1.99888046 1.23170834]
 [3.56145269 1.99888046 1.23170834]
 [2.42771972 1.99888046 1.23170834]
 [3.65284509 1.99888046 1.23170834]
 [3.16142278 7.24116293 1.23170834]
 [1.47704299 1.99888046 1.04453088]
 [3.92254696 7.03652983 1.23170834]
 [3.28736782 1.99888046 1.23170834]
 [2.07459768 1.99888046 1.40894434]
 [1.29520081 1.99888046 1.04453088]
 [2.07459768 1.63895422 1.23170834]
 [1.28131808 1.99888046 1.04453088]
 [2.07459768 6.06141902 1.04453088]
 [2.57943595 1.99888046 1.04453088]
 [3.16142278 7.03652983 1.82118523]
 [2.69241258 1.99888046 1.23170834]
 [2.07459768 6.06799966 1.04453088]
 [3.56722758 7.03652983 1.04453088]
 [2.01033825 1.99888046 1.23170834]
 [3.16142278 6.5479837  1.04453088]]
Generation:  2
Fitness of the best solution:  -24.722152943647707
[[1.28131808 1.99888046 1.04453088]
 [2.09949845 1.99888046 1.04453088]
 [1.29520081 1.99888046 1.0129344 ]
 [1.29520081 2.22192974 1.04453088]
 [0.82004067 1.99888046 1.04453088]
 [1.29520081 1.99888046 0.98087778]
 [1.29520081 1.16314784 1.04453088]
 [1.87806643 1.99888046 1.04453088]
 [1.29520081 1.99888046 1.8447068 ]
 [1.28131808 1.99888046 0.32813766]
 [1.5355591  1.99888046 1.04453088]
 [0.58614149 1.99888046 1.04453088]
 [1.28131808 2.0880843  1.04453088]
 [2.26926661 1.99888046 1.04453088]
 [1.29520081 2.7712763  1.04453088]
 [1.28131808 1.4141959  1.04453088]
 [1.29520081 2.36576298 1.04453088]
 [1.28131808 1.99888046 0.70622684]
 [1.29520081 1.99888046 0.68931262]
 [1.28131808 1.99888046 1.03751326]
 [0.45449538 1.99888046 1.04453088]
 [0.99333261 1.99888046 1.04453088]
 [1.04672293 1.99888046 1.04453088]
 [1.28131808 1.99888046 1.05712917]
 [1.29520081 2.58456241 1.04453088]]
Generation:  3
Fitness of the best solution:  -8.192181602589772
[[ 0.45449538  1.99888046  1.04453088]
 [-0.36621069  1.99888046  1.04453088]
 [ 0.58614149  1.99888046  0.55517176]
 [ 0.78056108  1.99888046  1.04453088]
 [ 0.58614149  2.4595645   1.04453088]
 [-0.08957035  1.99888046  1.04453088]
 [ 0.45449538  1.99888046  1.84548136]
 [ 0.45449538  1.99888046  1.29708686]
 [-0.09706325  1.99888046  1.04453088]
 [ 0.45449538  2.74790227  1.04453088]
 [ 1.07363283  1.99888046  1.04453088]
 [ 0.45449538  1.57339222  1.04453088]
 [ 1.30683791  1.99888046  1.04453088]
 [ 0.45449538  2.13104472  1.04453088]
 [ 0.58614149  2.66586669  1.04453088]
 [ 0.58614149  1.61688355  1.04453088]
 [-0.34337124  1.99888046  1.04453088]
 [-0.36872195  1.99888046  1.04453088]
 [ 0.58614149  1.63256771  1.04453088]
 [ 0.45449538  1.99888046  0.45982315]
 [ 1.14267477  1.99888046  1.04453088]
 [ 0.45449538  1.99888046  1.68204579]
 [ 0.58614149  1.00184849  1.04453088]
 [ 0.45449538  2.87866592  1.04453088]
 [ 0.58614149  1.03960542  1.04453088]]
Generation:  4
Fitness of the best solution:  -6.959651271386772
[[ 0.45449538  1.99888046  0.45982315]
 [ 0.45449538  1.99888046  1.43070244]
 [ 0.58614149  1.99888046  0.70432687]
 [ 0.45449538  1.99888046  0.70955976]
 [ 0.58614149  1.99888046  0.24787504]
 [ 0.45449538  2.07431701  0.55517176]
 [ 0.58614149  1.99888046  1.19290294]
 [ 0.58614149  1.72833405  0.45982315]
 [ 0.58614149  2.78402656  0.55517176]
 [ 0.45449538  2.95568749  0.55517176]
 [ 0.58614149  1.75406559  0.45982315]
 [ 0.45449538  1.99888046  0.42955025]
 [-0.3734784   1.99888046  0.45982315]
 [ 0.58614149  1.99888046  0.70292078]
 [ 0.58614149  1.17007047  0.55517176]
 [ 0.58614149  1.44043918  0.45982315]
 [ 0.45449538  1.99888046  1.1444909 ]
 [ 0.45449538  2.89546477  0.45982315]
 [ 0.55672898  1.99888046  0.55517176]
 [ 0.45449538  1.99487012  0.45982315]
 [ 0.58614149  1.35881649  0.55517176]
 [ 0.45449538  1.99888046 -0.16723094]
 [ 0.17244246  1.99888046  0.55517176]
 [ 0.76427334  1.99888046  0.45982315]
 [ 0.45449538  1.36527078  0.55517176]]
Generation:  5
Fitness of the best solution:  -5.4188749328074355
[[ 0.45449538  2.89546477  0.45982315]
 [ 0.45449538  2.89546477  0.92049022]
 [ 0.45449538  2.09564266  0.55517176]
 [ 0.17244246  3.07868896  0.45982315]
 [ 0.17244246  1.99888046  1.44815087]
 [ 0.17244246  2.89546477  0.46571149]
 [-0.28316308  2.89546477  0.55517176]
 [-0.13042152  2.89546477  0.55517176]
 [ 0.45449538  1.99888046 -0.20173628]
 [ 1.03394215  2.89546477  0.45982315]
 [-0.75366651  2.89546477  0.55517176]
 [ 0.17244246  2.53295089  0.45982315]
 [-0.2298007   1.99888046  0.45982315]
 [ 0.45449538  2.22128257  0.55517176]
 [-0.16549938  1.99888046  0.55517176]
 [ 1.32137942  2.89546477  0.55517176]
 [ 0.17244246  3.40162094  0.55517176]
 [ 0.45449538  2.57788052  0.45982315]
 [ 0.45449538  1.99888046 -0.16264764]
 [ 0.45449538  3.27533824  0.55517176]
 [ 0.45449538  1.29164807  0.55517176]
 [ 0.45449538  1.99888046  0.63424457]
 [ 0.45449538  1.75476976  0.55517176]
 [ 0.08735812  1.99888046  0.45982315]
 [ 0.17244246  2.8002193   0.45982315]]
Generation:  6
Fitness of the best solution:  -4.72574462167547
[[0.17244246 3.40162094 0.55517176]
 [0.2606472  3.07868896 0.55517176]
 [0.17244246 3.07868896 0.78975567]
 [0.17244246 3.40162094 0.23578298]
 [0.17244246 3.07868896 1.45783992]
 [1.12948186 3.07868896 0.55517176]
 [0.17244246 4.01441516 0.45982315]
 [0.25457864 3.40162094 0.45982315]
 [0.52596381 3.07868896 0.45982315]
 [0.17244246 3.40162094 1.10074317]
 [0.85735498 3.40162094 0.45982315]
 [0.17244246 3.05891256 0.45982315]
 [0.17244246 3.07868896 0.2820466 ]
 [0.17244246 2.86278528 0.55517176]
 [0.17244246 2.87536619 0.55517176]
 [0.17244246 3.20493001 0.55517176]
 [0.17244246 3.40162094 0.64981198]
 [0.17244246 3.66998186 0.45982315]
 [0.17244246 3.07868896 0.31925826]
 [0.17244246 3.40162094 0.67185475]
 [0.17244246 3.07868896 0.59878439]
 [0.17244246 3.40162094 1.25535291]
 [0.17244246 3.24514135 0.45982315]
 [0.17244246 2.83967105 0.55517176]
 [0.17244246 3.07868896 0.23815343]]
Generation:  7
Fitness of the best solution:  -4.471071715020473
[[ 2.54578635e-01  3.40162094e+00  4.59823154e-01]
 [ 2.54578635e-01  3.40162094e+00  7.10538664e-01]
 [ 1.72442459e-01  2.60523641e+00  4.59823154e-01]
 [ 7.36610266e-01  4.01441516e+00  4.59823154e-01]
 [ 2.54578635e-01  4.01441516e+00  6.67174543e-01]
 [ 1.72442459e-01  3.40162094e+00  7.88047131e-01]
 [-1.58295856e-01  3.40162094e+00  4.59823154e-01]
 [ 4.83124094e-01  4.01441516e+00  4.59823154e-01]
 [ 1.72442459e-01  4.01441516e+00 -1.55954576e-03]
 [ 2.54578635e-01  4.01441516e+00  6.38590250e-01]
 [ 1.72442459e-01  3.40162094e+00 -4.66749618e-01]
 [ 1.46122938e-01  3.40162094e+00  4.59823154e-01]
 [ 1.72442459e-01  4.78412143e+00  4.59823154e-01]
 [ 2.54578635e-01  4.01441516e+00  6.57460241e-01]
 [ 1.72442459e-01  4.01441516e+00 -4.79089232e-01]
 [ 1.72442459e-01  4.18994947e+00  4.59823154e-01]
 [ 2.54578635e-01  4.21796787e+00  4.59823154e-01]
 [ 1.72442459e-01  3.40162094e+00  8.84162628e-01]
 [ 1.72442459e-01  3.25400823e+00  4.59823154e-01]
 [-3.76436622e-01  3.40162094e+00  4.59823154e-01]
 [ 1.72442459e-01  3.03188608e+00  4.59823154e-01]
 [ 1.72442459e-01  3.40162094e+00 -2.78566648e-01]
 [-4.87455489e-01  4.01441516e+00  4.59823154e-01]
 [ 2.54578635e-01  3.95279310e+00  4.59823154e-01]
 [ 1.72442459e-01  3.88747467e+00  4.59823154e-01]]
Generation:  8
Fitness of the best solution:  -3.7753967261962487
[[ 0.25457864  4.21796787  0.45982315]
 [ 0.25457864  4.21796787 -0.04938925]
 [ 0.94989733  3.9527931   0.45982315]
 [ 0.25457864  4.21796787 -0.11554659]
 [ 0.25457864  3.9527931   1.02954058]
 [ 0.25457864  5.10431332  0.45982315]
 [ 0.25457864  4.21796787  0.29513344]
 [ 0.25457864  4.21796787  0.38015872]
 [-0.07433964  3.9527931   0.45982315]
 [ 0.09165252  3.9527931   0.45982315]
 [ 0.25457864  3.80292108  0.45982315]
 [ 0.25457864  3.29982499  0.45982315]
 [ 0.25457864  3.2246434   0.45982315]
 [ 0.89453145  4.21796787  0.45982315]
 [-0.29267434  3.9527931   0.45982315]
 [ 0.21852207  3.9527931   0.45982315]
 [ 0.25457864  4.21796787 -0.33283455]
 [ 0.25457864  4.74355993  0.45982315]
 [ 0.25457864  3.71672072  0.45982315]
 [ 0.25457864  2.97685556  0.45982315]
 [ 0.25457864  4.41935744  0.45982315]
 [-0.17732903  3.9527931   0.45982315]
 [ 0.25457864  3.91065973  0.45982315]
 [ 0.25457864  5.10980398  0.45982315]
 [ 0.25457864  3.38532072  0.45982315]]
Generation:  9
Fitness of the best solution:  -3.5303812657713722
[[ 0.25457864  4.21796787 -0.04938925]
 [ 0.25457864  4.21796787  0.81564174]
 [ 0.25457864  4.29548555  0.29513344]
 [ 0.25457864  5.09890798 -0.04938925]
 [ 0.25457864  4.21796787  0.56791456]
 [ 1.1478545   4.21796787 -0.04938925]
 [ 0.25457864  4.21796787 -0.76923087]
 [-0.69301894  4.21796787 -0.04938925]
 [ 0.06229381  4.21796787  0.29513344]
 [ 0.13384576  4.21796787  0.29513344]
 [ 0.25457864  4.21796787 -0.28659602]
 [ 0.25457864  5.03508292 -0.04938925]
 [ 0.25457864  4.24405247 -0.04938925]
 [ 0.25457864  4.21796787  1.28671388]
 [-0.39206953  4.21796787 -0.04938925]
 [ 0.25457864  4.21796787  0.1687551 ]
 [ 0.25457864  4.21796787  0.02106534]
 [ 0.25457864  3.38073475 -0.04938925]
 [ 1.03071211  4.21796787  0.29513344]
 [ 0.25457864  4.21796787  0.04329904]
 [ 0.25457864  3.97906854  0.29513344]
 [-0.65183441  4.21796787  0.29513344]
 [ 0.25457864  4.21796787  0.88467525]
 [ 0.25457864  3.62871944 -0.04938925]
 [ 0.25457864  3.81178978 -0.04938925]]
Generation:  10
Fitness of the best solution:  -3.1631815568971735
[[ 0.25457864  5.09890798 -0.04938925]
 [ 0.25457864  5.49605528 -0.04938925]
 [ 0.25457864  5.18189634 -0.04938925]
 [-0.51199621  5.09890798 -0.04938925]
 [ 0.25457864  5.03508292 -0.71387206]
 [ 0.25457864  4.20715434 -0.04938925]
 [ 0.6954302   5.03508292 -0.04938925]
 [ 0.25457864  4.94376256 -0.04938925]
 [ 0.25457864  5.09890798 -0.11273747]
 [ 0.25457864  5.09890798 -0.71125985]
 [ 0.25457864  4.82022049 -0.04938925]
 [ 0.25457864  5.99826796 -0.04938925]
 [ 0.12646629  5.03508292 -0.04938925]
 [ 0.10532778  5.09890798 -0.04938925]
 [-0.21730277  5.03508292 -0.04938925]
 [ 0.25457864  5.09890798  0.90273769]
 [ 0.25457864  4.46873928 -0.04938925]
 [ 0.25457864  5.01062712 -0.04938925]
 [ 0.25457864  5.90925253 -0.04938925]
 [ 0.65392003  5.09890798 -0.04938925]
 [ 0.74275465  5.03508292 -0.04938925]
 [ 0.45974256  5.03508292 -0.04938925]
 [ 0.25457864  5.09890798 -0.62747956]
 [ 0.25457864  4.25438131 -0.04938925]
 [ 1.0895125   5.09890798 -0.04938925]]
Generation:  11
Fitness of the best solution:  -2.8212711473712333
[[ 0.45974256  5.03508292 -0.04938925]
 [ 1.45310439  5.99826796 -0.04938925]
 [ 0.45974256  5.75059959 -0.04938925]
 [ 0.25457864  4.39536867 -0.04938925]
 [ 1.06476421  5.99826796 -0.04938925]
 [-0.3822628   5.99826796 -0.04938925]
 [ 0.45974256  5.77752501 -0.04938925]
 [ 0.25457864  5.03508292 -0.33808098]
 [ 0.45974256  5.99826796  0.56126986]
 [ 0.45974256  5.99826796 -0.41004982]
 [ 0.22097995  5.99826796 -0.04938925]
 [-0.3761327   5.03508292 -0.04938925]
 [ 0.25457864  5.03508292 -0.01187146]
 [ 0.45974256  5.99826796 -0.02516016]
 [ 0.68060577  5.99826796 -0.04938925]
 [ 0.12881056  5.03508292 -0.04938925]
 [ 0.25457864  5.03508292  0.19712608]
 [ 0.25457864  5.03508292 -0.35020006]
 [ 0.25457864  5.75499201 -0.04938925]
 [ 0.45974256  5.99826796  0.27071282]
 [ 0.45974256  6.49813162 -0.04938925]
 [ 0.25457864  5.6262986  -0.04938925]
 [ 0.45974256  5.99826796  0.45445448]
 [ 0.13944012  5.99826796 -0.04938925]
 [-0.01815016  5.99826796 -0.04938925]]
Generation:  12
Fitness of the best solution:  -2.7464849656461308
[[ 0.45974256  5.99826796 -0.02516016]
 [ 0.45974256  6.49813162 -0.34748966]
 [ 0.908519    6.49813162 -0.04938925]
 [ 0.95366121  6.49813162 -0.02516016]
 [-0.3275678   5.99826796 -0.04938925]
 [ 1.26578214  5.99826796 -0.04938925]
 [ 0.90290729  6.49813162 -0.04938925]
 [-0.46895146  5.99826796 -0.04938925]
 [ 0.45974256  6.75256979 -0.04938925]
 [ 0.45974256  5.41271941 -0.04938925]
 [ 0.45974256  6.3830186  -0.02516016]
 [ 0.48663027  5.99826796 -0.04938925]
 [ 0.45974256  7.31481637 -0.04938925]
 [ 0.45974256  5.00840034 -0.04938925]
 [ 0.45974256  7.24660329 -0.04938925]
 [ 0.17244776  5.99826796 -0.02516016]
 [-0.28509787  5.99826796 -0.04938925]
 [ 0.0521946   5.99826796 -0.04938925]
 [ 0.45974256  5.86926425 -0.04938925]
 [ 0.45974256  5.99826796  0.5758997 ]
 [ 0.45974256  5.99826796  0.28327187]
 [ 0.45974256  6.88440832 -0.04938925]
 [ 0.45974256  7.23702275 -0.04938925]
 [-0.05965518  5.99826796 -0.02516016]
 [ 0.17721875  5.99826796 -0.04938925]]
Generation:  13
Fitness of the best solution:  -2.6587306394280947
[[ 0.45974256  7.31481637 -0.04938925]
 [ 0.45974256  7.60578188 -0.04938925]
 [ 0.45974256  7.96973212 -0.04938925]
 [ 0.45974256  6.52869652 -0.04938925]
 [ 0.45974256  7.24660329 -0.49864645]
 [ 0.45974256  6.29516481 -0.04938925]
 [ 0.45974256  7.06557802 -0.04938925]
 [ 0.45974256  7.31481637 -0.42421482]
 [ 1.1016333   7.31481637 -0.04938925]
 [ 0.45974256  7.31481637 -0.44222181]
 [ 1.07397754  7.24660329 -0.04938925]
 [ 0.45974256  7.86844688 -0.04938925]
 [ 0.45974256  7.24660329 -0.3310492 ]
 [ 0.76180432  7.24660329 -0.04938925]
 [ 0.45974256  7.31481637  0.19074069]
 [ 0.45974256  7.31481637  0.68693959]
 [ 0.45974256  6.53187382 -0.04938925]
 [ 0.45974256  8.30009664 -0.04938925]
 [ 0.45974256  7.08950915 -0.04938925]
 [ 0.45974256  7.24660329 -0.27378718]
 [ 0.45974256  7.24660329 -0.35886281]
 [ 0.45974256  7.31481637 -0.03673029]
 [ 0.45974256  6.58621599 -0.04938925]
 [ 1.28178919  7.31481637 -0.04938925]
 [-0.08516571  7.24660329 -0.04938925]]
Generation:  14
Fitness of the best solution:  -2.551843289822769
[[ 0.45974256  8.30009664 -0.04938925]
 [ 0.45974256  7.96973212 -0.8422991 ]
 [ 0.45974256  8.30009664 -0.9605493 ]
 [ 0.45974256  8.88789863 -0.04938925]
 [ 1.06160952  7.96973212 -0.04938925]
 [ 0.45974256  7.6850684  -0.04938925]
 [ 0.45974256  7.9026418  -0.04938925]
 [ 0.23841856  8.30009664 -0.04938925]
 [ 0.45974256  8.30009664  0.37952627]
 [ 0.8769243   8.30009664 -0.04938925]
 [ 0.72121649  7.96973212 -0.04938925]
 [ 0.45974256  7.96973212 -0.01250528]
 [ 1.1386868   7.96973212 -0.04938925]
 [ 0.45974256  8.32742656 -0.04938925]
 [ 0.59789399  7.96973212 -0.04938925]
 [ 1.31746787  8.30009664 -0.04938925]
 [ 0.45974256  8.30009664  0.8330329 ]
 [ 0.45974256  8.2528124  -0.04938925]
 [ 0.69194241  8.30009664 -0.04938925]
 [-0.40071905  8.30009664 -0.04938925]
 [ 0.45974256  7.96973212 -0.24502853]
 [ 0.45974256  8.30009664  0.68009945]
 [ 0.45974256  7.96973212 -0.01847781]
 [ 0.45974256  7.85875202 -0.04938925]
 [ 0.45974256  7.14849384 -0.04938925]]
Generation:  15
Fitness of the best solution:  -2.5097580044541274
[[ 0.45974256  7.96973212 -0.01250528]
 [ 1.28839151  7.96973212 -0.01250528]
 [ 0.45974256  7.96973212 -1.01477088]
 [ 0.45974256  7.83040499 -0.01847781]
 [ 0.45974256  7.96973212 -0.13021026]
 [ 0.45974256  7.82200825 -0.01847781]
 [ 0.45974256  7.81917867 -0.01847781]
 [ 0.45974256  7.96973212 -0.77569708]
 [ 0.45974256  8.83768759 -0.01847781]
 [ 0.45974256  7.96973212 -0.50244872]
 [-0.15473705  7.96973212 -0.01250528]
 [ 0.45974256  7.96973212  0.9678468 ]
 [ 0.45974256  7.96973212 -0.34817737]
 [ 0.45974256  8.20486567 -0.01250528]
 [ 0.45974256  7.96973212  0.27160225]
 [ 1.37954444  7.96973212 -0.01250528]
 [ 0.09869606  7.96973212 -0.01847781]
 [ 1.24670287  7.96973212 -0.01847781]
 [ 0.45974256  7.96973212  0.31023382]
 [ 0.45974256  7.96973212  0.808691  ]
 [ 0.45974256  7.8754468  -0.01250528]
 [ 1.05312791  7.96973212 -0.01250528]
 [-0.42198038  7.96973212 -0.01250528]
 [ 0.45974256  7.74194439 -0.01847781]
 [ 0.45974256  7.96973212 -0.25234181]]
Generation:  16
Fitness of the best solution:  -2.460262151896883
[[ 0.45974256  8.83768759 -0.01847781]
 [ 0.45974256  9.15965236 -0.01847781]
 [ 0.99095213  8.20486567 -0.01250528]
 [ 0.45974256  8.83768759  0.92195238]
 [ 0.45974256  8.87016759 -0.01847781]
 [ 0.45974256  8.83768759  0.29997332]
 [ 0.45974256  8.83768759 -0.13749508]
 [ 0.45974256  9.44842186 -0.01250528]
 [ 1.26191016  8.20486567 -0.01847781]
 [ 0.36613196  8.20486567 -0.01847781]
 [ 0.45974256  7.31410572 -0.01250528]
 [-0.02714443  8.20486567 -0.01847781]
 [ 0.45974256  8.20486567  0.06079727]
 [ 0.45974256  7.92433314 -0.01847781]
 [ 0.52376367  8.20486567 -0.01847781]
 [ 0.69147512  8.20486567 -0.01847781]
 [ 0.45974256  8.83768759  0.20696447]
 [ 0.45974256  8.83768759  0.32443861]
 [ 0.93683759  8.20486567 -0.01847781]
 [-0.16556827  8.83768759 -0.01250528]
 [ 0.45974256  8.20486567 -0.9984315 ]
 [ 0.45974256  9.42944069 -0.01250528]
 [ 0.45974256  8.4030622  -0.01250528]
 [-0.34067977  8.20486567 -0.01847781]
 [ 0.45974256  8.83768759 -0.72303529]]
Generation:  17
Fitness of the best solution:  -2.4184209574317634
[[ 0.45974256  9.44842186 -0.01250528]
 [ 0.58219685  9.44842186 -0.01250528]
 [ 1.26507368  9.44842186 -0.01250528]
 [ 1.21334369  9.42944069 -0.01250528]
 [ 0.23129211  9.42944069 -0.01250528]
 [ 0.45974256  9.42944069  0.48999523]
 [ 0.45974256  9.42944069 -0.62573231]
 [ 0.45974256  8.84329593 -0.01250528]
 [ 0.45974256  8.85238127 -0.01250528]
 [ 0.45974256  9.42944069 -0.17915474]
 [ 1.18437385  9.42944069 -0.01250528]
 [ 0.45974256  9.44842186 -0.03123977]
 [ 0.45974256  9.44842186 -0.42361886]
 [ 0.45974256  9.47271773 -0.01250528]
 [ 0.45974256  9.74163912 -0.01250528]
 [ 0.45974256  9.42944069  0.88307677]
 [-0.44390999  9.44842186 -0.01250528]
 [ 0.45974256  8.97118791 -0.01250528]
 [ 0.64650372  9.42944069 -0.01250528]
 [ 0.41000414  9.44842186 -0.01250528]
 [ 0.45974256  8.759658   -0.01250528]
 [ 0.58661648  9.44842186 -0.01250528]
 [ 0.45974256  8.92292862 -0.01250528]
 [ 0.45974256  9.44842186  0.07660333]
 [ 0.48688113  9.42944069 -0.01250528]]
Generation:  18
Fitness of the best solution:  -2.3809494330259984
[[ 0.45974256  9.44842186  0.07660333]
 [ 0.45974256 10.29779021  0.07660333]
 [ 1.30989206  9.44842186 -0.01250528]
 [ 0.45974256  9.44842186  0.28520128]
 [ 0.45974256 10.47021656  0.07660333]
 [-0.41727464  9.44842186  0.07660333]
 [ 0.45974256  8.88433165  0.07660333]
 [-0.47214598  9.74163912  0.07660333]
 [ 0.45974256  9.74163912 -0.17511722]
 [ 0.45974256  9.43346662  0.07660333]
 [ 0.45974256  9.93159975 -0.01250528]
 [ 0.45974256  9.74163912 -0.52316031]
 [ 0.45974256  9.74163912 -0.89463884]
 [ 0.45974256 10.32282232  0.07660333]
 [ 0.45974256  9.74163912 -0.73812699]
 [ 0.45974256  9.44842186  0.33679168]
 [ 0.45974256  9.74163912  0.2277844 ]
 [ 0.80819721  9.74163912  0.07660333]
 [-0.27763408  9.44842186 -0.01250528]
 [ 0.93724171  9.74163912  0.07660333]
 [ 0.45974256  9.48215426 -0.01250528]
 [ 1.29661807  9.44842186 -0.01250528]
 [ 0.45974256  9.2312239   0.07660333]
 [ 0.45974256  9.74163912 -0.36649098]
 [ 0.45974256  9.74163912 -0.19389689]]
Generation:  19
Fitness of the best solution:  -2.357768131749973
[[ 0.45974256 10.47021656  0.07660333]
 [ 0.84599593 10.47021656  0.07660333]
 [ 0.45974256 10.32282232  0.14687841]
 [-0.40754199 10.47021656  0.07660333]
 [ 0.45974256 10.47021656 -0.09959657]
 [ 0.45974256 10.18640616  0.07660333]
 [ 0.59020792 10.32282232  0.07660333]
 [ 0.45974256 11.09268785  0.07660333]
 [ 0.45974256 10.01790046  0.07660333]
 [ 0.45974256 11.25001804  0.07660333]
 [ 0.45974256 10.61413785  0.07660333]
 [ 0.28399153 10.32282232  0.07660333]
 [ 0.45974256 10.32282232 -0.1036952 ]
 [ 0.45974256 11.01733984  0.07660333]
 [ 0.45974256  9.87450824  0.07660333]
 [ 1.09757722 10.47021656  0.07660333]
 [-0.128119   10.32282232  0.07660333]
 [ 0.45974256 10.47021656  0.64552622]
 [ 0.45974256  9.6168308   0.07660333]
 [ 0.45974256 10.47021656  0.47189336]
 [ 1.25355619 10.32282232  0.07660333]
 [ 0.45974256 10.47021656  0.70193223]
 [ 0.45974256  9.6343202   0.07660333]
 [ 0.45974256 11.01665644  0.07660333]
 [ 0.45974256  9.83300589  0.07660333]]
Generation:  20
Fitness of the best solution:  -2.342505514836156
[[ 0.45974256 11.25001804  0.07660333]
 [ 0.45974256 11.24935929  0.07660333]
 [ 0.45974256 10.38254431  0.07660333]
 [ 1.44956437 11.25001804  0.07660333]
 [ 0.45974256 11.25001804  0.54173634]
 [ 0.23143206 11.25001804  0.07660333]
 [ 0.69018082 11.25001804  0.07660333]
 [ 0.45974256 11.25001804  1.01885862]
 [-0.09203402 11.25001804  0.07660333]
 [ 0.58428298 11.09268785  0.07660333]
 [ 0.45974256 11.09268785  0.91194832]
 [ 0.45974256 11.75413646  0.07660333]
 [ 0.45974256 11.19992508  0.07660333]
 [ 0.45974256 11.28528114  0.07660333]
 [ 0.45974256 11.09268785  0.42982806]
 [ 0.45974256 11.28832371  0.07660333]
 [ 0.45974256 11.09268785  1.05922599]
 [ 0.05999122 11.25001804  0.07660333]
 [ 0.45974256 11.82566718  0.07660333]
 [ 0.79992443 11.25001804  0.07660333]
 [ 0.45974256 11.51739715  0.07660333]
 [ 0.45974256 11.25001804 -0.02499996]
 [-0.05831912 11.25001804  0.07660333]
 [ 0.45974256 11.25001804  0.06611987]
 [ 0.45974256 11.09268785  0.57509985]]
Generation:  21
Fitness of the best solution:  -2.318432943484823
[[ 4.59742561e-01  1.12500180e+01  6.61198674e-02]
 [ 4.59742561e-01  1.12500180e+01  5.52201650e-01]
 [ 4.59742561e-01  1.18256672e+01 -3.49735278e-01]
 [ 4.59742561e-01  1.12587248e+01  6.61198674e-02]
 [ 4.59742561e-01  1.17487207e+01  7.66033343e-02]
 [ 4.59742561e-01  1.12500180e+01  1.74668356e-03]
 [ 4.59742561e-01  1.18256672e+01 -2.34717470e-01]
 [ 4.59742561e-01  1.11009118e+01  6.61198674e-02]
 [ 4.59742561e-01  1.12176487e+01  7.66033343e-02]
 [ 1.20517934e+00  1.12500180e+01  7.66033343e-02]
 [ 4.59742561e-01  1.21779568e+01  7.66033343e-02]
 [ 4.59742561e-01  1.12500180e+01  1.51142865e-01]
 [ 4.59742561e-01  1.18256672e+01  8.90958443e-01]
 [ 4.59742561e-01  1.18256672e+01  1.35134145e-01]
 [ 2.23130473e-01  1.12500180e+01  7.66033343e-02]
 [ 4.59742561e-01  1.18256672e+01 -5.73906578e-02]
 [ 4.59742561e-01  1.18256672e+01  4.40411468e-01]
 [ 1.31318234e+00  1.12500180e+01  7.66033343e-02]
 [ 4.59742561e-01  1.18256672e+01 -4.91926658e-01]
 [ 4.59742561e-01  1.16399784e+01  6.61198674e-02]
 [ 4.59742561e-01  1.18256672e+01 -5.56009386e-01]
 [ 4.59742561e-01  1.12500180e+01 -4.09832849e-02]
 [ 4.59742561e-01  1.16209642e+01  7.66033343e-02]
 [-2.02327422e-01  1.12500180e+01  7.66033343e-02]
 [ 4.59742561e-01  1.22012924e+01  6.61198674e-02]]
Generation:  22
Fitness of the best solution:  -2.2987113726642288
[[ 0.45974256 12.2012924   0.06611987]
 [ 0.45974256 12.2012924   0.33993568]
 [ 0.45974256 11.64500713  0.06611987]
 [ 0.33761644 12.2012924   0.06611987]
 [ 0.45974256 12.33652253  0.06611987]
 [ 0.95990149 12.2012924   0.06611987]
 [ 0.45974256 12.2012924   0.98412407]
 [ 0.45974256 11.94324816  0.06611987]
 [ 1.20768297 11.63997841  0.06611987]
 [ 1.30614925 12.2012924   0.06611987]
 [ 0.45974256 12.2012924   0.82247897]
 [ 0.45974256 12.2012924  -0.93146267]
 [ 0.45974256 11.63997841 -0.71033609]
 [-0.49803033 12.2012924   0.06611987]
 [ 0.45974256 11.05143166  0.06611987]
 [ 0.45974256 11.22708405  0.06611987]
 [-0.29993319 11.63997841  0.06611987]
 [ 0.16553613 12.2012924   0.06611987]
 [ 0.45974256 11.95428054  0.06611987]
 [ 0.45974256 11.00129661  0.06611987]
 [ 0.45974256 11.63997841 -0.16139831]
 [ 0.45974256 12.40392385  0.06611987]
 [ 0.45974256 12.2866801   0.06611987]
 [ 0.45974256 13.1352118   0.06611987]
 [ 0.45974256 12.2012924   0.82335243]]
Generation:  23
Fitness of the best solution:  -2.2987113726642288
[[ 0.45974256 13.1352118   0.06611987]
 [ 0.45974256 13.09282851  0.06611987]
 [ 0.45974256 12.40392385  0.89895248]
 [ 0.45974256 12.40392385 -0.665421  ]
 [ 1.16925534 13.1352118   0.06611987]
 [ 0.64812234 13.1352118   0.06611987]
 [-0.17803796 13.1352118   0.06611987]
 [-0.22442738 13.1352118   0.06611987]
 [ 0.06748406 13.1352118   0.06611987]
 [ 0.45974256 13.1352118  -0.68870272]
 [ 0.78839231 12.40392385  0.06611987]
 [ 0.57528298 13.1352118   0.06611987]
 [ 0.45974256 11.60946909  0.06611987]
 [ 0.45974256 13.1352118  -0.90734793]
 [-0.22188771 12.40392385  0.06611987]
 [ 0.45974256 12.94833665  0.06611987]
 [ 0.45974256 13.01861293  0.06611987]
 [ 0.28196251 13.1352118   0.06611987]
 [ 1.09609875 12.40392385  0.06611987]
 [ 0.45974256 13.1352118   0.85189956]
 [ 0.45974256 12.39987495  0.06611987]
 [ 1.10959929 13.1352118   0.06611987]
 [ 0.30957514 13.1352118   0.06611987]
 [ 0.45974256 12.40392385  0.32056635]
 [ 0.45974256 12.40392385  0.83075896]]
Generation:  24
Fitness of the best solution:  -2.281373061032567
[[ 0.45974256 13.1352118   0.06611987]
 [ 0.45974256 13.1352118   0.2148662 ]
 [ 0.45974256 13.09282851  0.61009247]
 [-0.52793451 13.1352118   0.06611987]
 [ 0.45974256 13.0844488   0.06611987]
 [ 0.45974256 13.1352118  -0.61816809]
 [ 0.45974256 13.1352118  -0.6619583 ]
 [ 1.31407813 13.1352118   0.06611987]
 [-0.16446902 13.09282851  0.06611987]
 [ 0.33325831 13.1352118   0.06611987]
 [ 0.45974256 13.09282851  0.23538609]
 [ 0.45974256 13.40980956  0.06611987]
 [ 0.45974256 13.15334308  0.06611987]
 [ 0.45974256 13.1352118  -0.29862855]
 [ 0.45974256 13.09282851  0.03269467]
 [ 0.45974256 12.87150756  0.06611987]
 [ 1.13880973 13.09282851  0.06611987]
 [ 1.29020487 13.09282851  0.06611987]
 [ 0.74037342 13.09282851  0.06611987]
 [ 0.56176017 13.1352118   0.06611987]
 [ 1.20092382 13.1352118   0.06611987]
 [ 1.40402986 13.09282851  0.06611987]
 [-0.24635411 13.1352118   0.06611987]
 [ 0.41127282 13.1352118   0.06611987]
 [ 1.41552652 13.09282851  0.06611987]]
Generation:  25
Fitness of the best solution:  -2.2609405856106397
[[ 0.45974256 13.09282851  0.03269467]
 [ 0.45974256 13.40980956  0.84258861]
 [ 0.45974256 13.09282851 -0.38135677]
 [ 0.04581094 13.09282851  0.03269467]
 [ 0.45974256 13.49668124  0.06611987]
 [ 1.17486604 13.09282851  0.03269467]
 [ 0.45974256 14.16833707  0.03269467]
 [ 0.45974256 12.95412942  0.03269467]
 [ 0.45974256 13.0705798   0.03269467]
 [ 0.07736881 13.09282851  0.03269467]
 [ 0.96746452 13.09282851  0.06611987]
 [ 0.45974256 13.32318965  0.06611987]
 [ 0.45974256 13.40980956  0.30818646]
 [ 0.45974256 13.09282851 -0.52280986]
 [ 0.45974256 13.58555521  0.03269467]
 [ 0.45974256 13.40980956 -0.31268052]
 [-0.15056551 13.40980956  0.03269467]
 [ 0.21587553 13.09282851  0.03269467]
 [ 0.45974256 13.03513749  0.06611987]
 [ 0.45974256 12.4558085   0.03269467]
 [ 0.64976983 13.40980956  0.06611987]
 [ 0.45974256 13.09282851 -0.63254983]
 [ 0.45974256 13.40980956  0.71035941]
 [ 0.45974256 13.09282851 -0.08713503]
 [ 0.45974256 12.78476808  0.06611987]]

#Gráficos

from google.colab import drive
drive.mount('/content/drive')
---------------------------------------------------------------------------
MessageError                              Traceback (most recent call last)
<ipython-input-21-d5df0069828e> in <module>
      1 from google.colab import drive
----> 2 drive.mount('/content/drive')

/usr/local/lib/python3.8/dist-packages/google/colab/drive.py in mount(mountpoint, force_remount, timeout_ms, readonly)
     99 def mount(mountpoint, force_remount=False, timeout_ms=120000, readonly=False):
    100   """Mount your Google Drive at the specified mountpoint path."""
--> 101   return _mount(
    102       mountpoint,
    103       force_remount=force_remount,

/usr/local/lib/python3.8/dist-packages/google/colab/drive.py in _mount(mountpoint, force_remount, timeout_ms, ephemeral, readonly)
    122       'TBE_EPHEM_CREDS_ADDR'] if ephemeral else _os.environ['TBE_CREDS_ADDR']
    123   if ephemeral:
--> 124     _message.blocking_request(
    125         'request_auth', request={'authType': 'dfs_ephemeral'}, timeout_sec=None)
    126 

/usr/local/lib/python3.8/dist-packages/google/colab/_message.py in blocking_request(request_type, request, timeout_sec, parent)
    169   request_id = send_request(
    170       request_type, request, parent=parent, expect_reply=True)
--> 171   return read_reply_from_input(request_id, timeout_sec)

/usr/local/lib/python3.8/dist-packages/google/colab/_message.py in read_reply_from_input(message_id, timeout_sec)
    100         reply.get('colab_msg_id') == message_id):
    101       if 'error' in reply:
--> 102         raise MessageError(reply['error'])
    103       return reply.get('data', None)
    104 

MessageError: Error: credential propagation was unsuccessful
filename = '/content/drive/MyDrive/Colab Notebooks/dados ag/teste_dados_ag/genetic'
ga_instance.save(filename=filename)
loaded_ga_instance = pygad.load(filename=filename)
ga_instance.plot_fitness()
ga_instance.pop_fitness=True
solution, solution_fitness, solution_idx = ga_instance.best_solution(ga_instance.last_generation_fitness)
print(f"Melhor Solução: {np.round(solution,2)}")
print(f"Fitness: {np.round(-solution_fitness,2)}")
print("Index of the best solution : {solution_idx}".format(solution_idx=solution_idx))
if ga_instance.best_solution_generation != -1:
    print("Best fitness value reached after {best_solution_generation} generations.".format(
        best_solution_generation=ga_instance.best_solution_generation))

Melhor Solução: [ 0.46 14.17  0.03]
Fitness: 2.26
Index of the best solution : 6
Best fitness value reached after 25 generations.
J,t,y,u,K = PID(solution)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10,5))
ax1.plot(t, y, label='y(t)')
ax2.plot(t, u, label='u_out(t)')
ax1.grid()
ax2.grid()
ax1.legend()
ax2.legend()  
ax1.set_xlabel('t')
ax2.set_xlabel('t')
ax1.set_title('Step response')
ax2.set_title('Control signal')
/usr/local/lib/python3.8/dist-packages/control/timeresp.py:935: UserWarning: return_x specified for a transfer function system. Internal conversion to state space used; results may meaningless.
  warnings.warn(

from mpl_toolkits.mplot3d import axes3d
plt.figure()
k = ga_instance.initial_population
h = ga_instance.population
ax = plt.axes(projection ="3d")

colors = ('y', 'g', 'c', 'b', 'k')
c_list = []
for c in colors:
    c_list.extend([c] * 5)

# Creating plot
sct = ax.scatter(k[:,0], k[:,1], k[:,2], c=c_list)
scct = ax.scatter(h[:,0], h[:,1], h[:,2], c=c_list)

ax.set_xlabel('P', fontweight ='bold')
ax.set_ylabel('I', fontweight ='bold')
ax.set_zlabel('D', fontweight ='bold')

plt.show()

# Rotate the axes and update
# for angle in range(0, 360*4 + 1):
#     # Normalize the angle to the range [-180, 180] for display
#     angle_norm = (angle + 180) % 360 - 180

#     # Cycle through a full rotation of elevation, then azimuth, roll, and all
#     elev = azim = roll = 0
#     if angle <= 360:
#         elev = angle_norm
#     elif angle <= 360*2:
#         azim = angle_norm
#     elif angle <= 360*3:
#         roll = angle_norm
#     else:
#         elev = azim = roll = angle_norm

#     # Update the axis view and title
#     ax.view_init(elev, azim)
#     plt.title("Primeira e última Geração")

#     plt.draw()

#Controlador baseado em otimização Controle ótimo: operação de um sistema dinâmico a um custo mínimo. O problema LQR: Dinâmica do sistema descrita por um conjunto de equações diferênciais lineares com o Custo descrito por uma função quadrática. >A solução é fornecida pelo regulador linear-quadrático (LQR), um controlador realimentado.

O LQR é uma parte importante da solução para o problema LQG (linear-quadrártico gaussiano).

Sistemas MIMO: difícil especificar um overshoot. Os pólos são, do ponto de vista da engenharia, o resultado da raiz do determinante de uma matriz, e possuem uma relação obscura com a resposta temporal. (Usar LQR para sistemas MIMO).

Muitos problemas de controle podem ser expressos como a minimização do “desvio” das variáveis controladas, y, de seus set-points, r.

O significado do desvio pode ser formalizado como, por exemplo, \((y-r)^2\). Desta forma, elevando ao quadrado, penaliza-se tanto os desvios poditivos quanto os negativos.

\(e^2 = (y-r)^2\)

Inicialmente \(r = 0\) será assumido, pois denota qualquer ponto de equilíbrio constante em um modelo linearizado.

\(e^2 = y^2 = (Cx)^2\)

A função custo é uma função que queremos minimizar, o objetivo é encontrar um compensador que minimize a função J, ou seja, obtenha o menor valor possível.

Para o caso do erro \(e^2\), queremos minimizar a função:

\(J_c = \int_{0}^{\infty} e^2 \,dt\)

\(J_d=\sum_{k=0}^{\infty} e(k)^2 \,dt\)

Quando falamos em matrizes a função custo assume a forma:

Função custo contínua: \(J_c = \int_{0}^{\infty} (Cx)^2 \,dt\)

\(J_c = \int_{0}^{\infty} ((Cx)^T(Cx)) \,dt = \int_{0}^{\infty} (x^TC^TCx)) \,dt\)$

\(J_c = \int_{0}^{\infty} (x^TQx) \,dt\)

Função custo discreta: \(J_d = \sum_{k=0}^{\infty} (C_kx(k))^2\)

\(J_d = \sum_{k=0}^{\infty} ((C_kx(k))^T(C_kx(k)))^2 = \sum_{k=0}^{\infty} (x(k)^TC_k^TC_kx(k))\)$

\(J_d = \sum_{k=0}^{\infty} (x(k)^TQ_kx(k))\)

Função custo incluíndo agora os desvios na entrada:

\(J_c = \int_{0}^{\infty} (x^TQx+u^TRu) \,dt\)

Os sinais mudam com o tempo, o objetivo do controle deve ser orientado para minimizar o “desvio acumulado” tanto dos estados x quanto da entrada u.

#Modelo linear: \(x=Ax+Bu\), com \((A, \ B)\) estabilizavel.

##Funcão de custo quadratico:

\(\int_{0}^{\infty} [x^T(t)Qx(t) +u^T(t)Ru(t)] \,dt\)

\(Q=QT≥0,R=RT>0\), com $ (A,  Q^{1/2}) $ observavel.

from scipy.signal import tf2ss
import scipy.signal as signal
A, B, C, D = tf2ss(num, den)

# A = matrix([[0,0,1], [0,-2,-1], [0,0,0]])
# B = matrix([[0,0,1]]).reshape(3,1)
# C = matrix([[0,0,1]])
# D = 0*eye(1)

system = ct.ss(A,B,C,D)
sys = ct.tf(system)

print('system: ',sys)
print('A:\n', A)
print('B:\n', B)
print('C:\n', C)
print('D:\n', D)
system:  
2.665e-15 s^2 + 1.443e-15 s + 1
-------------------------------
         s^3 + s^2 + s

A:
 [[-1. -1. -0.]
 [ 1.  0.  0.]
 [ 0.  1.  0.]]
B:
 [[1.]
 [0.]
 [0.]]
C:
 [[0. 0. 1.]]
D:
 [[0.]]
# Entrada ao degrau
def Step(sys):
    plt.figure()
    yout, T = ct.step_response(sys)
    plt.plot(yout, T)

Step(system)

def LQR(indiv):

  global A, B, C, D, dt

  T0 = 0
  N = 600
  t = np.arange(T0,N*dt, dt)

  Q = matrix([[indiv[0],0,0],
       [0,indiv[1],0],
       [0,0,indiv[2]]])
  
  R = indiv[3]

  K, S, E = ct.lqr(A, B, Q, R)

  Ac = (A-B@K)

  sys = ct.ss(Ac,B@K@matrix([[1],[0],[0]]),C,D)

  y,t,xout = lsim(sys,dt,t)

  J = dt*sum(np.dot(np.dot(y.T,y),Q)+np.dot(np.dot(Ac.T,Ac),R))

  # plt.plot(t,y)
  # plt.grid()
  # plt.show()

  return J, K, y, t, xout
def f_func(solution, solution_idx):
    J, K, y, t, xout = LQR(solution)
    return -J
def callback_gen(ga_instance):
  print("Generation: ", ga_instance.generations_completed)
  print("Fitness of the best solution: ", ga_instance.best_solution()[1])
  print(ga_instance.population)
last_fitness = 0
def on_generation(ga_instance):
    global last_fitness
    print("Generation = {generation}".format(generation=ga_instance.generations_completed))
    print("Fitness    = {fitness}".format(fitness=ga_instance.best_solution(pop_fitness=ga_instance.last_generation_fitness)[1]))
    print("Change     = {change}".format(change=ga_instance.best_solution(pop_fitness=ga_instance.last_generation_fitness)[1] - last_fitness))
    last_fitness = ga_instance.best_solution(pop_fitness=ga_instance.last_generation_fitness)[1]
#  Configuração dos Parâmetros do AG
fitness_function = f_func
# Definição da população e dos indivíduos
num_generations = 10
num_parents_mating = 2
num_pop = 5
num_genes = 4

init_range_low = 0.1
init_range_high = 10
# Elitismo
parent_selection_type = "sss"
keep_parents = 1
# Cruzamento
crossover_type = "two_points"
# Mutação
mutation_type = "random"
mutation_percent_genes = 0.01
mutation_num_genes = 1
ga_instance = pygad.GA(num_generations=num_generations,
                       num_parents_mating=num_parents_mating,
                       fitness_func=fitness_function,
                       sol_per_pop=num_pop,
                       num_genes=num_genes,
                       init_range_low=init_range_low,
                       init_range_high=init_range_high,
                       parent_selection_type=parent_selection_type,
                       keep_parents=keep_parents,
                       crossover_type=crossover_type,
                       mutation_type=mutation_type,
                       mutation_percent_genes=mutation_percent_genes,
                       save_best_solutions=True,
                       save_solutions=True,
                       mutation_num_genes=mutation_num_genes,
                       allow_duplicate_genes=False,
                       stop_criteria="saturate_10",
                       on_generation=on_generation,
                       callback_generation=callback_gen)
ga_instance.run()
Generation:  1
Fitness of the best solution:  -13.315317431015036
[[7.91717774 1.65970891 7.52509274 0.23326649]
 [8.32234891 5.10504725 2.61945967 0.23326649]
 [7.91717774 1.65970891 2.61945967 9.72650587]
 [8.35795827 1.65970891 2.61945967 9.726719  ]
 [1.96303611 5.10504725 7.52509274 0.23326649]]
Generation:  2
Fitness of the best solution:  -10.674806333045062
[[1.96303611 5.10504725 7.52509274 0.23326649]
 [1.96303611 1.30520908 7.52509274 0.23326649]
 [8.06018692 5.10504725 7.52509274 0.23326649]
 [1.96303611 2.21987709 7.52509274 0.23326649]
 [7.91717774 5.10504725 7.99991901 0.23326649]]
---------------------------------------------------------------------------
LinAlgError                               Traceback (most recent call last)
<ipython-input-51-e87ae048484f> in <module>
----> 1 ga_instance.run()

/usr/local/lib/python3.8/dist-packages/pygad/pygad.py in run(self)
   1407             self.previous_generation_fitness = self.last_generation_fitness.copy()
   1408             # Measuring the fitness of each chromosome in the population. Save the fitness in the last_generation_fitness attribute.
-> 1409             self.last_generation_fitness = self.cal_pop_fitness()
   1410 
   1411             best_solution, best_solution_fitness, best_match_idx = self.best_solution(pop_fitness=self.last_generation_fitness)

/usr/local/lib/python3.8/dist-packages/pygad/pygad.py in cal_pop_fitness(self)
   1233                     fitness = self.previous_generation_fitness[parent_idx]
   1234                 else:
-> 1235                     fitness = self.fitness_func(sol, sol_idx)
   1236                     if type(fitness) in GA.supported_int_float_types:
   1237                         pass

<ipython-input-43-081b4e95514f> in f_func(solution, solution_idx)
      1 def f_func(solution, solution_idx):
----> 2     J, K, y, t, xout = LQR(solution)
      3     return -J

<ipython-input-42-7dc11440f013> in LQR(indiv)
     13   R = indiv[3]
     14 
---> 15   K, S, E = ct.lqr(A, B, Q, R)
     16 
     17   Ac = (A-B@K)

/usr/local/lib/python3.8/dist-packages/control/statefbk.py in lqr(*args, **kwargs)
    451 
    452     # Compute the result (dimension and symmetry checking done in care())
--> 453     X, L, G = care(A, B, Q, R, N, None, method=method, S_s="N")
    454     return G, X, L
    455 

/usr/local/lib/python3.8/dist-packages/control/mateqn.py in care(A, B, Q, R, S, E, stabilizing, method, A_s, B_s, Q_s, R_s, S_s, E_s)
    433                     "method='scipy' not valid when stabilizing is not True")
    434 
--> 435             X = sp.linalg.solve_continuous_are(A, B, Q, R)
    436             K = np.linalg.solve(R, B.T @ X)
    437             E, _ = np.linalg.eig(A - B @ K)

/usr/local/lib/python3.8/dist-packages/scipy/linalg/_solvers.py in solve_continuous_are(a, b, q, r, e, s, balanced)
    521 
    522     if norm(u_sym, 1) > sym_threshold:
--> 523         raise LinAlgError('The associated Hamiltonian pencil has eigenvalues '
    524                           'too close to the imaginary axis')
    525 

LinAlgError: The associated Hamiltonian pencil has eigenvalues too close to the imaginary axis
ga_instance.plot_fitness()
ga_instance.pop_fitness=True
solution, solution_fitness, solution_idx = ga_instance.best_solution()
print(f"Melhor Solução: {np.round(solution,2)}")
print(f"Fitness: {np.round(-solution_fitness,2)}")
print("Index of the best solution : {solution_idx}".format(solution_idx=solution_idx))
if ga_instance.best_solution_generation != -1:
    print("Best fitness value reached after {best_solution_generation} generations.".format(
        best_solution_generation=ga_instance.best_solution_generation))

Melhor Solução: [ 1.85 -0.63  5.86 -0.21]
Fitness: -14.68
Index of the best solution : 0
Best fitness value reached after 9 generations.
J, K, y, t, xout = LQR(solution)
fig, (ax1, ax2) = plt.subplots(1, 2, figsize=(10,5))
ax1.plot(t, y, label='y(t)')
ax2.plot(t, u, label='xout(t)')
ax1.grid()
ax2.grid()
ax1.legend()
ax2.legend()  
ax1.set_xlabel('t')
ax2.set_xlabel('t')
ax1.set_title('Step response')
ax2.set_title('Control signal')