-
Notifications
You must be signed in to change notification settings - Fork 0
/
cmfunc.py
72 lines (67 loc) · 2.34 KB
/
cmfunc.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
#! /usr/bin/env python
# -*- coding: utf-8 -*-
#
# Copyright © 2019 zhaoyi <yizhaome@gmail.com>
#
# Distributed under terms of the Apache V2.0 license.
import numpy as np
import random
# SBX cross
def sbx_cross(population, cross_prob=0.5, expo=1):
for _ in range(len(population)):
if np.random.random() < cross_prob:
# compute para
mu = np.random.random()
if mu < 0.5:
para = np.power(2*mu, 1/(expo+1))
else:
para = np.power(1/(2*(1-mu)), 1/(expo+1))
# cross
ind1, ind2 = random.sample(range(len(population)), 2)
p1, p2 = population[ind1], population[ind2]
temp1 = p1
p1 = 0.5*((1+para)*p1 + (1-para)*p2)
p2 = 0.5*((1-para)*temp1 + (1+para)*p2)
population[ind1] = p1
population[ind2] = p2
return population
# ramdom cross
def random_cross(population, cross_prob=0.5, expo=1):
for _ in range(len(population)):
if np.random.random() < cross_prob:
# compute para
mu = np.random.random()
if mu < 0.5:
para = 1 - mu
else:
para = mu
# cross
ind1, ind2 = random.sample(range(len(population)), 2)
p1, p2 = population[ind1], population[ind2]
temp1 = p1
p1 = para*p1 + (1-para)*p2
p2 = (1-para)*temp1 + para*p2
population[ind1] = p1
population[ind2] = p2
return population
# polynomial mutation
def poly_mutate(population, mute_prob=0.1, expo=1):
for _ in range(len(population)):
if np.random.random() < mute_prob:
# compute para
mu = np.random.random()
if mu < 0.5:
addition = np.power(2*mu, 1/(expo+1)) - 1
else:
addition = np.power(1-(2*(1-mu)), 1/(expo+1))
# cross
ind = random.sample(range(len(population)), 1)
population[ind] += addition
return population
# polynomial mutation
def random_mutate(population, mute_prob=0.2, _min=-1000, _max=1000):
for _ in range(len(population)):
if np.random.random() < mute_prob:
ind = random.sample(range(len(population)), 1)
population[ind] = _min + np.random.random() * (_max-_min)
return population