Exemplo n.º 1
0
Arquivo: pso.py Projeto: LukeKort/Opp
def pso(n_particles,n_variables,n_iterations,tolerance,a,b,pso_only_w,pso_only_c1,pso_only_c2):

    from random_matrix import radom_generator #random generator. takes x and y vector dimentions between the limits a and b
    import functions
    reload(functions)  #uptade the changes made in the function file
    from functions import objective #objetive function(s)
    from functions import constraints #constraint function(s)

    best_result_acum = np.empty((n_iterations)) #preallocation
    v = radom_generator(n_variables,n_particles,a,b) #velocity matrix
    x_aux = radom_generator(n_variables,n_particles,a,b)
    x = radom_generator(n_variables,n_particles,a,b)
    x_best = np.zeros((n_variables))

    cc = 1 #controler counter

    t_0 = time.time() #start time

    for i in range(n_iterations):  
        x_0=x.copy() #stores the last x before uptade
        for j in range(n_particles):
            v[:,j]= pso_only_w*v[:,j] + rand.random()*pso_only_c1*(x_aux[:,j]-x[:,j]) + rand.random()*pso_only_c2*(x_best - x[:,j]) #new velocity matrix
            x[:,j]=x_0[:,j]+v[:,j] #new position matrix
            for k in range(n_variables): #test with the limits (a,b)
                if x[k,j]<a[k]:
                    x[k,j]=a[k]+(b[k]-a[k])*rand.random()
                if x[k,j]>b[k]:
                    x[k,j]=a[k]+(b[k]-a[k])*rand.random()
            if (constraints(x[:,j])) is True: #teste the new x within the constraints functions
                if (objective(x[:,j])) < objective(x_aux[:,j]): #teste the new x within the objetive function
                    x_aux[:,j] = x[:,j].copy() #setting new best particle position
                    
                    if cc == 1:
                        results = np.full(n_particles,objective(x_aux[:,j])) #the 1st best value will fill the results vector
                        best_result_acum = np.full(n_iterations,objective(x_aux[:,j]))
                        cc += 1
                    else:    
                        results[j] = objective(x_aux[:,j]) #save result per particle
                    
                    best_result = min(results).copy() #find best result of all particles
                    best_result_acum[i] = best_result.copy()
                    idx = results.tolist().index(best_result) #find the best result's index inside the results vector
                    x_best = x_aux[:,idx] #find the best result's position
        
        if tolerance >= np.amax(abs(x-x_0)): #break for setting tolerance
            break

    t_end = time.time() #finish time
    t_total = t_end - t_0 #total processing time

    if cc == 1:
        best_result = x_best = 'Not found!' #if the problem can't be solved, rise the messange

    print('#Particle Swarm\nMelhor resultado:',best_result,'\nPosição:',x_best,'\nTempo de execução:',(t_total),'s\n')
    
    return({'best_result':best_result,'acumulate_result':best_result_acum,'x_best':x_best,'t_total':t_total,'max_n_iteration':i})
Exemplo n.º 2
0
def lj(n_variables, n_iterations, tolerance, a, b, lj_only_in, lj_only_c):

    from random_matrix import radom_generator  #random generator. takes x and y vector dimentions between the limits a and b
    import functions
    reload(functions)  #uptade the changes made in the function file
    from functions import objective  #objetive function(s)
    from functions import constraints  #constraint function(s)

    best_result_acum = np.empty((n_iterations))  #preallocation
    x_0 = (radom_generator(n_variables, 1, a, b))  #postion matrix
    x = r = np.ones((n_variables, 1))

    t_0 = time.time()  #start time

    for i in range(n_iterations):  #external cicle
        x_aux = x_0.copy()
        for j in range(lj_only_in):  #internal cicle
            x[:,
              0] = x_0[:,
                       0] + (2 * rand.random() - 1) * r[:, 0]  #particle update
            if (constraints(
                    x[:, 0])) is True:  #teste within the constraints functions
                if (objective(x[:, 0])) < objective(
                        x_0[:, 0]):  #teste particle update
                    x_0 = x  #setting new particle position

        best_result = objective(x_0[:, 0])  #find best result of each iteration
        best_result_acum[i] = best_result

        r[:, 0] = (1 - lj_only_c) * abs(x[:, 0] - x_aux[:, 0])

        if tolerance >= np.amax(r):  #break for setting tolerance
            x_best = x_0  #find the best result's position
            break

    x_best = x_0[:, 0]  #find the best result's position

    t_end = time.time()  #finish time
    t_total = t_end - t_0  #total processing time

    print('#Luus Jaakola\nMelhor resultado:', best_result, '\nPosição:',
          x_best, '\nTempo de execução:', (t_total), 's\n')

    return ({
        'best_result': best_result,
        'acumulate_result': best_result_acum,
        'x_best': x_best,
        't_total': t_total,
        'max_n_iteration': i
    })
