-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcellcode.py
More file actions
213 lines (182 loc) · 7.29 KB
/
Copy pathcellcode.py
File metadata and controls
213 lines (182 loc) · 7.29 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
import ConfigParser, os
import logging
import random
import numpy as np
import copy
#import extendedarn as arn
from evodevo import Agent
from numpy import array as nparray
from functools import partial
from bitstring import *
from math import exp
import sys
from sys import stdout
from subprocess import call
from utils import *
from utils.bitstrutils import *
#testing miguel's approach implies importing arnmiguel instead'
#delegated to main import order (cellcode would be imported after the
#arn module but it doesn not work like that, must be delegated to
#config file)
#from extendedarn import *
from arnmiguel import *
log = logging.getLogger(__name__)
### Problem base to use with ReNCoDe
class CellProb:
def __init__(self, evaluate, numins=100, numouts=100):
self.eval_ = evaluate
self.ninp = numins
self.nout = numouts
self.print_ = printcell
def printcell(arn):
return arn.code.bin
class Cell(Agent):
phenotype = None
genotype = None
fitness = None
def __init__(self, config, problem, gcode = None, parent = None, **kwargs):
Agent.__init__(self, parent)
generator = bindparams(config, generatechromo)
if gcode == None:
gcode = generator()
self.genotype = ARNetwork(gcode, config, problem=problem)
#because now the phenotype is expressed at
#evaluatiuon time
self.phenotype = self.genotype
#self.phenotype = arn.ARNetwork(gcode,config)
while (self.phenotype.numeff == 0 or
#self.phenotype.numrec == 0 or
self.phenotype.numtf == 0):
gcode = generator()
self.genotype = ARNetwork(gcode, config, problem=problem)
self.phenotype = self.genotype
#initialize phenotype
inps = nparray(np.zeros(problem.ninp))
inps += 0.05
self.phenotype.nstepsim(2000, #config.getint('default','simtime'),
*inps)
#FIXME: this is not being used, 'cause there is a problem
#with the pickled ccs. Adopted the reset function below()
self.initstate = copy.deepcopy(self.phenotype.ccs)
self.fitness = 1e9
def __str__(self):
return "### Agent ###\n%s\n%s: %f" % (self.phenotype.proteins,self.phenotype.effectors,
self.fitness)
def pickled(self):
mycode = self.genotype.code.bin
try:
myout = self.phenotype.output_idx
except:
myout = 0
return (mycode,myout)
def reset(self):
self.phenotype.reset()
self.phenotype.nstepsim(self.phenotype.simtime,*[.0,.0,.0,.0])
TFACTORS = 0
STRUCTS = 1
def plotindividual(arnet, **kwargs):
displayARNresults(arnet.proteins, arnet.cchistory,
kwargs['samplerate'], temp=0,
figure=TFACTORS)
extralabels = ['R']*arnet.numrec + ['E']*arnet.numeff
struct_prots = arnet.receptors + arnet.effectors
hist = np.vstack((arnet.receptorhist,arnet.effectorhist))
displayARNresults(struct_prots, hist, kwargs['samplerate'],
temp = 1, extralabels = extralabels,
figure=STRUCTS)
def getbinaryoutput(arn, **kwargs):
index = arn.output_idx
gradientsum = []
leftlim = -(1.0 / kwargs['samplerate'])
output = (arn.effectorhist[index][-1] -
arn.effectorhist[index][leftlim-1])
return 0 if output > 0 else 1
def getoutputp0p1(arn, **kwargs):
index = 0
try:
index = kwargs['outidx']
except KeyError: pass
leftlim = -(1.0 / kwargs['samplerate'])
g1 = np.sum(np.gradient(arn.effectorhist[index][leftlim-1:]))
try:
g2 = np.sum(np.gradient(arn.effectorhist[index + 1][leftlim-1:]))
except IndexError: return 0
return 1 if g2 > g1 else 0
def evaluatewithreset(phenotype, test = False, **kwargs):
mapfun = getbinaryoutput
try:
mapfun = kwargs['mapfun']
except KeyError: pass
n = 3
ok=0
intinps = range(pow(2,n))
initstate = phenotype.ccs
for i in intinps:
inputs = BitStream(uint = i, length = n)
#print inputs.bin
normalized = nparray([float(inputs.bin[i])
for i in range(n)])
normalized *= .1
phenotype.nstepsim(kwargs['simtime'],*normalized)
out = mapfun(phenotype, **kwargs)
#print 'OUT: ', out
if out == inputs[1+inputs[0]]:
ok += 1
phenotype.reset(initstate)
#print 'SILENT: ', kwargs['silentmode']
if not kwargs['silentmode']:
plotindividual(phenotype,**kwargs)
return len(intinps) - ok
if __name__ == '__main__':
arnconfigfile = '../configfiles/arnsim.cfg'
log.setLevel(logging.DEBUG)
cfg = ConfigParser.ConfigParser()
cfg.readfp(open(arnconfigfile))
proteins=[]
nump = 0
try:
f = open(sys.argv[1], 'r')
genome = BitStream(bin=f.readline())
arnet = ARNetwork(genome, cfg)
except:
while nump < 4 or nump > 32 or numeff == 0 or not arnet.receptors:
genome = BitStream(float=random.random(), length=32)
for i in range(cfg.getint('default','initdm')):
genome = dm_event(genome,
.02)
arnet = ARNetwork(genome, cfg, numinputs = 3,numoutputs=1)
nump = len(arnet.promlist)
numeff = len(arnet.effectors)
offspring = None
themother = Cell(cfg,genome )
eval_ = bindparams(cfg, evaluatecircuit)
plot_ = bindparams(cfg, plotindividual)
pop = [(themother, eval_(themother)),
(None,0)]
while pop[0][1] > 0:
offspring = Cell(cfg, bitflipmutation(
pop[0][0].genotype.code,.01))
while not offspring.phenotype.effectors:
offspring = Cell(cfg, bitflipmutation(
pop[0][0].genotype,.01))
pop[1] = (offspring,eval_(offspring))
pop.sort(key = lambda x: x[1])
print pop
#for p in arnet.proteins: print p
f = open('genome.save','w')
f.write(pop[0][0].genotype.code.bin)
f.close
#print genome.bin
plot_(pop[0][0].genotype)
def buildcircuit(agent, problem, **kwargs):
#DELETE THIS: NO NEED TO BUILD A CIRCUIT, BEHAVIOR WILL BE THE
#DEVELOPMENT OF THE REGULATORY NETWORK INTERACTING WITH THE
#ENVIRONMENT THROUGH RECEPTORS AND EFFECTORS, DURING FITNESS EVALUATION
"""Returns the circuit to be fed into the evaluation function"""
arn = agent.genotype
if not arn.promlist:
return []
arn.nstepsim()
#map signatures to bitwise operators
#cumsum of ccs to probabilities
return circuit