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/rencode.py at master · rmlopes/code Expand file tree/ Copy pathrencode.pyMore file actions 349 lines (304 loc) · 11.8 KB / Copy pathrencode.pyFile metadata and controls349 lines (304 loc) · 11.8 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 import logging from functools import partial from bitstring import BitStream import math import arn from evodevo import Problem, Agent from utils import * from utils.bitstrutils import * from utils.mathlogic import * log = logging.getLogger(__name__) def printdotcircuit(circuit, labels=None): circuit = circuit.circuit s = 'digraph best {\nordering = out;\n' for c in circuit: s += '%i [label="%s"];\n' % (c[0], c[1])# if not labels #else labels[c[1]]) for inp in c[2]: aux = "dir=back" if inp < 0: aux += ",style=dotted" s += '%i -> %i [%s];\n' % (c[0],abs(inp),aux) s += '}' return s #TODO: remove! behavior is identical to nnlikefun def regressionfun(mapped, node_inputs, inputs ): if not node_inputs: return eval(mapped) mainmod = __import__('__main__') if mapped in ['if_']: return getattr(mainmod, mapped)(*node_inputs) #print r # return r #else: if len(node_inputs) == 1: return getattr(mainmod, mapped)(node_inputs[0]) return reduce(lambda m,n: getattr(mainmod, mapped)(m,n), node_inputs) def nnlikefun(mapped, node_inputs, inputs): mainmod = __import__('__main__') if not node_inputs: try: return eval(mapped) except NameError: return getattr(mainmod, mapped)(inputs) if len(node_inputs) == 1: return getattr(mainmod, mapped)(node_inputs[0]) if mapped not in ReNCoDeProb.funs: return getattr(mainmod, mapped)(*node_inputs) #print mapped, node_inputs return reduce(lambda m,n: getattr(mainmod, mapped)(m,n), node_inputs) def mergefun(mapped, node_inputs, inputs): if not node_inputs: return mapped else: result = mapped + '(' result += reduce(lambda m, n: m + ',' + n, node_inputs) result += ')' return result def defaultnodemap(signature, mappingset): if len(mappingset) < 2: return mappingset[0] index = BitArray(bin=applymajority( signature, int(math.ceil(math.log(len(mappingset),2))))) intindex = index.uint if intindex >= len(mappingset): intindex -= len(mappingset) return mappingset[intindex] def evaluatecircuit(circuit, circuitmap, resultdict, *inputs,**kwargs): try: nout = kwargs['nout'] except KeyError: nout = 1 if resultdict == None: resultdict = dict() for i in range(len(circuit)): inputvalues = [resultdict[abs(v)] for v in circuit[-1-i][2]] result = circuitmap(circuit[-1-i][1], inputvalues, inputs) resultdict[circuit[-1-i][0]] = result if nout == 1: return result else: results = list() for i in range(nout): if len(circuit) > i: results.append(resultdict[circuit[i][0]]) else: results.append(0) return results def buildcircuit(agent, problem, **kwargs): """Returns the circuit to be fed into the evaluation function""" arn = agent.genotype if not arn.promlist: return [] #arn.simulate() #orderedps = sorted(arn.proteins, key = lambda x: x[-1], reverse=True) graph = arn.ebindings - arn.ibindings cleanpairs(graph) promlist = [(p[0], _getinputlist( arn.promlist, graph[:,arn.promlist.index(p[0])].tolist())) for p in arn.proteins] promlist.sort(key=lambda x: len(x[1]),reverse=True) circuit = [] pdict = dict(zip(arn.promlist,arn.proteins)) recursivebuild(circuit, problem, pdict, dict(promlist), graph, [promlist[0][0]], [], []) return circuit def recursivebuild(circuit, problem, proteindict, inputdict, graph, pqueue, secondqueue, blacklist): if not pqueue: if not secondqueue: return circuit else: secondqueue.sort(key=lambda x: len(inputdict[x]), reverse=True) pqueue.append(secondqueue.pop(0)) next = pqueue.pop(0) pnext = proteindict[next] blacklist.append(next) inputs = [] for i in inputdict[next]: if i in blacklist: if problem.feedback: inputs.append(-i) else: inputs.append(i) if inputs: fun = problem.nodemap_(pnext[4],problem.funs) ar = problem.arity[fun] if ar > 0 and len(inputs) > ar: del inputs[ar:] else: fun = problem.nodemap_(pnext[4],problem.terms) circuit.append((next, fun , inputs)) #update input dict if not using feedback if not problem.feedback: for k,v in inputdict.items(): inputdict[k] = filter( lambda i: i not in blacklist, v) secondqueue.extend([inp for inp in inputs if inp not in (pqueue+secondqueue+blacklist) and (inp >= 0)]) pqueue, secondqueue = _mergequeues(pqueue, secondqueue, inputdict) pqueue.sort(key=lambda x: len(inputdict[x]), reverse = True) return recursivebuild(circuit, problem, proteindict, inputdict, graph, pqueue,secondqueue, blacklist) def cleanpairs(matrix): s = len(matrix) for i in range(s): for j in range(i): if matrix[i][j] >= matrix[j][i]: matrix[j][i] = 0 else: matrix[i][j] = 0 def _mergequeues(q1, q2,inputdict): disjunction = q2[:] demoted = [] for e in q1: dependent = False if e in [p for pq_el in q1 for p in inputdict[pq_el] if pq_el != e]: dependent = True if e in [p for pq_el in q2 for p in inputdict[pq_el]]: dependent = True if dependent: demoted.append(e) for e in q2: dependent = False if e in [p for pq_el in q1 for p in inputdict[pq_el]]: dependent = True if e in [p for pq_el in q2 for p in inputdict[pq_el] if pq_el != e]: dependent = True if dependent: disjunction.remove(e) for e in demoted: q1.remove(e) q2.extend(demoted) for e in disjunction: q2.remove(e) q1.extend(disjunction) return q1,q2 def _getinputlist(promlist, weights): """Returns the relevant inputs given the weights.""" inputs=[] pmap = zip(promlist,weights) for p,w in pmap: if w > 0: inputs.append(p) return inputs def printcircuit(circuit): s = '' for c in circuit: s += "%i [%s]: %s\n" % (c[0], c[1], reduce(lambda m,n: "%s %s " % (m,n),c[2], "")) return s[:-2] ### Problem base to use with ReNCoDe class ReNCoDeProb(Problem): #TODO: read fun set from config file funs = [ 'add_', 'sub_', 'mul_', 'div_'] terms = [ 'inputs[0]' ] labels = {'add_':'+', 'sub_':'-', 'mul_':'*', 'div_':'/', 'inputs[0]':'x', 'inputs[1]':'1.0'} arity = {}#{'add_':0, 'sub_':0, 'mul_':0, 'div_':0} feedback = False nout=1 def __init__(self, evaluate, nodemap = defaultnodemap): Problem.__init__(self, evaluate) self.nodemap_ = nodemap #callable phenotype class P: def __init__(self, arnet, circuit, problem, skeleton = regressionfun): self.geno = arnet self.circuit = circuit self.problem = problem #memory (disabled by default) self.memory = None self.funskel = skeleton if not problem.feedback: self._str = compile(evaluatecircuit(self.circuit, mergefun, self.memory, *problem.terms), '<string>', 'eval') def getcircuit(self, *args): return self.circuit def __call__(self, *inputs): return evaluatecircuit(self.circuit,self.funskel , self.memory, *inputs, nout = self.problem.nout) def __len__(self): return len(self.circuit) def __eq__(self,other): return self.circuit == other.circuit def printgraph(self): return "GRAPH NOT AVAILABLE" ### Agent model to use with this CoDe module class ReNCoDeAgent(Agent): genotype = None phenotype = None fitness = None def __init__(self, config, problem, gcode = None, parent = None): Agent.__init__(self, parent) generator = arn.bindparams(config, self.generate) if gcode == None: gcode = generator() arnet = arn.ARNetwork(gcode,config) self.genotype = arnet self.phenotype = P(arnet,buildcircuit(self,problem), problem) self.problem = problem self.fitness = 1e6 def __str__(self): return "### Agent ###\n%s\n%s: %f" % (self.arn,self.phenotype, self.fitness) def pickled(self): return self.print_() def print_(self): return printdotcircuit(self.phenotype) class DMAgent(ReNCoDeAgent): def __init__(self, config, problem, gcode = None, parent = None): self.generate = arn.generatechromo ReNCoDeAgent.__init__(self, config, problem, gcode, parent) class RndAgent(ReNCoDeAgent): def __init__(self, config, problem, gcode = None, parent = None): self.generate = partial(arn.generatechromo_rnd, genomesize = 32 * pow(2,config.getint('default','initdm'))) ReNCoDeAgent.__init__(self, config, problem, gcode, parent) ########################################################################### ### Test ### ########################################################################### if __name__ == '__main__': import ConfigParser import random from bitstring import BitStream from bitstringutils import dm_event from arn import ARNetwork from evodevo import Problem log.setLevel(logging.DEBUG) cfg = ConfigParser.ConfigParser() cfg.readfp(open('test.cfg')) arncfg = ConfigParser.ConfigParser() arncfg.readfp(open('arnsim.cfg')) proteins=[] nump = 0 while nump < 3: genome = BitStream(float=random.random(), length=32) for i in range(5): genome = dm_event(genome, .02) arnet = ARNetwork(genome, arncfg) nump = len(arnet.promlist) for p in arnet.proteins: print p prob = Problem(defaultnodemap,regressionfun, None) circuit = buildcircuit(arnet, prob,False) _printcircuit(circuit) print printdotcircuit(circuit, prob.labels) |
| 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. |