Ejemplo n.º 1
0
def Plot(id, function, detail, algorithm, samples):
    name = str(id) + ': ' + type(
        function).__name__ + " (" + algorithm.__name__ + ")"
    print(name, ":\t\t\tComputing...")
    fig = plt.figure(name)
    fig.suptitle(name)
    ax = fig.gca(projection='3d')
    fig.canvas.draw_idle()

    # Plot the surface.
    full = FullFunction(function, detail)
    surf = ax.plot_surface(full.X,
                           full.Y,
                           full.Z,
                           cmap=cm.coolwarm,
                           linewidth=0,
                           antialiased=True,
                           alpha=0.5)
    plt.pause(0.001)

    # Make data.
    #search = []
    #FuncAnimation(fig, UpdatePlot, fargs=[algorithm, function, ax, search], interval=100, repeat=False, frames=np.linspace(0, samples))
    search = [algorithm(function, fig, ax) for x in range(0, samples)]

    smin = GraphData(sys.maxsize, sys.maxsize, sys.maxsize)
    smax = GraphData(-sys.maxsize, -sys.maxsize, -sys.maxsize)
    points = []
    for result in search:
        points.append(result)
        if smin.Z >= result.Z:
            smin = result
        if smax.Z < result.Z:
            smax = result

    for point in points:
        color = "#000000"
        alpha = 0.6
        if point.Z == smax.Z:
            color = "#0000FF"
            alpha = 1.0
        if point.Z == smin.Z:
            color = "#FF0000"
            alpha = 1.0
        ax.scatter(point.X, point.Y, point.Z, c=color, alpha=alpha)

    print(name, ":\t\t\tMinimum [", smin.X, ", ", smin.Y, "] = ", smin.Z)
    print(name, ":\t\t\tMaximum [", smax.X, ", ", smax.Y, "] = ", smax.Z)

    # Customize the z axis.
    # ax.set_zlim(data.Min, data.Max)
    ax.zaxis.set_major_locator(LinearLocator(10))
    ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

    # Add a color bar which maps values to colors.
    fig.colorbar(surf, shrink=0.5, aspect=5)
Ejemplo n.º 2
0
Archivo: Utils.py Proyecto: MGSE97/BIA
def FullFunction(function, detail):
    step = (function.Range[1] - function.Range[0]) / detail
    x = np.arange(function.Range[0], function.Range[1], step)
    y = np.arange(function.Range[0], function.Range[1], step)
    x, y = np.meshgrid(x, y)
    z = function.Value([x, y])

    return GraphData(x, y, z)
Ejemplo n.º 3
0
def fix_mutation(function, y):
    r = []
    diff = function.Range[1] - function.Range[0]
    for x in y.Data:
        if function.Range[0] <= x <= function.Range[1]:
            r.append(x)
        else:
            r.append(x % diff)
    r.pop()
    r.append(function.Value(r))
    return GraphData(r)
Ejemplo n.º 4
0
Archivo: PSO.py Proyecto: MGSE97/BIA
def plot_pso(function, detail=1000):
    # Setup
    random.seed()
    plt.ion()
    args = []
    step = (function.Range[1] - function.Range[0]) / 100
    for d in range(0, D-1):
        args.append(np.random.uniform(function.Range[0], function.Range[1], NP))

    population = []
    for i in range(0, NP):
        p = []
        for d in range(0, D-1):
            p.append(args[d][i])
        p.append(function.Value(p))
        m = Member(p)
        m.Velocity = GraphData(np.random.uniform(-1, 1, NP))
        population.append(m)

    fig = plt.figure("PSO")
    fig.suptitle("PSO")
    ax = fig.gca(projection='3d')
    fig.canvas.draw_idle()

    # Plot the surface.
    full = FullFunction(function, detail)
    surf = ax.plot_surface(full.X, full.Y, full.Z, cmap=cm.coolwarm, linewidth=0, antialiased=True, alpha=0.5)
    plt.pause(0.001)

    points = []
    i = 0
    best = population[0].Best
    while True:
        i += 1
        print(i, best)

        # Draw population
        for point in points:
            point.remove()
        points.clear()

        # Move population
        for m in population:
            best = move_member(m, best, step, function)
            points.append(ax.quiver(m.X, m.Y, m.Z, m.Velocity.X, m.Velocity.Y, m.Velocity.Z, length=step, arrow_length_ratio=0.01, alpha=0.3))

        px, py, pz = [[p.X for p in population], [p.Y for p in population], [p.Z for p in population]]
        points.append(ax.plot(px, py, pz, 'ro', color='black', alpha=0.5)[0])
        points.append(ax.plot([best.X], [best.Y], [best.Z], 'ro', color='red')[0])
        plt.pause(0.01)

    plt.show()
