Exemplo n.º 1
0
def compound_simpson(start, end, num):
    nodes1, nodes2 = get_nodes(start, end, num)
    f1 = [2 * target_function(i) for i in nodes1]
    f1[0] /= 2
    f1[-1] /= 2
    f2 = [4 * target_function(i) for i in nodes2]
    step = (end - start) / num
    return step / 6 * (sum(f1) + sum(f2))
Exemplo n.º 2
0
def gauss(start, end, num):
	if num not in (3,4):
		print("The number of nodes should be 3 or 4!")
		return None
	A, nodes = get_nodes(start, end ,num)
	nodes = nodes*(end - start)/2 + (start + end)/2
	f = [target_function(i) for i in nodes]
	integral = (end - start)/2 * np.dot(A, f)
	return integral
Exemplo n.º 3
0
def compound_trapezoid(start, end, num):
    start = float(start)
    end = float(end)
    num = int(num)
    nodes = get_nodes(start, end, num)
    f = [2 * target_function(i) for i in nodes]
    f[0] = f[0] / 2
    f[-1] = f[-1] / 2
    step = (end - start) / num
    return step / 2 * sum(f)
def differential_evolution(params):

    cr, f, b_lo, b_up, np, dim, it_s, it_t = params

    agents = [[(random() * (b_up - b_lo)) for x in range(dim)] for a in range(np)]

    results = []
    best, best_fitness = None, None

    for i in range(it_t + 1):
        for x in range(np):

            a, b, c = randint(0, np - 1), randint(0, np - 1), randint(0, np - 1)
            while a == b or b == c or c == a or a == x or b == x or c == x:
                a, b, c = randint(0, np - 1), randint(0, np - 1), randint(0, np - 1)

            R = randint(0, dim)
            y = [None] * dim

            for j in range(dim):
                ri = random()
                if ri < cr or j == R:
                    y[j] = agents[a][j] + f * (agents[b][j] - agents[c][j])
                else:
                    y[j] = agents[x][j]

            if target_function(y) < target_function(agents[x]):
                agents[x] = y

        if i % it_s == 0:

            if best is None:
                best = agents[0]
                best_fitness = target_function(agents[0])

            for a in agents:
                if target_function(a) < best_fitness:
                    best = a
                    best_fitness = target_function(a)

            results.append(best)

    return results
def pso(params):

    it_s, it_t, np, dim, b_up, b_lo, omega, phi_p, phi_g = params

    global swarm_best, swarm_best_fitness

    swarm = []
    results = []

    for p in range(np):
        swarm.append(Particle(dim, b_up, b_lo))

    for i in range(it_t + 1):

        for particle in swarm:

            for d in range(dim):

                rp, rg = uniform(0, 1), uniform(0, 1)

                particle.velocity[d] = omega * particle.velocity[d] + phi_p * rp * \
                                       (particle.best[d] - particle.position[d]) + phi_g \
                                       * rg * (swarm_best[d] - particle.position[d])

            particle.position = [
                sum(x) for x in zip(particle.position, particle.velocity)
            ]

            if target_function(particle.position) < target_function(
                    particle.best):

                particle.best = particle.position

                if target_function(particle.best) < swarm_best_fitness:

                    swarm_best = particle.best
                    swarm_best_fitness = target_function(swarm_best)

        if i % it_s == 0:
            results.append(swarm_best)

    return results
    def __init__(self, dim, b_up, b_lo):

        global swarm_best, swarm_best_fitness

        self.position = []

        for i in range(0, dim):
            self.position.append(uniform(b_lo, b_up))

        self.velocity = []

        for i in range(0, dim):
            self.velocity.append(uniform(-abs(b_up - b_lo), abs(b_up - b_lo)))

        self.best = self.position

        if swarm_best is None:
            swarm_best = self.best
            swarm_best_fitness = target_function(self.best)

        elif target_function(self.best) < swarm_best_fitness:
            self.best = swarm_best
def init():

    cpu_cores = 4
    omega = 0.729
    phi_p = 2.05
    phi_g = 2.05
    b_lower = -2
    b_upper = 2
    generation_size = 20
    dimensions = 20
    iteration_step = 5
    iteration_target = 1000
    repetitions = 10

    worker_tasks = [[
        iteration_step, iteration_target, generation_size, dimensions, b_upper,
        b_lower, omega, phi_p, phi_g
    ]] * repetitions

    # single computer
    workers = Pool(cpu_cores)
    worker_results = workers.map(pso, worker_tasks)

    # cluster computer
    # worker_results = list(futures.map(pso, worker_tasks))

    results = []
    for i in range(int(iteration_target / iteration_step) + 1):
        iteration_result = [0] * dimensions

        for thread in worker_results:
            iteration_result = [
                sum(x) for x in zip(iteration_result, thread[i])
            ]

        iteration_result = [x / repetitions for x in iteration_result]
        results.append(iteration_result)

    print(results[-1])

    fitness = [target_function(r) for r in results]
    print(fitness[-1])

    with open('results.csv', 'w', newline='\n') as csvfile:
        writer = csv.writer(csvfile,
                            delimiter=' ',
                            quotechar=';',
                            quoting=csv.QUOTE_MINIMAL)
        for line in fitness:
            writer.writerow([line])
