def fitness(genome, rs): fitnesses = [] random.seed(rs) for sp, rp, goal in [(random.uniform(0, 0.3), random.uniform(0, 0.3), random.uniform(0.5, 1)) for _ in range(ntrials)]: sender = ctrnn.CTRNN(genome, time_const) receiver = ctrnn.CTRNN(genome, time_const) sim = line_location.line_location(senderPos=sp, receiverPos=rp, goal=goal) # Run the given simulation for up to num_steps time steps. fitness = 0.0 while sim.t < simulation_seconds: senderOut = sender.eulerStep(sim.getState(True))[0] receiverOut = receiver.eulerStep(sim.getState(False))[0] sim.step(senderOut, receiverOut) fitness = sim.fitness() fitnesses.append(fitness) return aggregate_fitness(fitnesses) / maxfitness
def runtrial(c, task): sp, rp, goal = task sim = line_location.line_location(senderPos=sp, receiverPos=rp, goal=goal) time_const = line_location.line_location.timestep sender = ctrnn.CTRNN(c, time_const) receiver = ctrnn.CTRNN(c, time_const) sender.reset() receiver.reset() # Run the given simulation for up to num_steps time steps. while sim.t < simulation_seconds: senderstate = sim.getState(True) receiverstate = sim.getState(False) act1 = sender.eulerStep(senderstate) act2 = receiver.eulerStep(receiverstate) senderOut = act1[0] receiverOut = act2[0] sim.step(senderOut, receiverOut) # print(sim.getAsciiState()) distance = abs(sim.goal - sim.receiverPos) if sim.fitness() > 0.95: return (1, distance, sim.touches, sim.ctime) else: return (0, distance, sim.touches, sim.ctime)
def runtrial(c, goal): dist = [] endpos = [] count = 0 for sp, rp in [(sp, rp) for sp in np.arange(0, 0.3, 0.03) for rp in np.arange(0, 0.3, 0.03)]: sim = line_location.line_location(senderPos=sp, receiverPos=rp, goal=goal) time_const = line_location.line_location.timestep sender = ctrnn.CTRNN(c, time_const) receiver = ctrnn.CTRNN(c, time_const) sender.reset() receiver.reset() # Run the given simulation for up to num_steps time steps. while sim.t < simulation_seconds: senderstate = sim.getState(True) receiverstate = sim.getState(False) act1 = sender.eulerStep(senderstate) act2 = receiver.eulerStep(receiverstate) senderOut = act1[0] receiverOut = act2[0] sim.step(senderOut, receiverOut) # print(sim.getAsciiState()) dist.append(abs(sim.goal - sim.receiverPos)) endpos.append(sim.receiverPos) return (mean(dist), stdev(dist), mean(endpos), stdev(endpos), goal)
def runtrial(c, goal): step = -1 fit = [] endpos = [] count = 0 # print(goal,lb,ub) for goal2 in np.arange(-lb,-ub,step): #make me the whole range of other values if abs(goal + goal2) < 15: fit.append(np.nan) continue if goal == -goal2: fit.append(np.nan) continue g = goal/100 g2=goal2/100 sim = line_location.line_location(senderPos=0,receiverPos=0,goal=g,goal2=g2) time_const = line_location.line_location.timestep sender = ctrnn.CTRNN(c,time_const) receiver = ctrnn.CTRNN(c,time_const) sender.reset() receiver.reset() minv = 100 # Run the given simulation for up to num_steps time steps. while sim.t < simulation_seconds: senderstate = sim.getState(True) receiverstate = sim.getState(False) act1 = sender.eulerStep(senderstate) act2 = receiver.eulerStep(receiverstate) senderOut = act1[0] receiverOut = act2[0] sim.step(senderOut,receiverOut) if sim.t > 90 and sim.senderPos < minv: minv = sim.senderPos # print(sim.getAsciiState()) # rdistance = abs(sim.truegoal - sim.receiverPos) # sdistance = abs(sim.truegoal - sim.senderPos) # fit.append(1 if rdistance < 0.1 and sdistance < 0.1 else 0.5) # fit.append(1 if sim.fitness() > 0.9 else 0.5) fit.append(minv) return fit
def fitnessFunction(genotype): time = numpy.arange(0.0, duration, stepsize) net = ctrnn.CTRNN(nnsize) net.setParameters(genotype, WeightRange, BiasRange, TimeConstMin, TimeConstMax) net.initializeState(numpy.zeros(nnsize)) outputs = numpy.zeros((len(time), nnsize)) for t in time: net.step(stepsize) outputs[int(t / stepsize)] = net.Output # Find all the pairwise distances between each of the points in the two systems across time (ignoring the transient) dist = cdist(outputs[start_ind:], target_output[start_ind:], metric='euclidean') # Find the one point where the distance between the two systems was the smallest: t1 and t2 t1, t2 = numpy.unravel_index(numpy.argmin(dist, axis=None), dist.shape) # Use that point to align the rest of the points and take the cumulative of that distance cum_dist = 0.0 n = len(dist) for i in range(n): cum_dist += dist[t1][t2] t1 = (t1 + 1) % n t2 = (t2 + 1) % n avg_dist = cum_dist / n return 1 - avg_dist
def fitnessFunction(genotype): time = np.arange(0.0, duration, stepsize) nn = ctrnn.CTRNN(nnsize) nn.setParameters(genotype, WeightRange, BiasRange, TimeConstMin, TimeConstMax) nn.initializeState(np.zeros(nnsize)) ip_count = 0 #count of (i)nflection (p)oints slope_list = [] for t in time: #simulate network pastOutput = nn.Output[ 0] #get output at current step (soon to be past) nn.step(stepsize) #run one step currentOutput = nn.Output[0] #get output at current step if (currentOutput - pastOutput) > 1: #this will populate slope list slope = True #positive slope else: slope = False #negative slope slope_list.append(slope) for s in range((len(slope_list) - 1)): #this loop will count the number of inflection points if slope_list[s] != slope_list[s + 1]: ip_count += 1 return ip_count
def large_n_fitness(genotype): time = numpy.arange(0.0, duration, stepsize) net = ctrnn.CTRNN(nnsize) net.setParameters(genotype, WeightRange, BiasRange, TimeConstMin, TimeConstMax) net.initializeState(numpy.zeros(nnsize)) outputs = numpy.zeros((len(time), nnsize)) for t in time: net.step(stepsize) outputs[int(t / stepsize)] = net.Output #CONVERT OUTPUTS INTO PCA OUTPUTS BY APPLYING same transformation res_out = pca.transform(outputs) dim = 2 # Find all the pairwise distances between each of the points in PCA space in the two systems across time (ignoring the transient) dist = cdist(res_out[start_ind:, :dim], res_targ[start_ind:, :dim], metric='euclidean') # Find the one point where the distance between the two systems was the smallest: t1 and t2 t1, t2 = numpy.unravel_index(numpy.argmin(dist, axis=None), dist.shape) # Use that point to align the rest of the points and take the cumulative of that distance cum_dist = 0.0 n = len(dist) for i in range(n): cum_dist += dist[t1][t2] t1 = (t1 + 1) % n t2 = (t2 + 1) % n avg_dist = cum_dist / (n * numpy.sqrt(dim)) return 1 - avg_dist
def create_phenotype(chromo): num_inputs = chromo.sensors num_neurons = len(chromo.node_genes) - num_inputs #num_outputs = chromo.actuators network = ctrnn.CTRNN(num_inputs, num_neurons) #network.set_rk4(0.01) # integration method network.set_euler(0.01) if chromo.node_genes[-1].activation_type == 'tanh': network.set_logistic(False) # create neurons neuron_type = None for ng in chromo.node_genes[num_inputs:]: if ng.type == 'OUTPUT': neuron_type = 1 else: neuron_type = 0 #print 'Creating neuron: ', ng.id-num_inputs-1, ng.bias, ng.response, neuron_type network.setNeuronParameters(ng.id-num_inputs-1, ng.bias, ng.response, neuron_type) # create connections for cg in chromo.conn_genes: if cg.enabled: if cg.innodeid-1 < num_inputs: # set sensory input network.set_sensory_weight(cg.innodeid-1, cg.outnodeid-num_inputs-1, cg.weight) #print "Sensory: ", cg.innodeid-1, cg.outnodeid-num_inputs-1, cg.weight else: # set interneuron connection network.SetConnectionWeight(cg.innodeid-num_inputs-1, cg.outnodeid-num_inputs-1, cg.weight) #print "Inter..: ", cg.innodeid-num_inputs, cg.outnodeid-num_inputs-1, cg.weight return network
def fitnessFunction(genotype): time = numpy.arange(0.0,duration,stepsize) nn = ctrnn.CTRNN(nnsize) nn.setParameters(genotype,WeightRange,BiasRange,TimeConstMin,TimeConstMax) nn.initializeState(numpy.zeros(nnsize)) fit = 0.0 for t in time: pastOutputs = nn.Output nn.step(stepsize) currentOutputs = nn.Output fit += numpy.sum(abs(currentOutputs - pastOutputs)) return fit/(nnsize*duration)
bf[i] = np.load(dir + "best_fitness.npy") bi[i] = np.load(dir + "best_individual.npy") plt.plot(af.T, 'b') plt.plot(bf.T, 'g') plt.xlabel("Generations") plt.ylabel("Fitness") plt.title("Evolution") plt.show() plt.figure() # Get best evolved networks and show its activity for i in range(reps): if bf[i][-1] > fitness_threshold: time = np.arange(0.0, duration, stepsize) nn = ctrnn.CTRNN(nnsize) nn.setParameters(bi[i], WeightRange, BiasRange, TimeConstMin, TimeConstMax) nn.initializeState(np.zeros(nnsize)) outputs = np.zeros((len(time), nnsize)) step = 0 for t in time: nn.step(stepsize) outputs[step] = nn.Output step += 1 plt.plot(outputs.T[0][start_index:], outputs.T[1][start_index:]) # Also show the activity of the target network target_genotype = np.load(dir + "target_genotype.npy") time = np.arange(0.0, duration, stepsize) nn = ctrnn.CTRNN(nnsize)
def runtrial(c, task): sp, rp, goal = task sim = line_location.line_location(senderPos=sp, receiverPos=rp, goal=goal) time_const = line_location.line_location.timestep sender = ctrnn.CTRNN(c, time_const) receiver = ctrnn.CTRNN(c, time_const) sender.reset() receiver.reset() sender_positions = [] receiver_positions = [] # Run the given simulation for up to num_steps time steps. while sim.t < simulation_seconds: senderstate = sim.getState(True) receiverstate = sim.getState(False) act1 = sender.eulerStep(senderstate) act2 = receiver.eulerStep(receiverstate) senderOut = act1[0] receiverOut = act2[0] sim.step(senderOut, receiverOut) sender_positions.append(sim.senderPos) receiver_positions.append(sim.receiverPos) plt.figure() plt.xlim(left=0, right=1.2) plt.ylim(bottom=0, top=-300) plt.xlabel("Position") plt.ylabel("Time") plt.vlines(0.3, 0, -300, colors='black', linestyles='dotted') plt.vlines(goal, 0, -300, colors='green', linestyles='dotted') history_c = len(sender_positions) history_ys = range(-history_c + 1, 1) alphalist = [i / history_c for i in range(history_c)] if history_c != 0 else 1 plt.scatter(sender_positions, history_ys, c="blue", alpha=alphalist) plt.scatter(receiver_positions, history_ys, c="orange", alpha=alphalist) plt.savefig(f"./frames/{sim.t}") plt.close() # print(sim.getAsciiState()) # 2 second pause at the end for i in range(1, 49): plt.figure() plt.xlim(left=0, right=1.2) plt.ylim(bottom=0, top=-300) plt.xlabel("Position") plt.ylabel("Time") plt.vlines(0.3, -0.5, sim.t, colors='black', linestyles='dotted') plt.vlines(goal, -0.5, sim.t, colors='green', linestyles='dotted') history_c = len(sender_positions) history_ys = range(-history_c + 1, 1) plt.plot(sender_positions, history_ys, c="blue") plt.plot(receiver_positions, history_ys, c="orange") plt.savefig(f"./frames/{sim.t+i}") plt.close()
np.random.uniform(-1, 1), np.random.uniform(-1, 1) ] for _ in range(10)] for inputs in inplist: print(inputs) fig = plt.figure() ax = plt.axes(projection="3d") for state in itertools.product([-10, 10], repeat=3): # state = [np.random.uniform(-10,10),np.random.uniform(-10,10),np.random.uniform(-10,10)] states = state t = 0 time_const = line_location.line_location.timestep brain = ctrnn.CTRNN(c, time_const) brain.setStates(np.array(state, dtype=np.float64)) # Run the given simulation for up to num_steps time steps. while t < 10000: # if sim.t < 1.5: # receiverstate[0] = 0 # senderstate[0] = 0 brain.eulerStep(inputs) states = np.vstack([states, brain.states]) t += time_const ax.plot3D(states[:, 0], states[:, 1], states[:, 2]) print(states[-1]) ax.scatter3D(states[::10, 0], states[::10, 1], states[::10, 2])
cg.outnodeid - num_inputs - 1, cg.weight) #print "Sensory: ", cg.innodeid-1, cg.outnodeid-num_inputs-1, cg.weight else: # set interneuron connection network.SetConnectionWeight(cg.innodeid - num_inputs - 1, cg.outnodeid - num_inputs - 1, cg.weight) #print "Inter..: ", cg.innodeid-num_inputs, cg.outnodeid-num_inputs-1, cg.weight return network if __name__ == "__main__": # setting a network manually network = ctrnn.CTRNN(0, 2) network.set_logistic(True) network.set_euler(0.05) # integrate using Euler's method #network.set_rk4(0.05) network.setNeuronParameters(0, -2.75, 1.0, 1) network.setNeuronParameters(1, -1.75, 1.0, 1) network.set_neuron_state(0, -0.084000643) network.set_neuron_state(1, -0.408035109) network.SetConnectionWeight(0, 0, 4.5) network.SetConnectionWeight(0, 1, -1.0) network.SetConnectionWeight(1, 0, 1.0) network.SetConnectionWeight(1, 1, 4.5)
# plt.yticks(fontsize=14) # plt.tight_layout() # plt.savefig("params_{0}".format(targ)) estimated_pars = np.mean(bi1, axis=0) #np.median(bi1, axis=0) # plt.figure() plt.scatter(np.arange(bi1.shape[1]-nnsize), 15*target_genotype[:-nnsize], color='r', label='Target') plt.scatter(np.arange(bi1.shape[1]-nnsize), 15*estimated_pars[:-nnsize], color='g', label='Estimated') plt.legend() plt.ylabel("Parameter Value", fontsize=14) plt.xlabel("Parameter Index", fontsize=14) plt.title("Estimated parameter values (average)", fontsize=18) plt.xticks(np.arange(bi1.shape[1]-nnsize), np.arange(bi1.shape[1]-nnsize)) plt.savefig("n{0}_avgestimate_{1}.png".format(nnsize, targ)) fig = plt.figure() nn_1 = ctrnn.CTRNN(nnsize) nn_1.setParameters(target_genotype,WeightRange,BiasRange,TimeConstMin,TimeConstMax) nn_1.initializeState(np.zeros(nnsize)) time = np.arange(0.0,duration,stepsize) outputs_targ = np.zeros((len(time),nnsize)) step = 0 for t in time: nn_1.step(stepsize) outputs_targ[step] = nn_1.Output step += 1 nn_2 = ctrnn.CTRNN(nnsize) nn_2.setParameters(estimated_pars,WeightRange,BiasRange,TimeConstMin,TimeConstMax) nn_2.initializeState(np.zeros(nnsize)) time = np.arange(0.0,duration,stepsize) outputs_est = np.zeros((len(time),nnsize)) step = 0
print("Initial conditions:") print(" Sender = {0:.4f}".format(sp)) print(" Receiver = {0:.4f}".format(rp)) print() fig, ax = plt.subplots(3,3) i = 0 # for goal in [0.5,0.6,0.7,0.8,0.9]: for goal in [0.5,0.7,0.9]: displacement = [[],[],[]] rsens = [[],[],[]] ssens = [[],[],[]] sim = line_location.line_location(senderPos=sp,receiverPos=rp,goal=goal) time_const = line_location.line_location.timestep sender = ctrnn.CTRNN(c,time_const) receiver = ctrnn.CTRNN(c,time_const) sender.reset() receiver.reset() vals = [] # Run the given simulation for up to num_steps time steps. while sim.t < simulation_seconds: senderstate = sim.getState(True) receiverstate = sim.getState(False) # if sim.t < 1.5: # receiverstate[0] = 0 # senderstate[0] = 0 act1 = sender.eulerStep(senderstate) act2 = receiver.eulerStep(receiverstate)
def dendro(params, target_params, typ, dist_thresh): param2 = np.zeros((params.shape[0]+1,gs)) param2[:params.shape[0]] = params param2[-1] = target_params param3 = param2[:,:-nnsize] Z = linkage(param3, typ) plt.figure() d = dendrogram(Z, orientation='left', labels=list(np.arange(params.shape[0]))+['*'], color_threshold=dist_thresh*max(Z[:,2])) plt.title("{0}-neuron results: dendrogram - {1}".format(nnsize, typ)) plt.savefig("dendrogram_{0}.png".format(targ)) colors_seen = set() time = np.arange(0.0,duration,stepsize) clusters = {} clust_list = dendro_clusters(d) print(clust_list) for color in clust_list: for num in clust_list[color]: if num == '*': continue else: if color not in colors_seen: colors_seen.add(color) clusters[color] = [params[num,:]] print(color) print(num) else: clusters[color].append(params[num,:]) print(num) for color in clusters: clusters[color] = np.stack(clusters[color], axis=0) colnum = params.shape[1] paramsl = np.concatenate(clusters[color]) data = pd.DataFrame([[paramsl[0], '0']], columns=["Value", "Gene"]) for idx, val in enumerate(paramsl): if idx%colnum >= colnum-nnsize: continue else: data = data.append({"Value": val, "Gene": str(idx%colnum)}, ignore_index=True) plt.figure() sns.swarmplot(x="Gene", y="Value", data=data) plt.title("Cluster {0}".format(color)) plt.savefig("{0}_cluster_{1}_genotype.png".format(targ, color)) if nnsize == 2: plt.figure() plt.title("Phase portrait - Cluster {0}".format(color)) plt.xlabel("Neuron 1") plt.ylabel("Neuron 2") nn = ctrnn.CTRNN(nnsize) nn.setParameters(target_genotype,WeightRange,BiasRange,TimeConstMin,TimeConstMax) nn.initializeState(np.zeros(nnsize)) outputs = np.zeros((len(time),nnsize)) step = 0 for t in time: nn.step(stepsize) outputs[step] = nn.Output step += 1 plt.plot(outputs.T[0][start_index:],outputs.T[1][start_index:], 'k', label="Target", zorder=2) for pars in clusters[color]: nn1 = ctrnn.CTRNN(nnsize) nn1.setParameters(pars,WeightRange,BiasRange,TimeConstMin,TimeConstMax) nn1.initializeState(np.zeros(nnsize)) outputs1 = np.zeros((len(time),nnsize)) step1 = 0 for t in time: nn1.step(stepsize) outputs1[step1] = nn1.Output step1 += 1 plt.plot(outputs1.T[0][start_index:],outputs1.T[1][start_index:], zorder=1) plt.savefig("{0}_cluster_{1}_phase.png".format(targ, color)) return d, clusters, clust_list
def compare_phase(params, target_params): outs_list = [] time = np.arange(0.0, duration, stepsize) for pars in params: nn = ctrnn.CTRNN(nnsize) nn.setParameters(pars, WeightRange, BiasRange, TimeConstMin, TimeConstMax) nn.initializeState(np.zeros(nnsize)) outputs = np.zeros((len(time), nnsize)) step = 0 for t in time: nn.step(stepsize) outputs[step] = nn.Output step += 1 outs_list.append(outputs) for i in range(nnsize - 2): if i % 2 == 0: fig = plt.figure() ax = fig.add_subplot(111, projection='3d') ax.set_xlabel("Neuron {0}".format(i)) ax.set_ylabel("Neuron {0}".format(i + 1)) ax.set_zlabel("Neuron {0}".format(i + 2)) ax.plot3D(target_output.T[i][start_index:], target_output.T[i + 1][start_index:], target_output.T[i + 2][start_index:], 'k', zorder=2) #calculate target_output earlier for outs in outs_list: ax.plot3D(outs.T[i][start_index:], outs.T[i + 1][start_index:], outs.T[i + 2][start_index:], zorder=1) plt.savefig("N{0}/{2}/phase_{1}.png".format(nnsize, i, targ)) pca = PCA(n_components=None, svd_solver='auto') pca.fit(target_output) #calculate target_output earlier res_target = pca.transform(target_output) res_list = [] for outs in outs_list: res_est = pca.transform(outs) res_list.append(res_est) # df_PCA = pd.DataFrame(res_target[:, 0:9], columns=['1c', '2c', '3c', '4c', '5c', '6c', '7c', '8c', '9c']) df_PCA = pd.DataFrame(res_target[:, 0:4], columns=['1c', '2c', '3c', '4c']) s_Var = pd.Series(pca.explained_variance_ratio_, index=range(1, (res_target.shape[1] + 1)), name='explained_variance_ratio') fig, ((ax1, ax2, ax3), (ax4, ax5, ax6), (ax7, ax8, ax9)) = plt.subplots(figsize=(12, 10), nrows=3, ncols=3) fig.suptitle("PCA on output for {0} neurons".format(nnsize)) s_cumsum = s_Var.cumsum() n_eigen_95 = s_cumsum[(s_cumsum < 0.95)].shape[0] n = 4 #4 ind = np.arange(n) height = s_Var.iloc[:n].values width = 0.60 xticklabels = (ind + 1) cmap = mpl.cm.get_cmap('hsv_r') norm = mpl.colors.Normalize(vmin=0, vmax=n) tab20 = cm.get_cmap('tab20').colors s_colors = tab20[0::2] s_edgecolors = tab20[1::2] ax1.bar(ind, height, width, color=s_colors, edgecolor=s_edgecolors, zorder=9, lw=1) ax1.set_xticks(ind) ax1.set_xticklabels(xticklabels) ax1.set_title('Explained variance ratio') ax1.annotate('95% with {:,d}\nsingular vectors'.format(n_eigen_95), xy=(0.97, 0.97), xycoords="axes fraction", ha='right', va='top') ax1.set_xlabel('Components') ax1.set_ylabel('%') ax1.grid() for dim, ax in zip(range(1, 10), [ax2, ax3, ax4, ax5, ax6, ax7, ax8, ax9]): print('- Dim: {:d}'.format(dim)) col = str(dim) + 'c' x = str(dim) + 'c' y = str(dim + 1) + 'c' xs = df_PCA[x].tolist() ys = df_PCA[y].tolist() ax.plot(xs[start_index:], ys[start_index:], 'k', zorder=2) ax.plot(0, 0, color='#2ca02c', marker='x', ms=16) for res in res_list: ax.plot(res[start_index:, dim - 1], res[start_index:, dim], zorder=1) ax.axhline(y=0, c='black', lw=0.75, ls='-.', zorder=2) ax.axvline(x=0, c='black', lw=0.75, ls='-.', zorder=2) ax.set_title('Components {dim1} and {dim2}'.format(dim1=dim, dim2=(dim + 1))) ax.set_xlabel('Component {dim1:d}'.format(dim1=dim)) ax.set_ylabel('Component {dim2:d}'.format(dim2=dim + 1)) ax.grid() ax.axis('equal') ax.locator_params(axis='both', tight=True, nbins=6) plt.subplots_adjust(left=0.06, right=0.98, bottom=0.06, top=0.93, wspace=0.26, hspace=0.35) plt.savefig("N{1}/results_outputs_pca_{0}.png".format(targ, nnsize)) df_PCA.to_csv("N{1}/results_outputs_pca_{0}.csv".format(targ, nnsize))
def dendro_clusters(d): cluster_idxs = defaultdict(list) for c, pi in zip(d['color_list'], d['icoord']): for leg in pi[1:3]: i = (leg - 5.0) / 10.0 if abs(i - int(i)) < 1e-5: cluster_idxs[c].append(int(i)) cluster_classes = {} for c, l in cluster_idxs.items(): i_l = [d['ivl'][i] for i in l] cluster_classes[c] = i_l bestfit_params = {} avg_params = {} for cluster in cluster_classes: fits = {} params = np.zeros((len(cluster_classes[cluster]), gs)) i = 0 j = -1 for idx in cluster_classes[cluster]: if idx == "*": j = i i += 1 else: fits[idx] = bf[idx, -1] params[i] = bi[idx] i += 1 if j != -1: params = np.delete(params, j, 0) bestfit_params[cluster] = (bi[max(fits, key=fits.get)], max(fits, key=fits.get)) #Parameters, index # avg_params[cluster] = np.mean(params, axis=0) if nnsize == 3: time = np.arange(0.0, duration, stepsize) fig = plt.figure() ax = fig.add_subplot(121, projection='3d') plt.title("Representative networks - best fit individuals") ax.set_xlabel("Neuron 1") ax.set_ylabel("Neuron 2") ax.set_zlabel("Neuron 3") nn = ctrnn.CTRNN(nnsize) nn.setParameters(target_genotype, WeightRange, BiasRange, TimeConstMin, TimeConstMax) nn.initializeState(np.zeros(nnsize)) outputs = np.zeros((len(time), nnsize)) step = 0 for t in time: nn.step(stepsize) outputs[step] = nn.Output step += 1 ax.plot3D(outputs.T[0][start_index:], outputs.T[1][start_index:], outputs.T[2][start_index:], 'orange', label="Target", zorder=2) paramsl = [] for cluster in bestfit_params: pars = bestfit_params[cluster][0] paramsl.append(pars) nn1 = ctrnn.CTRNN(nnsize) nn1.setParameters(pars, WeightRange, BiasRange, TimeConstMin, TimeConstMax) nn1.initializeState(np.zeros(nnsize)) outputs1 = np.zeros((len(time), nnsize)) step1 = 0 for t in time: nn1.step(stepsize) outputs1[step1] = nn1.Output step1 += 1 ax.plot3D( outputs1.T[0][start_index:], outputs1.T[1][start_index:], outputs1.T[2][start_index:], zorder=1, color=cluster, label=str(bestfit_params[cluster][1]) ) #, label="No.{0}, fit={1}".format(bestfit_params[cluster][1], fits[bestfit_params[cluster][1]]) paramsl = np.vstack(paramsl) plt.legend() colors = list(bestfit_params.keys()) ax1 = fig.add_subplot(122) ax1.set_xlabel("Gene index #") ax1.set_ylabel("Value") # colnum = paramsl.shape[1] # paramsl = np.concatenate(paramsl) # data = pd.DataFrame([[paramsl[0], '0', colors[0]]], columns=["Value", "Gene", "Cluster"]) # for idx, val in enumerate(paramsl): # if idx%colnum >= colnum-nnsize: # continue # else: # data = data.append({"Value": val, "Gene": str(idx%colnum)}, ignore_index=True) ax1.scatter(np.arange(nnsize**2 + nnsize), target_genotype[:-nnsize], color='orange', label="Target", zorder=2) for cluster in bestfit_params: ax1.scatter(np.arange(nnsize**2 + nnsize), bestfit_params[cluster][0][:-nnsize], color=cluster, zorder=1) plt.legend() fig1 = plt.figure() ax2 = fig1.add_subplot(121, projection='3d') plt.title("Representative networks - average individual") ax2.set_xlabel("Neuron 1") ax2.set_ylabel("Neuron 2") ax2.set_zlabel("Neuron 3") nn = ctrnn.CTRNN(nnsize) nn.setParameters(target_genotype, WeightRange, BiasRange, TimeConstMin, TimeConstMax) nn.initializeState(np.zeros(nnsize)) outputs = np.zeros((len(time), nnsize)) step = 0 for t in time: nn.step(stepsize) outputs[step] = nn.Output step += 1 ax2.plot3D(outputs.T[0][start_index:], outputs.T[1][start_index:], outputs.T[2][start_index:], 'orange', label="Target", zorder=2) paramsl = [] for cluster in avg_params: pars = avg_params[cluster] paramsl.append(pars) nn1 = ctrnn.CTRNN(nnsize) nn1.setParameters(pars, WeightRange, BiasRange, TimeConstMin, TimeConstMax) nn1.initializeState(np.zeros(nnsize)) outputs1 = np.zeros((len(time), nnsize)) step1 = 0 for t in time: nn1.step(stepsize) outputs1[step1] = nn1.Output step1 += 1 ax2.plot3D(outputs1.T[0][start_index:], outputs1.T[1][start_index:], outputs1.T[2][start_index:], zorder=1, color=cluster) paramsl = np.vstack(paramsl) ax3 = fig1.add_subplot(122) ax3.set_xlabel("Gene index #") ax3.set_ylabel("Value") ax3.scatter(np.arange(nnsize**2 + nnsize), target_genotype[:-nnsize], color='orange', label="Target", zorder=2) for cluster in avg_params: ax3.scatter(np.arange(nnsize**2 + nnsize), avg_params[cluster][:-nnsize], color=cluster, zorder=1) return cluster_classes