Ejemplo n.º 5
0
Archivo: SOMA.py Proyecto: MGSE97/BIA
def move_others(function, population, leader, step):
    newPopulation = []
    newPopulation.append(leader)

    leaderIndex = population.index(leader)
    for i, member in enumerate(population):
        if i == leaderIndex:
            continue

        pertubatingVector = []
        for d in range(0, D - 1):
            r = random.random()
            pertubatingVector.append(0 if r <= PRT else 1)

        pertubatingVector = Vector(pertubatingVector)

        newMember = member
        t = step
        while t < PATH_LENGTH:

            # D-1
            vector = member + (member - leader) * t * pertubatingVector
            data = []
            for v in vector.Data:
                if v < function.Range[0] or v > function.Range[1]:
                    data.append(np.random.uniform(function.Range[0], function.Range[1], 1)[0])
                else:
                    data.append(v)
            data.append(function.Value(data))
            vector = GraphData(data)

            if vector.last() <= newMember.last():
                newMember = vector

            t += step

        newPopulation.append(newMember)

    return newPopulation
Ejemplo n.º 6
0
Archivo: PSO.py Proyecto: MGSE97/BIA
def move_member(m, best, step, function):
    # calc new speed
    m.Velocity = m.Velocity + C1 * vector_rand() * (m.Best - m) + C2 * vector_rand() * (best - m)
    m.Velocity = GraphData(m.Velocity.Data)
    # move member
    newPosition = m + step * m.Velocity
    newPos = []
    for i in range(0, D-1):
        if function.Range[0] > newPosition.Data[i]:
            newPos.append(function.Range[0])
        elif function.Range[1] < newPosition.Data[i]:
            newPos.append(function.Range[1])
        else:
            newPos.append(newPosition.Data[i])

    # evaluate
    newPos.append(function.Value(newPos))
    newPos = GraphData(newPos)
    if (newPos.last() <= m.Best.last()):
        m.Best = newPos
        m.set(newPos.Data)
        if (m.Best.last() <= best.last()):
            best = m.Best
    return best
Ejemplo n.º 7
0
def cross(function, x, y):
    # Get random index
    r = random.randrange(0, D - 1)
    # Generate indexes
    rs = [np.random.random() for d in range(0, D - 1)]
    # Set values
    z = []
    for i, ri in enumerate(rs):
        if ri <= CR or i == r:
            z.append(y.Data[i])
        else:
            z.append(x.Data[i])

    z.append(function.Value(z))
    return GraphData(z)
Ejemplo n.º 8
0
Archivo: SOMA.py Proyecto: MGSE97/BIA
def plot_soma(function, detail=1000):
    # Setup
    random.seed()
    plt.ion()
    args = []
    for d in range(0, D-1):
        args.append(np.random.uniform(function.Range[0], function.Range[1], NP))

    population = []
    for i in range(0, NP):
        p = []
        for d in range(0, D-1):
            p.append(args[d][i])
        p.append(function.Value(p))
        population.append(GraphData(p))

    fig = plt.figure("SOMA")
    fig.suptitle("SOMA")
    ax = fig.gca(projection='3d')
    fig.canvas.draw_idle()

    # Plot the surface.
    full = FullFunction(function, detail)
    surf = ax.plot_surface(full.X, full.Y, full.Z, cmap=cm.coolwarm, linewidth=0, antialiased=True, alpha=0.5)
    plt.pause(0.001)

    points = []
    i = 0
    while True:
        i += 1
        print(i, len(population))

        # Draw population
        for point in points:
            point.remove()
        points.clear()

        px, py, pz = [[p.X for p in population], [p.Y for p in population], [p.Z for p in population]]
        points.append(ax.plot(px, py, pz, 'ro', color='black')[0])
        plt.pause(0.01)

        leader = find_leader(population)
        leader = move_leader(function, leader)

        population = move_others(function, population, leader, STEP)

    plt.show()
Ejemplo n.º 9
0
def plot_diff_evolution(function, detail=1000):
    random.seed()
    plt.ion()
    args = []
    for d in range(0, D - 1):
        args.append(np.random.uniform(function.Range[0], function.Range[1],
                                      NP))

    population = []
    for i in range(0, NP):
        p = []
        for d in range(0, D - 1):
            p.append(args[d][i])
        p.append(function.Value(p))
        population.append(GraphData(p))

    fig = plt.figure("DE")
    fig.suptitle("DE")
    ax = fig.gca(projection='3d')
    fig.canvas.draw_idle()

    # Plot the surface.
    full = FullFunction(function, detail)
    surf = ax.plot_surface(full.X,
                           full.Y,
                           full.Z,
                           cmap=cm.coolwarm,
                           linewidth=0,
                           antialiased=True,
                           alpha=0.5)
    plt.pause(0.001)

    points = []
    new_population = []
    i = 0
    while True:
        i += 1
        print(i)  #, len(population))
        plt.pause(0.01)
        # Compute
        for x in population:
            # Get 3 from population
            a, b, c = random.sample(population, k=3)
            while x == a or x == b or x == c:
                [a, b, c] = random.sample(population, k=3)
            # Compute temp vector
            y = mutate(a, b, c)
            y = fix_mutation(function, y)
            # Cross selected
            y = cross(function, x, y)
            # Select new population
            if evaluate(x, y):
                new_population.append(y)
            else:
                new_population.append(x)

        # Draw population

        for point in points:
            point.remove()
        points.clear()

        px, py, pz = [[p.X for p in population], [p.Y for p in population],
                      [p.Z for p in population]]
        points.append(ax.plot(px, py, pz, 'ro', color='black')[0])

        population.clear()
        population.extend(new_population)
        new_population.clear()
    plt.show()
Ejemplo n.º 10
0
def mutate(a, b, c):
    return GraphData((a + F * (b - c)).Data)
Ejemplo n.º 11
0
import matplotlib.pyplot as plt
import numpy as np
import random
from matplotlib import cm
from mpl_toolkits.mplot3d import Axes3D

Axes3D = Axes3D  # pycharm auto import
from Models import GraphData
from Utils import FullFunction

F = GraphData(0.5, 0.5, 0.5)
CR = 0.2
NP = 20
D = 3


# best
def mutate(a, b, c):
    return GraphData((a + F * (b - c)).Data)


# binomial
def cross(function, x, y):
    # Get random index
    r = random.randrange(0, D - 1)
    # Generate indexes
    rs = [np.random.random() for d in range(0, D - 1)]
    # Set values
    z = []
    for i, ri in enumerate(rs):
        if ri <= CR or i == r:
Ejemplo n.º 12
0
Archivo: TLBO.py Proyecto: MGSE97/BIA
def plot_tlbo(function, detail=1000):
    # Setup
    random.seed()
    plt.ion()

    # Create population
    args = []
    step = (function.Range[1] - function.Range[0]) / 100
    for d in range(0, D - 1):
        args.append(np.random.uniform(function.Range[0], function.Range[1],
                                      NP))

    population = []
    for i in range(0, NP):
        p = []
        for d in range(0, D - 1):
            p.append(args[d][i])
        p.append(function.Value(p))
        f = GraphData(p)
        population.append(f)

    # Set plots
    fig = plt.figure("TLBO")
    fig.suptitle("TLBO")
    ax = fig.gca(projection='3d')
    fig.canvas.draw_idle()

    # Plot the surface.
    full = FullFunction(function, detail)
    surf = ax.plot_surface(full.X,
                           full.Y,
                           full.Z,
                           cmap=cm.coolwarm,
                           linewidth=0,
                           antialiased=True,
                           alpha=0.5)
    plt.pause(0.001)

    points = []
    g = 0
    teacher = population[0].copy()
    while True:
        g += 1
        print(g, teacher)

        # Draw population
        for point in points:
            point.remove()
        points.clear()

        px, py, pz = [[p.X for p in population], [p.Y for p in population],
                      [p.Z for p in population]]
        points.append(ax.plot(px, py, pz, 'ro', color='black', alpha=0.5)[0])
        points.append(
            ax.plot([teacher.X], [teacher.Y], [teacher.Z], 'ro',
                    color='red')[0])
        plt.pause(0.01)

        # Find best teacher
        x_mean = Vector([0, 0, 0])
        for m in population:
            if m.last() < teacher.last():
                teacher = m.copy()
            x_mean += m

        x_mean = 1.0 / len(population) * x_mean
        Tf = np.round(np.random.uniform(1, 2))

        # Teach
        newPopulation = []
        for m in population:
            if m is teacher:
                continue

            pos = function.FixRange(
                (m + vector_rand() * (teacher - Tf * x_mean)).Data)
            pos.append(function.Value(pos))
            pos = GraphData(pos)
            if pos.last() < m.last():
                newPopulation.append(pos)
            else:
                newPopulation.append(m)

        # Learn
        for m in newPopulation:
            l = random.sample(newPopulation, k=1)[0]
            while m is l:
                l = random.sample(newPopulation, k=1)[0]

            pos = function.FixRange(
                (m + vector_rand() * ((m - l) if m.last() <= l.last() else
                                      (l - m))).Data)
            pos.append(function.Value(pos))
            if pos[len(pos) - 1] < m.last():
                m.set(pos)

        population = newPopulation

    plt.show()