Exemplo n.º 3
0
    def run_methods(self): #run the methods

        print(datetime.now().strftime("%H:%M:%S"),"\n")

        try:
            import functions
            reload(functions)  #uptade the changes made in the function file
        except:
            print('Parece que existe um problema com as funções fornecidas.\n')
            return
        from functions import constraints
        from functions import objective

        n_iterations = int(self.ui.n_iterations.text())
        n_particles = int(self.ui.n_particles.text())
        tolerance = float(self.ui.n_tolerance.text())
        a = list(map(float,(self.ui.vector_inf_limit.text().split(',')))) #limit inferior per variable (must be a list)
        b= list(map(float,(self.ui.vector_sup_limit.text().split(',')))) #limit superior per variable (must be a list)
        n_variables = np.size(a) #number of variables = number of constraints
        pso_only_w=float(self.ui.w_pso_only.text()) #w for alcateia only
        pso_only_c1=float(self.ui.c1_pso_only.text()) #c1 for alcateia only
        pso_only_c2=float(self.ui.c2_pso_only.text()) #c2 for alcateia only
        alcateia_only_ic = int(self.ui.alcateia_inner_circle.text()) #internal cicles for alcateia only
        alcateia_only_id = float(self.ui.alcatei_id.text()) #idependency for alcateia only
        lj_only_in = int(self.ui.inner_circle_lj_only.text()) #internal for alcateia only
        lj_only_c = float(self.ui.c_lj_only.text()) #contraction factor(0,1) for alcateia only

        
        if np.size(a) != np.size(b): #check for erros in a and b
            print('O limite inferior e superior tem tamanhos diferentes!\n')
            return

        if alcateia_only_id < 0 or alcateia_only_id > 1: #check for erros in jaakola innercircles
            print("No Alcateia, o parâmetro 'id' precisa estar entre 0 e 1 \n")
            return

        if lj_only_c < 0 or lj_only_c > 1: #check for erros in jaakola innercircles
            print("No Jaakola, o parâmetro 'c'precisa estar entre 0 e 1 \n")
            return

        if n_iterations < 1 or n_particles < 1 or alcateia_only_ic < 1 or lj_only_in < 1: #check for erros in jaakola innercircles
            print("O número de iterações, laços internos e partículas precisam ser no mínimo 1 \n")
            return

        try: #check for erros in objective, constraints functions
            teste_var = np.ones((n_variables,1))
            constraints(teste_var)
            objective(teste_var)
        except:
            print('Função ou limites fornecidos não aceitos\n')
            return

        n_methods=methods.count('y')
        result_table=np.zeros((n_iterations,n_methods))
        last_iteration=np.zeros(n_methods) #consider early end of method's processing by tolerance
        i=0
        methods_name=[]

        if 'y' not in methods:
            print('Nenhum método foi selecionado!\n')
            return

        if methods[0] == 'y':
            from alcateia import alcateia
            alcateia_results=alcateia(n_particles,n_variables,n_iterations,tolerance,a,b,alcateia_only_ic,alcateia_only_id) #activate de alcateia method
            result_table[:,i] = alcateia_results['acumulate_result']
            last_iteration[i] = alcateia_results['max_n_iteration']
            methods_name.append('Alcateia')
            i=i+1
        if methods[1] == 'y':
            from pso import pso
            pso_results=pso(n_particles,n_variables,n_iterations,tolerance,a,b,pso_only_w,pso_only_c1,pso_only_c2) #activate de alcateia method
            result_table[:,i] = pso_results['acumulate_result']
            last_iteration[i] = pso_results['max_n_iteration']
            methods_name.append('Particle Swarm')
            i=i+1
        if methods[2] == 'y':
            from luus_jaakola import lj
            lj_results=lj(n_variables,n_iterations,tolerance,a,b,lj_only_in, lj_only_c) #activate de alcateia method
            result_table[:,i] = lj_results['acumulate_result']
            last_iteration[i] = lj_results['max_n_iteration']
            methods_name.append('Luus Jaakola')
            i=i+1

        plotter(n_iterations,last_iteration,result_table,n_methods,methods_name)
        
        if self.ui.export_results_cvs.isChecked():
            from plotter_export_csv import export_csv
            export_csv(result_table,methods_name,n_iterations)