def differential_evolution(cr, f, np, dim, it, b_lo, b_up):

    agents = [[(random() * (b_up - b_lo)) for x in range(dim)]
              for a in range(np)]

    for i in range(it):
        for x in range(np):

            a, b, c = randint(0, np - 1), randint(0,
                                                  np - 1), randint(0, np - 1)
            while a == b or b == c or c == a or a == x or b == x or c == x:
                a, b, c = randint(0,
                                  np - 1), randint(0,
                                                   np - 1), randint(0, np - 1)

            R = randint(0, dim)
            y = [None] * dim

            for j in range(dim):
                ri = random()
                if ri < cr or j == R:
                    y[j] = agents[a][j] + f * (agents[b][j] - agents[c][j])
                else:
                    y[j] = agents[x][j]

            if target_function(y) < target_function(agents[x]):
                agents[x] = y

    best = agents[0]
    best_fitness = target_function(agents[0])

    for a in agents:
        if target_function(a) < best_fitness:
            best = a
            best_fitness = target_function(a)

    return best
def init():

    cpu_cores = 4
    cr = 0.8803
    f = 0.4717
    b_lower = -2
    b_upper = 2
    generation_size = 200
    dimensions = 20
    iteration_step = 5
    iteration_target = 1000
    repetitions = 2

    worker_tasks = [[
        cr,
        f,
        b_lower,
        b_upper,
        generation_size,
        dimensions,
        iteration_step,
        iteration_target,
    ]] * repetitions

    # single computer
    workers = Pool(cpu_cores)
    worker_results = workers.map(differential_evolution, worker_tasks)

    # cluster computer
    # worker_results = list(futures.map(differential_evolution, worker_tasks))

    results = []
    for i in range(int(iteration_target / iteration_step) + 1):
        iteration_result = [0] * dimensions

        for thread in worker_results:
            iteration_result = [sum(x) for x in zip(iteration_result, thread[i])]

        iteration_result = [x / repetitions for x in iteration_result]
        results.append(iteration_result)

    print(results[-1])

    fitness = (target_function(r) for r in results)

    with open('results.csv', 'w', newline='\n') as csvfile:
        writer = csv.writer(csvfile, delimiter=' ', quotechar=';', quoting=csv.QUOTE_MINIMAL)
        for line in fitness:
            writer.writerow([line])
Exemplo n.º 10
0
def romberg(start, end, k=4, ep=1e-5, choose_k=True, max_k=10):
	if choose_k:
		t_mat = np.zeros((k,k))
	else:
		t_mat = np.zeros((max_k,max_k))
	p = t_mat.shape[0]
	nodes = [start, end]
	h = (end - start)
	t_mat[0,0] = (target_function(start) + target_function(end))*h/2
	for k in range(1,p):
		new_nodes, nodes = expand_nodes(nodes)
		t_mat[k,0] = t_mat[k-1,0]/2 + sum([target_function(i) for i in new_nodes])*h/2
		for j in range(1,k+1):
			t_mat[k,j] = (1+1/(4**j-1))*t_mat[k,j-1] - 1/(4**j-1)*t_mat[k-1,j-1]
		if choose_k and (k == 4):
			break
		if k == max_k:
			break
		if (not choose_k) and abs(t_mat[k,k]-t_mat[k-1,k-1])<ep:
			break
		h = h/2
	integral = t_mat[k,k]
	print(t_mat)
	return integral
Exemplo n.º 11
0
def pso(omega, phi, np, dim, it, b_lo, b_up):

    global swarm_best, swarm_best_fitness

    swarm = []

    for p in range(np):
        swarm.append(Particle(dim, b_up, b_lo))

    for i in range(it):

        for particle in swarm:

            for d in range(dim):

                rp, rg = uniform(0, 1), uniform(0, 1)

                particle.velocity[d] = omega * particle.velocity[d] + phi * rp * \
                                       (particle.best[d] - particle.position[d]) + phi \
                                       * rg * (swarm_best[d] - particle.position[d])

            particle.position = [
                sum(x) for x in zip(particle.position, particle.velocity)
            ]

            if target_function(particle.position) < target_function(
                    particle.best):

                particle.best = particle.position

                if target_function(particle.best) < swarm_best_fitness:

                    swarm_best = particle.best
                    swarm_best_fitness = target_function(swarm_best)

    return swarm_best
def run(params):

    cr_range, f_range, increment_step, repetitions, generation_size, \
    dimensions, iterations, b_lower, b_upper = params

    fitness = []

    cr_vals = [
        round(x, 6)
        for x in arange(cr_range[0], cr_range[1], increment_step).tolist()
    ]
    f_vals = [
        round(x, 6)
        for x in arange(f_range[0], f_range[1], increment_step).tolist()
    ]

    for f in f_vals:
        for cr in cr_vals:

            average_fitness = 0
            average_position = [0] * dimensions

            for r in range(repetitions):
                position = differential_evolution(cr, f, \
                           generation_size, dimensions, iterations, \
                           b_lower, b_upper)
                average_fitness += target_function(position)
                average_position = [
                    sum(x) for x in zip(average_position, position)
                ]

            average_fitness /= repetitions
            average_position = [x / repetitions for x in average_position]
            fitness.append([cr, f, average_fitness])

    return fitness
Exemplo n.º 13
0
def run(params):

    om_range, phi_range, increment_step, repetitions, generation_size,\
    dimensions, iterations, b_lower, b_upper = params

    fitness = []

    omega_vals = [
        round(x, 6)
        for x in arange(om_range[0], om_range[1], increment_step).tolist()
    ]
    phi_vals = [
        round(x, 6)
        for x in arange(phi_range[0], phi_range[1], increment_step).tolist()
    ]

    for phi in phi_vals:
        for omega in omega_vals:

            average_fitness = 0
            average_position = [0] * dimensions

            for r in range(repetitions):
                position = pso(omega, phi, \
                               generation_size, dimensions, iterations,\
                               b_lower, b_upper)
                average_fitness += target_function(position)
                average_position = [
                    sum(x) for x in zip(average_position, position)
                ]

            average_fitness /= repetitions
            average_position = [x / repetitions for x in average_position]
            fitness.append(average_fitness)

    return fitness