forked from volpe-framework/volpe-container-py
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.py
More file actions
184 lines (159 loc) · 6.93 KB
/
main.py
File metadata and controls
184 lines (159 loc) · 6.93 KB
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
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
from typing import Any
from typing_extensions import override
import volpe_py as volpe
import grpc
import concurrent.futures
import threading
import array
import random
from opfunu.cec_based.cec2022 import *
from deap import base, creator, tools, algorithms
NDIM=20
func = F122022(ndim=NDIM)
LOW = func.lb[0]
HIGH = func.ub[0]
MIN_STRATEGY = 0.5
MAX_STRATEGY = 3.0
MUTATION_RATE = 0.3
CXPROB = 0.6
BASE_POPULATION_SIZE = 100
LAMBDA_SIZE = 7*BASE_POPULATION_SIZE
# Setup DEAP with ES
creator.create("FitnessMin", base.Fitness, weights=(-1.0,))
creator.create("Individual", array.array, typecode="d", fitness=creator.FitnessMin, strategy=None)
creator.create("Strategy", array.array, typecode="d")
def generateES(icls, scls, size, imin, imax, smin, smax):
ind = icls(random.uniform(imin, imax) for _ in range(size))
ind.strategy = scls(random.uniform(smin, smax) for _ in range(size))
return ind
def checkStrategy(minstrategy):
def decorator(func):
def wrapper(*args, **kargs):
children = func(*args, **kargs)
for child in children:
for i, s in enumerate(child.strategy):
if s < minstrategy:
child.strategy[i] = minstrategy
return children
return wrapper
return decorator
toolbox = base.Toolbox()
toolbox.register("individual", generateES, creator.Individual, creator.Strategy, NDIM, LOW, HIGH, MIN_STRATEGY, MAX_STRATEGY)
toolbox.register("population", tools.initRepeat, list, toolbox.individual)
def fitness(x):
if any(v > HIGH for v in x) or any(v < LOW for v in x):
return (float('inf'),)
return (float(func.evaluate(list(x))),)
toolbox.register("evaluate", fitness)
toolbox.register("mate", tools.cxESBlend, alpha=0.1)
toolbox.register("mutate", tools.mutESLogNormal, c=1.0, indpb=0.03)
toolbox.register("select", tools.selTournament, tournsize=3)
toolbox.decorate("mate", checkStrategy(MIN_STRATEGY))
toolbox.decorate("mutate", checkStrategy(MIN_STRATEGY))
def gen_ind():
ind = toolbox.individual()
ind.fitness.values = fitness(ind)
return ind
def popListTostring(popln: list):
indList : list[volpe.ResultIndividual] = []
for mem in popln:
indList.append(
volpe.ResultIndividual(representation=str(list(mem)),
fitness=mem.fitness.values[0])
)
return volpe.ResultPopulation(members=indList)
def bstringToPopln(popln: volpe.Population):
popList = []
for memb in popln.members:
# Split the genotype bytes: first NDIM doubles for individual, next NDIM for strategy
bytes_per_double = 8
total_bytes = NDIM * bytes_per_double * 2
ind_bytes = memb.genotype[:NDIM * bytes_per_double]
strategy_bytes = memb.genotype[NDIM * bytes_per_double:]
ind = creator.Individual(array.array('d', ind_bytes))
ind.strategy = creator.Strategy(array.array('d', strategy_bytes) if len(strategy_bytes) > 0 else [random.uniform(MIN_STRATEGY, MAX_STRATEGY) for _ in range(NDIM)])
ind.fitness.values = (memb.fitness,)
popList.append(ind)
return popList
def popListToBytes(popln: list):
indList : list[volpe.Individual] = []
for mem in popln:
# Combine genotype and strategy into single byte representation
combined = bytes(mem) + bytes(mem.strategy)
indList.append(volpe.Individual(genotype=combined, fitness=mem.fitness.values[0]))
return volpe.Population(members=indList, problemID="p1")
class VolpeGreeterServicer(volpe.VolpeContainerServicer):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.popln = [ gen_ind() for _ in range(BASE_POPULATION_SIZE) ]
self.poplock = threading.Lock()
@override
def SayHello(self, request: volpe.HelloRequest, context: grpc.ServicerContext):
return volpe.HelloReply(message="hello " + request.name)
@override
def InitFromSeed(self, request: volpe.Seed, context: grpc.ServicerContext):
"""Missing associated documentation comment in .proto file."""
with self.poplock:
self.popln = [ gen_ind() for _ in range(BASE_POPULATION_SIZE) ]
return volpe.Reply(success=True)
@override
def InitFromSeedPopulation(self, request: volpe.Population, context: grpc.ServicerContext):
"""Missing associated documentation comment in .proto file."""
with self.poplock:
ogLen = len(self.popln)
seedPop = bstringToPopln(request)
if self.popln == None:
self.popln = []
self.popln.extend(seedPop)
self.popln = toolbox.select(self.popln, ogLen)
return volpe.Reply(success=True)
@override
def GetBestPopulation(self, request: volpe.PopulationSize, context):
"""Missing associated documentation comment in .proto file."""
with self.poplock:
if self.popln is None:
return volpe.Population(members=[], problemID="p1")
popSorted = sorted(self.popln, key=lambda x: x.fitness.values[0])
return popListToBytes(popSorted[:request.size])
@override
def GetResults(self, request: volpe.PopulationSize, context):
with self.poplock:
if self.popln is None:
return volpe.Population(members=[], problemID="p1")
popSorted = sorted(self.popln, key=lambda x: x.fitness.values[0])
return popListTostring(popSorted[:request.size])
@override
def GetRandom(self, request: volpe.PopulationSize, context):
with self.poplock:
if self.popln is None:
return volpe.Population(members=[], problemID="p1")
popList = [self.popln[random.randint(0, len(self.popln) - 1)] for _ in range(request.size)]
return popListToBytes(popList)
@override
def AdjustPopulationSize(self, request: volpe.PopulationSize, context: grpc.ServicerContext):
"""Missing associated documentation comment in .proto file."""
pass
@override
def RunForGenerations(self, request: volpe.PopulationSize, context):
"""Missing associated documentation comment in .proto file."""
with self.poplock:
# Use DEAP's eaMuPlusLambda algorithm
self.popln, _ = algorithms.eaMuPlusLambda(
self.popln,
toolbox,
mu=len(self.popln),
lambda_=LAMBDA_SIZE,
cxpb=CXPROB,
mutpb=MUTATION_RATE,
ngen=request.size,
stats=None,
halloffame=None,
verbose=False
)
return volpe.Reply(success=True)
if __name__=='__main__':
server = grpc.server(concurrent.futures.ThreadPoolExecutor(max_workers=10))
volpe.add_VolpeContainerServicer_to_server(VolpeGreeterServicer(), server)
server.add_insecure_port("0.0.0.0:8081")
server.start()
server.wait_for_termination()