Exemplo n.º 4
0
def alcateia(n_particles, n_variables, n_iterations, tolerance, a, b,
             alcateia_only_ic, alcateia_only_id):

    from random_matrix import radom_generator  #random generator. takes x and y vector dimentions between the limits a and b
    import functions
    reload(functions)  #uptade the changes made in the function file
    from functions import objective  #objetive function(s)
    from functions import constraints  #constraint function(s)

    x = delta = np.zeros((n_variables, n_particles),
                         dtype=float)  #preallocation
    #results = np.ones((n_particles)) #preallocation
    best_result_acum = np.empty((n_iterations))  #preallocation

    r = radom_generator(n_variables, n_particles, a, b)
    x_0 = (radom_generator(n_variables, n_particles, a, b))  #postion matrix

    cc = 1  #controler counter

    t_0 = time.time()  #start time

    for i in range(n_iterations):  #external cicle
        for j in range(alcateia_only_ic):  #internal cicle
            for k in range(n_particles):  #calculos per particle
                delta[:, k] = (-1 + 2 * rand.random()) * r[:, k]
                x[:, k] = x_0[:, k] + delta[:, k]  #particle update
                for l in range(n_variables):  #test with the limits (a,b)
                    if x[l, k] < a[l]:
                        x[l, k] = a[l] + (b[l] - a[l]) * rand.random()
                    if x[l, k] > b[l]:
                        x[l, k] = a[l] + (b[l] - a[l]) * rand.random()
                if (constraints(x[:, k])
                    ) is True:  #teste within the constraints functions
                    if (objective(x[:, k])) < objective(
                            x_0[:, k]):  #teste particle update
                        x_0[:, k] = x[:, k]  #setting new particle position
                        if cc == 1:
                            results = np.full(n_particles, objective(x_0[:,
                                                                         k]))
                            cc += 1
                        else:
                            results[k] = objective(
                                x_0[:, k])  #save result per particle
                        best_result = min(
                            results)  #find best result of all particles
                        best_result_acum[i] = best_result
                        idx = results.tolist().index(
                            best_result
                        )  #find the best result's index inside the results vector
                        x_best = x_0[:, idx]  #find the best result's position

        if cc != 1:
            for w in range(
                    n_particles
            ):  #uptade x_0 within the best result of last external cicle
                r[:, w] = abs(x_0[:, w] - x[:, w])
                x_0[:, w] = alcateia_only_id * x_0[:, w] + (
                    1 - alcateia_only_id) * x_best

        if tolerance >= np.amax(r):  #break for setting tolerance
            #best_result_acum[:,i:n_iterations]=best_result #comple the rest of the vector with the last value
            break

    t_end = time.time()  #finish time
    t_total = t_end - t_0  #total processing time

    if cc == 1:
        best_result = x_best = 'Não encontrado!'

    print('#Alcateia\nMelhor resultado:', best_result, '\nPosição:', x_best,
          '\nTempo de execução:', (t_total), 's\n')

    return ({
        'best_result': best_result,
        'acumulate_result': best_result_acum,
        'x_best': x_best,
        't_total': t_total,
        'max_n_iteration': i
    })
