GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing github.com — code/code/evodevo.py at master · rmlopes/code Expand file tree/ Copy pathevodevo.pyMore file actions 430 lines (373 loc) · 17.9 KB / Copy pathevodevo.pyFile metadata and controls430 lines (373 loc) · 17.9 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 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 import ConfigParser import os import logging import logging.config from operator import itemgetter, attrgetter import random from functools import partial from time import clock, sleep import copy from bitstring import BitStream from utils import * from utils.bitstrutils import * from utils.filestuff import DefaultRunLog from numpy import cumsum from abc import * import cPickle as pickle import sys from math import ceil log = logging.getLogger(__name__) class Agent: __metaclass__ = ABCMeta parentfit = 1e4 @abstractproperty def genotype(self): pass @abstractproperty def phenotype(self): pass @abstractproperty def fitness(self): pass def __init__(self, parent = None): self.parent = parent #for backward compatibility if parent: self.parentfit = parent.fitness #name, (total, neutral) self.oplog = dict() #total, neutral self.mutlog = [0.0,0.0] def traceops(self, opname, neutral): log.debug("tracing use of operator %s (neutral=%s)"%(opname, neutral)) try: self.oplog[opname][0] += 1 if neutral: self.oplog[opname][1] += 1 except KeyError: self.oplog[opname] = [1, int(neutral)] def tracemuts(self, total, neutral): log.debug("tracing %i total mutations (%i neutral)"%(total, neutral)) self.mutlog[0] += total self.mutlog[1] += neutral def pickled(self): return self def print_(self): return str(self) #Problem base for this module class Problem: __metaclass__ = ABCMeta @abstractproperty def funs(self): pass @abstractproperty def terms(self): pass @abstractproperty def labels(self): pass @abstractproperty def arity(self): pass def __init__(self, evaluate): self.eval_ = evaluate self.arity = dict(zip(self.funs,[0]*len(self.funs))) def register_adf(adfcount,adf,problem): name = 'adf%i'%(adfcount,) mainmod = __import__('__main__') setattr(mainmod, name , adf) problem.terms = problem.terms +[name] log.debug('Registered %s', name) def greedyselection(pop, size): pop.sort(key=lambda a: a.fitness) del pop[size:] def _sumranks(agent): agent.ranksum = sum(agent.ranks)#/float(len(agent.ranks)) def moo0selection(pop, size): pop.sort(key=lambda a: a.phenotype.parcialfit[0]) #min_y1 = min([a.phenotype.parcialfit[0] for a in pop]) #min_y2 = min([a.phenotype.parcialfit[1] for a in pop]) for i in range(len(pop)): pop[i].ranks = [i] #for a in pop: # a.ranks = (abs(min_y1-a.phenotype.parcialfit[0]), # abs(min_y2-a.phenotype.parcialfit[1])) pop.sort(key=lambda a: a.phenotype.parcialfit[1]) for i in range(len(pop)): pop[i].ranks.append(i) map(_sumranks, pop) pop.sort(key=lambda a: a.ranksum) del pop[size:] log.info(pop[0].phenotype.parcialfit) ### Main class of the library class EvoDevoWorkbench: def __init__(self, loadedconfig, problem, logmanager = DefaultRunLog, **kwargs): config, self.arnconfig = loadedconfig logging.config.fileConfig(config.get('default','logconf'), disable_existing_loggers=False) log.info('Setting up evolutionary workbench...') self.runlog = logmanager(log) self.trace = config.getboolean('default', 'ancestortrace') mainmod = __import__('__main__') self.problem = problem self.popsize = config.getint('default','popsize') self.parentpsize = config.getint('default','parentpopsize') self.maxiters = config.getint('default','numiters') self.popratio = self.popsize / self.parentpsize opnames = config.get('default','operators') oprates = config.get('default','oprates') self.opargs = config.get('default','opargs').split(',') self.ops_, self.oprates = _initialize_ops(opnames,oprates) log.debug(self.ops_) log.debug(self.oprates) self.xover_ = config.get('default','xover') if self.xover_: log.info('Initializing crossover operator...') self.xover_ = getattr(mainmod,self.xover_) self.xrate = config.getfloat('default','xrate') aclass = config.get('default','agent').split('.') mod = aclass[0] + "." + aclass[1] self.device = __import__(mod,fromlist=aclass[2]) self.problem.eval_ = partial(self.problem.eval_, device = self.device) log.info("CoDe module: %s"%(mod,)) log.info("Agent class: %s"%(aclass[2],)) self.agentclass = partial(getattr(self.device, aclass[2]), config = self.arnconfig, problem = problem ) self.mutrate = config.getfloat('default','mutrate') self.orig_mutrate = self.mutrate self.mutate_ = partial(bitflipmutation, mutrate = self.mutrate) self.improves = 0 self.tempevals = 0 self.adfcount = 0 self.localsearch = config.get('default','localsearch') if self.localsearch: log.info('Initializing local search holder') self.localsearch = getattr(mainmod, self.localsearch)(5,codefun) self.basicadf = config.get('default','adf') if self.basicadf: log.info('Initializing multiplex adf skeleton') self.basicadf = getattr(mainmod, self.basicadf) self.interactive = config.get('default','gui') if self.interactive: log.info('Interactive mode enabled. Initialiazing GUI.') _guiclass = getattr(mainmod, self.interactive) self.gui = _guiclass(self.popsize,problem=self.problem) self.numevals = None self.population = None self.parents = None self.best = None self.itercount = None self._selectionop = config.get('default','selectionop') if self._selectionop: log.info('Initializing selection operator...') self._selectionop = getattr(mainmod, self._selectionop) else: self._selectionop = greedyselection def step(self): log.info('Evaluating population...') if not self.interactive: for i in self.population: i.fitness = self.problem.eval_(i.phenotype, itercount=self.itercount) else: self.gui.pop = self.population self.gui.unpause() self.parents = [] for i in self.gui.selected: self.population[i].fitness -= 1 if not self.gui._running: self.population[self.gui.selected[0]].fitness = 0 self.numevals += len(self.population) #self.adaptmutrate() if self.localsearch: log.info('Performing local search...') for i in self.population: self.numevals += self.localsearch.search( i,self.problem) log.info('Selecting parents...') #there is a bug in functools.partial in Py2.6 #cannot use deepcopy with partial'ed objects self.parents.extend(self.population[:]) self._selectionop(self.parents, self.parentpsize) log.info('Generating next population...') offsprings = [] if self.xover_: #tournament TODO: parameterise this for i in range(self.popsize//2): if random.random() < self.xrate: players1 = random.sample(self.parents,3) players1.sort(key=lambda a: a.fitness) players2 = random.sample(self.parents,3) players2.sort(key=lambda a: a.fitness) breeders = [players1[0], players2[0]] offsprings.extend(self._reproduct_agents(*breeders)) log.debug('Created %i offsprings by xover.' %(len(offsprings),)) if not self.interactive: if len(offsprings) < self.popsize: pr = self.popratio if self.popratio > 1 else self.popsize mutants = [self._create_mutant(p) for p in self.parents for i in range( \ int(ceil((self.popsize - len(offsprings))/float(pr))))] self.population = (offsprings + mutants[:(self.popsize-len(offsprings))]) else: if len(offsprings) < self.popsize: mutants = [self._create_mutant(p) for p in self.parents for i in range(self.popratio-1)] else: mutants = [] self.population = (self.parents + offsprings + mutants[:self.popsize - (self.parentpsize+len(offsprings))]) def _reproduct_agents(self, p1, p2): return [self.agentclass(gcode = self.mutate_(o), parent = p1, problem = self.problem) for o in self.xover_(p1, p2)] def _create_mutant(self, parent): op_ = _selectop(self.ops_,self.oprates) gcodeclass = parent.genotype.code.__class__ opcode = op_(gcodeclass(parent.genotype.code), *self.opargs, arnet = parent.genotype) if self.trace and op_.__name__ != 'idle': agent = self.agentclass(gcode = opcode, parent = parent, problem = self.problem) if agent.phenotype == parent.phenotype: neutraloperator = True else: neutraloperator = False mut_opcode = self.mutate_(gcodeclass(opcode)) mutagent = self.agentclass(gcode = mut_opcode, parent = parent, problem = self.problem) if self.trace: if op_.__name__=='idle': agent = parent assert len(mut_opcode) == len(opcode), \ "non-matching genomes; using %s\n%s\n%s" % (op_.__name__,opcode,mut_opcode) mutmask = mut_opcode ^ opcode idxmut = filter(lambda l: l[0] == '1', zip(mutmask, range(len(mutmask)))) totalmut = len(idxmut) if agent.phenotype == mutagent.phenotype: neutralmut = totalmut else: #TODO: remove hard coded constants #To use only with ARN genomes neutralmut = 0 try: promlist = agent.genotype.promlist + \ agent.genotype.effectorproms except: promlist = agent.genotype.promlist for i in idxmut: n = True for p in promlist: if p - 88 <= i[1] < p + 168: n = False break if n: neutralmut += 1 if op_.__name__ != '_idle': mutagent.traceops(op_.__name__, neutraloperator) mutagent.tracemuts(totalmut, neutralmut) return mutagent def run(self, terminate = (lambda x,y: x <= 1e-3 or y <= 0)): mainmod = __import__('__main__') start = clock() self.numevals = 0 self.itercount = 0 log.info('Initializing population...') self.population = [self.agentclass() for p in range(self.popsize)] self.best = self.agentclass() self.parents = [] if self.adfcount: self.problem.terms = filter(lambda t: t[:3]!='adf', self.problem.terms) self.adfcount = 0 while(not(terminate(self.best.fitness, self.maxiters-self.itercount))): log.info('--- Iteration #%i ---', self.itercount) self.step() log.debug(self.parents[0].fitness) log.debug(self.best.fitness) if self.parents[0].fitness < self.best.fitness: self.best = self.parents[0] if self.basicadf: register_adf(self.adfcount, partial(self.basicadf, circuit = self.best.phenotype), self.problem) self.adfcount += 1 #NOTE: cannot pickle on python 2.6 #(issue 1398) #self.circuitlog.critical( # pickle.dumps(self.best,2)) self.runlog.dumpcircuit( self.best ) log.info(self.best.genotype.snapshot()) log.info(self.best.phenotype.printgraph()) log.info('Best:\n%s', self.best.print_()) self.runlog.step(self.parents, numevals=self.numevals) self.itercount += 1 print str(clock()-start)+ "sec." if self.trace: self.runlog.dumpancestortree(self.best) return self.best def adaptmutrate(self): improves = [p.fitness <= p.parentfit for p in self.population] self.improves += improves.count(True) self.tempevals += self.popsize if self.itercount % 10 == 0: if self.improves >= .2*self.tempevals: self.mutrate /= 0.85 else: self.mutrate *= 0.85 self.improves = 0 self.tempevals = 0 if self.mutrate < .5*self.orig_mutrate: self.mutrate *= 2 log.debug('mutrate = %f' % (self.mutrate,)) self.mutate_ = partial(bitflipmutation, mutrate = self.mutrate) def _idle(gcode, *args, **kwargs): return gcode def _initialize_ops(opnames, rates): if not opnames or not rates: ops, ratescum = [_idle],[1.0] else: opnames = opnames.split(',') mainmod = __import__('__main__') try: ops = [getattr(mainmod, x) for x in opnames] except: log.warning('Operator not found, loading aborted...') log.debug('__main__ module contents: %s', dir(mainmod)) return [_idle],[1.0] ops.append(_idle) rates = rates.split(',') rates = [float(r) for r in rates] rates.append(1.0 - sum(rates)) ratescum = cumsum(rates) return ops,ratescum def _selectop(ops, rates): rnd = random.random() for i in range(len(rates)): if rnd < rates[i]: return ops[i] ########################################################################### ### Test ### ########################################################################### if __name__ == '__main__': from rencode import * p = Problem(defaultnodemap,regressionfun, lambda x,y: 1) edw = EvoDevoWorkbench('configfiles/test.cfg',p,buildcircuit,Agent) edw.run() |
| You are visitor 01402520 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |