1 | #pip install geneticalgorithm |
2 | import numpy as np |
3 | from geneticalgorithm import geneticalgorithm as ga |
4 | # Define charateristics of variables: |
5 | varbound = np.array([[ 0 , 1 ],[ 0 , 1 ]]) |
6 | vartype = np.array([[ 'real' ],[ 'real' ]]) |
7 |
8 | # Define settings of the algorithm: |
9 | algorithm_param = { 'max_num_iteration' : 100 ,\ |
10 | 'population_size' : 60 ,\ |
11 | 'mutation_probability' : 0.1 ,\ |
12 | 'elit_ratio' : 0.01 ,\ |
13 | 'crossover_probability' : 0.5 ,\ |
14 | 'parents_portion' : 0.3 ,\ |
15 | 'crossover_type' : 'uniform' ,\ |
16 | 'max_iteration_without_improv' : None } |
17 | |
18 | # Define your optimization model: |
19 | def MyOptProb(X): |
20 | y = 0 + X[ 1 ] * ( 1.29 - 0 ) |
21 | x = np. round ( 0 + X[ 0 ] * ( 2 - 0 )) |
22 | g1 = 5 / 10 * x + 3 / 10 * y - 1 |
23 | g2 = 2 / 9 * x + 7 / 9 * y - 1 |
24 | penalty = np.amax(np.array([ 0 ,g1,g2])) |
25 | return - ( 2 * x + 5 * y) + 150 * penalty * * 2 |
26 |
27 | # Define a solution retriever: |
28 | def Results(obj, variables): |
29 | x = round ( 0 + variables[ 0 ] * ( 2 - 0 )) |
30 | y = 0 + variables[ 0 ] * ( 1.29 - 0 ) |
31 | g1 = 5 * x + 3 * y - 10 |
32 | g2 = 2 * x + 7 * y - 9 |
33 | print (g1) |
34 | print (g2) |
35 | if g1> 10e - 6 or g2> 10e - 6 : |
36 | print ( "infeasible" ) |
37 | else : |
38 | print ( "feasible" ) |
39 | print ( "x:" ,x) |
40 | print ( "y:" ,y) |
41 | print ( "obj:" , 2 * x + 5 * y) |
42 |
43 | # Model and solve the problem: |
44 | model = ga(function = MyOptProb,dimension = 2 , |
45 | variable_type_mixed = vartype,variable_boundaries = varbound, |
46 | algorithm_parameters = algorithm_param) |
47 | model.run() |
48 | # Display results: |
49 | Results(model.best_function,model.best_variable) |
50 | # The best solution found: |
51 | # [0.41141754 0.79674808] |
52 | # Objective function: |
53 | # -7.068871696566733 |
54 | # -3.40781412393091 |
55 | # -3.284899622505458 |
56 | # feasible |
57 | # x: 1 |
58 | # y: 0.5307286253563631 |
59 | # obj: 4.653643126781816 |
Recent Comments