Exemplo n.º 5
0
Arquivo: main.py Projeto: LukeKort/Opp
    def run_methods(self):  #run the methods

        print(datetime.now().strftime("%H:%M:%S"), "\n")

        try:
            import functions
            reload(functions)  #uptade the changes made in the function file
        except:
            print('Looks like the inputted functions has a problem.\n')
            return
        from functions import constraints
        from functions import objective

        n_iterations = int(self.ui.n_iterations.text())
        n_particles = int(self.ui.n_particles.text())
        tolerance = float(self.ui.n_tolerance.text())
        a = list(map(float, (self.ui.vector_inf_limit.text().split(',')
                             )))  #limit inferior per variable (must be a list)
        b = list(map(float, (self.ui.vector_sup_limit.text().split(',')
                             )))  #limit superior per variable (must be a list)
        n_variables = np.size(a)  #number of variables = number of constraints
        pso_only_w = float(self.ui.w_pso_only.text())  #w for alcateia only
        pso_only_c1 = float(self.ui.c1_pso_only.text())  #c1 for alcateia only
        pso_only_c2 = float(self.ui.c2_pso_only.text())  #c2 for alcateia only
        alcateia_only_ic = int(self.ui.alcateia_inner_circle.text()
                               )  #internal cicles for alcateia only
        alcateia_only_id = float(
            self.ui.alcatei_id.text())  #idependency for alcateia only
        lj_only_in = int(
            self.ui.inner_circle_lj_only.text())  #internal for alcateia only
        lj_only_c = float(self.ui.c_lj_only.text()
                          )  #contraction factor(0,1) for alcateia only

        if np.size(a) != np.size(b):  #check for erros in a and b
            print('Inferior limit and superior limit have differente sizes!\n')
            return

        if alcateia_only_id < 0 or alcateia_only_id > 1:  #check for erros in jaakola innercircles
            print("Alcateias's 'id' must be between 0 and 1 \n")
            return

        if lj_only_c < 0 or lj_only_c > 1:  #check for erros in jaakola innercircles
            print("Jaakola's 'c' must be between 0 and 1 \n")
            return

        if n_iterations < 1 or n_particles < 1 or alcateia_only_ic < 1 or lj_only_in < 1:  #check for erros in jaakola innercircles
            print(
                "Number of iterations, inner circles and particles must be greater than or equal to 1 \n"
            )
            return

        try:  #check for erros in objective, constraints functions
            teste_var = np.ones((n_variables, 1))
            constraints(teste_var)
            objective(teste_var)
        except:
            print('Function or limits not correctly inputted\n')
            return

        n_methods = methods.count('y')
        result_table = np.zeros((n_iterations, n_methods))
        last_iteration = np.zeros(
            n_methods)  #consider early end of method's processing by tolerance
        i = 0
        methods_name = []

        if 'y' not in methods:
            print('No method has been selected!\n')
            return

        if methods[0] == 'y':
            from alcateia import alcateia
            alcateia_results = alcateia(
                n_particles, n_variables, n_iterations, tolerance, a, b,
                alcateia_only_ic,
                alcateia_only_id)  #activate de alcateia method
            result_table[:, i] = alcateia_results['acumulate_result']
            last_iteration[i] = alcateia_results['max_n_iteration']
            methods_name.append('Alcateia')
            i = i + 1
        if methods[1] == 'y':
            from pso import pso
            pso_results = pso(n_particles, n_variables, n_iterations,
                              tolerance, a, b, pso_only_w, pso_only_c1,
                              pso_only_c2)  #activate de alcateia method
            result_table[:, i] = pso_results['acumulate_result']
            last_iteration[i] = pso_results['max_n_iteration']
            methods_name.append('Particle Swarm')
            i = i + 1
        if methods[2] == 'y':
            from luus_jaakola import lj
            lj_results = lj(n_variables, n_iterations, tolerance, a, b,
                            lj_only_in,
                            lj_only_c)  #activate de alcateia method
            result_table[:, i] = lj_results['acumulate_result']
            last_iteration[i] = lj_results['max_n_iteration']
            methods_name.append('Luus Jaakola')
            i = i + 1

        plotter(n_iterations, last_iteration, result_table, n_methods,
                methods_name)

        if self.ui.export_results_cvs.isChecked():
            from plotter_export_csv import export_csv
            export_csv(result_table, methods_name, n_iterations)