# analysis.py -- Python script for running the simulation interactively # # Usage: # ipython --pylab -i sim.py # # Last update: 13/09/10 (salvadord) # # Global parameters # # Load the sys and os packages. import sys, os from neuron import h # Load the interpreter object. from numpy import * from pylab import * #from pylab import figure, array, size, zeros, subplot, ion, show, pause, hold, sum from os import system,listdir from copy import deepcopy import scipy.io import numpy as np import pickle from bicolormap import bicolormap import time import analyse_funcs # for ipython debugging #from IPython.core.debugger import Tracer; debug_here = Tracer() # show graphs with batch simulations error results def batchErrors(simdatadir, param1Arg=None): # Set up the simulation data directory. #simdatadir = 'data/13sep06_sim1' invert_axis = 1; # seed values wseedvals =[120456, 398115]#, 534031, 796321, 895199] iseedvals = [1235, 2837]#, 3955, 4506, 6789] # parameter values #arange(10,110,10)# #[0.01, 0.025, 0.05, 0.075, 0.1, 0.125, 0.15]#[10,20,30,40,50,60,70,80,90,100]#[50, 100,250,500,750,1000]#arange(20,180,20)#[25, 50,75, 100, 125, 150, 175, 200, 225, 250]# if param1Arg==None: param1_range =arange(0.8,1.24,0.04)#arange(1,9)# [0,1]#arange(50,550,50) else: param1_range=param1Arg param2_range = [0,1,2,3,4,5,6,7] # number of errror values = 6 = (ang vs xy) x (10%, 50%, 90%) err_vals = 6; # create array for all results (2 errors, 10 train times, 5 wseeds, 5 inseed, 4 error values) error_all = zeros((len(param1_range),len(param2_range),len(wseedvals),len(iseedvals),err_vals)) # create array for results avg'd over seeds (2 errors, 10 train times, 4 error values) error_avg = zeros((len(param1_range),len(param2_range),err_vals)) error_std = zeros((len(param1_range),len(param2_range),err_vals)) error_p1_avg = zeros((len(param1_range),err_vals)) # Loop over param1 values iparam1 = -1 for param1 in param1_range: iparam1 = iparam1 + 1 iparam2 = -1 skipValue = 0 # Loop over param2 values for param2 in param2_range: iparam2 = iparam2 + 1 iwseed = -1 # Loop over wiring seed... for wseed in wseedvals: iwseed = iwseed + 1 iiseed = -1 # Loop over input seed... for iseed in iseedvals: iiseed = iiseed + 1 # set filename outfilestem = '%s/p1-%d_p2-%d_i-%d_w-%d_test-nqa.nqs' % (simdatadir, param1, param2, iseed, wseed) if os.path.isfile(outfilestem): print "loading "+str(outfilestem) else: outfilestem = '%s/p1-%.2f_p2-%d_i-%d_w-%d_test-nqa.nqs' % (simdatadir, param1, param2, iseed, wseed) if os.path.isfile(outfilestem): print "loading "+str(outfilestem) else: outfilestem = '%s/p1-%.3f_p2-%d_i-%d_w-%d_test-nqa.nqs' % (simdatadir, param1, param2, iseed, wseed) if os.path.isfile(outfilestem): print "loading "+str(outfilestem) else: skipValue=1 # get errors from nqs if skipValue==0: tmp = h.calcErrorFromNQ(outfilestem).to_python() tmp =array(tmp) error_all[iparam1, iparam2, iwseed, iiseed, :] = tmp #print tmp # calculate avg error over seeds if skipValue==0: for i in arange(err_vals): error_avg[iparam1, iparam2, i] = mean(error_all[iparam1, iparam2, :, :, i]) error_std[iparam1, iparam2, i]= std(error_all[iparam1, iparam2, :, :, i]) # calculate average over all targets (param2) for each value of param1 if skipValue==0: for i in arange(err_vals): error_p1_avg[iparam1, i] = mean(error_avg[iparam1,:,i]) # plot results figsize=[800,500] fig = figure(figsize=(figsize[0]/100,figsize[1]/100),dpi=100) ax1 = fig.add_subplot(211) ax2 = fig.add_subplot(212) param_xaxis = 'param2' #debug_here() if invert_axis: param_xaxis='param1' tmp=param1_range param1_range = param2_range param2_range = tmp error_avg = swapaxes(error_avg, 0, 1) xaxis=array(param2_range) colorlist = ['black','darkgrey','blue', 'cyan', 'green', 'brown', 'red', 'magenta', 'orange','yellow'] # plot cartesian error iparam1=-1 for param1 in param1_range: iparam1 = iparam1 + 1 #ax1.errorbar(xaxis, error_avg[iparam1,:,0], yerr=error_std[0,:,0], fmt='s', color = colorlist[iparam1%10],) #ax1.errorbar(xaxis, error_avg[iparam1,:,1], yerr=error_std[0,:,1], fmt='o', color = colorlist[iparam1%10], ) #ax1.errorbar(xaxis, error_avg[iparam1,:,2], yerr=error_std[0,:,2], fmt='x', color = colorlist[iparam1%10], ) #ax1.plot(xaxis, error_avg[iparam1,:,0], color = colorlist[iparam1%10], label=str(param1)+', last 10%') ax1.plot(xaxis, error_avg[iparam1,:,0], linestyle = "--",color = colorlist[iparam1%10],label=str(param1)+', last 20%') ax1.plot(xaxis, error_avg[iparam1,:,2], linestyle = "-", color = colorlist[iparam1%10], label=str(param1)+', last 90%') ax1.plot(xaxis, error_p1_avg[:,0], linestyle = "--",color = 'black',linewidth=4, label='AVG - 20%') ax1.plot(xaxis, error_p1_avg[:,2], linestyle = "-", color = 'black', linewidth=4, label='AVG - 90%') ax1.set_ylabel('cartesian error (m)') ax1.set_xlabel(param_xaxis) ax1.set_title('Cartesian error as a func of param1 and param2') #ax1.legend(loc='upper center', bbox_to_anchor=(1, 0.2), borderaxespad=0., prop={'size':12}) ax1.grid(True) # plot angular error iparam1=-1 for param1 in param1_range: iparam1 = iparam1 + 1 #ax2.errorbar(xaxis, error_avg[iparam1,:,3], yerr=error_std[0,:,3], fmt='s', color = colorlist[iparam1%10],) #ax2.errorbar(xaxis, error_avg[iparam1,:,4], yerr=error_std[0,:,4], fmt='o', color = colorlist[iparam1%10],) #ax2.errorbar(xaxis, error_avg[iparam1,:,5], yerr=error_std[0,:,5], fmt='x', color = colorlist[iparam1%10], ) #ax2.plot(xaxis, error_avg[iparam1,:,3], color = colorlist[iparam1%10], label=str(param1)+', last 10%') ax2.plot(xaxis, error_avg[iparam1,:,3], linestyle = "--", color = colorlist[iparam1%10], label=str(param1)+', last 20%') ax2.plot(xaxis, error_avg[iparam1,:,5], linestyle = "-",color = colorlist[iparam1%10], label=str(param1)+', last 90%') ax2.plot(xaxis, error_p1_avg[:,3], linestyle = "--",color = 'black',linewidth=4, label='AVG - last 20%') ax2.plot(xaxis, error_p1_avg[:,5], linestyle = "-", color = 'black', linewidth=4, label=' AVG - last 90%') ax2.set_ylabel('angular error (rad)') ax2.set_xlabel(param_xaxis) ax2.set_title('Angular error as a func of param1 and param2') ax2.legend(loc='upper right', bbox_to_anchor=(1.1, 2.0), borderaxespad=0., prop={'size':12}) ax2.grid(True) fig.tight_layout() show() # show the receptive field of a neuron or group of neurons (targetCell); # nSyn = number of synaptic connections to take into account; eg. if 1: ES->EM; if 2, DP->ES->EM # animate = include synaptic changes over time; make graph # show error graphs for 8 sims of same day def batchErrors8(simdatadirRoot): numSims = 8 param1_range = []#[None] * numSims param1_range.append([10,20,30,40,50]) param1_range.append([10,20,30,40,50,60,70,80,90,100]) param1_range.append(arange(0.8,1.24,0.04))#([0.012, 0.025, 0.05, 0.075, 0.1, 0.125, 0.15]) param1_range.append([10,20,30,40,50,60,70,80,90,100]) param1_range.append([25, 50,75, 100, 125, 150, 175, 200, 225, 250]) param1_range.append([20,40,60,80,100,120,140,160]) param1_range.append([200,225,250,275,300,325,350]) param1_range.append([50, 100,250,500,750,1000]) for i in range(numSims): batchErrors(simdatadirRoot+'_sim'+str(i+1), param1_range[i]) # show the RF of targetCells # if nSyn2: use polysynaptic chains of length =2 # if animate: show RF change over time, overimposed with spikes def receptiveFieldAndSpikes(targetCells, nSyn2, animate, dosave): #dosave=1< if dosave: moviedir='data/movies/' moviename='13oct15b.mpg' maxmovieframes = 500 # Maximum number of movie frames view3d=0 showSpikes=1 print "Calculating receptive field of cell group starting at id %d " % targetCells[0] targetCells = array(targetCells) popnames=['P','ES','IS','ILS','EM','IM','IML']; popinds=[ 2, 41, 42, 43, 44, 45, 46]; popshape=['o', '^', 'h', '*', '^', 'h', '*', '8']; # convert connectivity to python arrays conpreid=array(h.col.connsnq.getcol("id1"), 'i') conpostid=array(h.col.connsnq.getcol("id2"), 'i') #condelay=array(h.col.connsnq.getcol("del")) #condistance=array(h.col.connsnq.getcol("dist")) conweight1=array(h.col.connsnq.getcol("wt1")) conweight2=array(h.col.connsnq.getcol("wt2")) order = lexsort((conpreid, conpostid)) # order by post and then pre conpreid = conpreid[order] conpostid = conpostid[order] #condelay = condelay[order] #condistance = condistance[order] conweight1 = conweight1[order] conweight2 = conweight2[order] maxW = max(conweight1.max(), conweight2.max()) conweight1 = conweight1/maxW # normalize so can multiply together conweight2 = conweight2/maxW # conweight1Original = deepcopy(conweight1) # make copy of weights at t=0 # convert locations to python arrays h('objref cellList') h('cellList=col.ce') h('objref cellListDP') h('cellListDP = cedp') n=h.cellList.count() # Number of cells ndp=h.cellListDP.count() # number of DP cells #cellLocations = zeros((n+ndp,5)) # number of cells and attributes cellids =zeros(n+ndp) celltypes = zeros(n+ndp) xlocs =zeros(n+ndp) ylocs =zeros(n+ndp) zlocs =zeros(n+ndp) for i in range(int(n)): # Loop over each cell cellids[i]=i # Cell ID celltypes[i]=h.cellList.o(i).type() # Cell population xlocs[i]=h.cellList.o(i).xloc # X position ylocs[i]=h.cellList.o(i).yloc # Y position zlocs[i]=h.cellList.o(i).zloc # Z position for i in range(int(ndp)): # Loop over each cell cellids[n+i]=n+i # Cell ID celltypes[n+i]=h.cellListDP.o(i).type # Cell population xlocs[n+i]=h.cellListDP.o(i).xloc # X position ylocs[n+i]=h.cellListDP.o(i).yloc # Y position zlocs[n+i]=h.cellListDP.o(i).zloc # Z position # arrange neurons in spatial grid and according to muscle group spatialGrid = 1 if spatialGrid: x = [0, 0, 0, 0, 0] # initial starting positions y = [0, 0, 0, 0, 0] xstep = 1 # step increase ystep = 1.5 xmax = 10 for i in range(len(xlocs)): if celltypes[i] == popinds[1]: #ES xmax = 24 xoffset = [0, 0, 0, 0, 0] yoffset = [0, 0, 0, 0, 14] zlocs[i] = 0 # fix to same muscle group elif celltypes[i] == popinds[2]: #IS zlocs[i] = 4 # do not divide in muscle groups elif celltypes[i] == popinds[3]: #ISL zlocs[i] = 4 # do not divide in muscle groups elif celltypes[i] == popinds[4]: #EM xoffset = [0, 14, 0, 14, 5] #offset for different muscle populations + inhibitory cells yoffset = [0, 0, 14, 14, 7] xmax = 12 elif celltypes[i] == popinds[5]: #IM zlocs[i] = 4 # do not divide in muscle groups xmax = 16 elif celltypes[i] == popinds[6]: #IML zlocs[i] = 4 # do not divide in muscle groups xmax = 16 elif celltypes[i] == popinds[0]: #P xmax = 12 xoffset = [0, 14, 0, 14, 3] #offset for different muscle populations + inhibitory cells yoffset = [0, 0, 12, 12, 9] zloc = int(zlocs[i]) x[zloc] = x[zloc] + xstep # increase step if x[zloc] > xmax: # if reached x limit y[zloc] = y[zloc] + ystep x[zloc] = 1 xlocs[i] = x[zloc] + xoffset[zloc] # set positions ylocs[i] = y[zloc] + yoffset[zloc] if (i==(192+44+20-1) or (i==(2*(192+44+20)-1))): # when change subplot, restart xy positions x = [0, 0, 0, 0, 0] # initial starting positions y = [0, 0, 0, 0, 0] ######################## # animation data and params if animate: # convert synaptic changes over time (since connsnq doesn't change with t, can add) h('objref synChanges') #h('nqsy.tog()') h('nqsy.select("t",">=", 0)') h('synChanges = nqsy') synpreid=array(h.synChanges.getcol("id1"), 'i') synpostid=array(h.synChanges.getcol("id2"), 'i') synweight=array(h.synChanges.getcol("wg")) syntime=array(h.synChanges.getcol("t")) order = lexsort((synpreid, synpostid)) # order syn by post and then pre synpreid = synpreid[order] synpostid = synpostid[order] synweight=synweight[order] syntime=syntime[order] # convert spiking data to python arrays h('objref spikes') h('snq.select("t",">=", 0)') h('spikes = snq') spikeId=array(h.spikes.getcol("id")) spikeType=array(h.spikes.getcol("type")) spikeTime=array(h.spikes.getcol("t")) spikeMid=array(h.spikes.getcol("mid")) weightInc = h.plastEEinc / maxW # set weight increases and normalize def makeplot(): # visualization options figsize = [720,800] # Figure size in pixels targetColor = 'green';#array([(1,0.4,0) , (0,0.2,0.8)]) # Define excitatory and inhibitory colors -- orange and turquoise normalColor = 'white'#'lightyellow' targetSizeFactor = 2 weightsCmap = 'YlOrRd' #'jet'#'hot'#'autumn' cellSize = 50; cellBorder = 1; # create subplots for M, S and P populations ion() fig = figure(figsize=(figsize[0]/100,figsize[1]/100),dpi=100) fig.subplots_adjust(left=0.02) # Less space on left fig.subplots_adjust(right=0.93) # Less space on right fig.subplots_adjust(bottom=0.08) # Less space on bottom #fig.subplots_adjust(wspace=0.25) # More space between #fig.subplots_adjust(hspace=0.30) # More space between if view3d: proj='3d' else: proj='rectilinear' rasterMsubplot = subplot(311, projection=proj) # create subplots rasterSsubplot = subplot(312, projection=proj) rasterPsubplot = subplot(313, projection=proj) rasterMsubplot.set_title('Motor population', fontsize=12) # titles rasterSsubplot.set_title('Somatosensory population', fontsize=12) rasterPsubplot.set_title('Proprioceptive population', fontsize=12) rasterMsubplot.text(-0.7, 1, "sho\next", fontsize=10, fontweight='bold') # muscle labels M rasterMsubplot.text(26.6, 1, "sho\nflex", fontsize=10, fontweight='bold') rasterMsubplot.text(-0.7, 15, "elb\next", fontsize=10, fontweight='bold') rasterMsubplot.text(26.6, 15, "elb\nflex", fontsize=10, fontweight='bold') rasterPsubplot.text(-0.7, 1, "sho\next", fontsize=10, fontweight='bold') # muscle labels P rasterPsubplot.text(26.6, 1, "sho\nflex", fontsize=10, fontweight='bold') rasterPsubplot.text(-0.7, 13, "elb\next", fontsize=10, fontweight='bold') rasterPsubplot.text(26.6, 13, "elb\nflex", fontsize=10, fontweight='bold') setp(rasterMsubplot.get_xticklabels(), visible=False) # hide x and y ticks setp(rasterSsubplot.get_xticklabels(), visible=False) setp(rasterPsubplot.get_xticklabels(), visible=False) setp(rasterMsubplot.get_yticklabels(), visible=False) setp(rasterSsubplot.get_yticklabels(), visible=False) setp(rasterPsubplot.get_yticklabels(), visible=False) border = 2 rasterMsubplot.set_xlim([xlocs.min()-border, xlocs.max()+border]) # set x-y lims rasterMsubplot.set_ylim([ylocs.min()-border, ylocs.max()+border]) rasterSsubplot.set_xlim([xlocs.min()-border, xlocs.max()+border]) rasterSsubplot.set_ylim([ylocs.min()-border, ylocs.max()+border]) rasterPsubplot.set_xlim([xlocs.min()-border, xlocs.max()+border]) rasterPsubplot.set_ylim([ylocs.min()-border, ylocs.max()+border]) ###################### # plot cells in gray (static) cellsScatter = [None]*len(popinds); for p in range(len(popinds)): #cells=where(cellLocations[:,1]==popinds[p]) cells=(celltypes==popinds[p]) if view3d: if (p == 0): rasterPsubplot.scatter(xlocs[cells], ylocs[cells], zlocs[cells], c=normalColor, marker=popshape[p], linewidth=cellBorder, s=cellSize) elif (p>=1 and p<=3): rasterSsubplot.scatter(xlocs[cells], ylocs[cells], zlocs[cells], c=normalColor, marker=popshape[p], linewidth=cellBorder, s=cellSize) elif (p>=4 and p<=6): rasterMsubplot.scatter(xlocs[cells], ylocs[cells], zlocs[cells], c=normalColor, marker=popshape[p], linewidth=cellBorder, s=cellSize) else: if (p == 0): cellsScatter[p] = rasterPsubplot.scatter(xlocs[cells], ylocs[cells], c=normalColor, marker=popshape[p], linewidth=cellBorder, s=cellSize, label=popnames[p]) elif (p>=1 and p<=3): cellsScatter[p] = rasterSsubplot.scatter(xlocs[cells], ylocs[cells], c=normalColor, marker=popshape[p], linewidth=cellBorder, s=cellSize, label=popnames[p]) elif (p>=4 and p<=6): cellsScatter[p] = rasterMsubplot.scatter(xlocs[cells], ylocs[cells], c=normalColor, marker=popshape[p], linewidth=cellBorder, s=cellSize, label=popnames[p]) ############################# # show target cells in different color targetLabel = 'target cell' for i in range(len(targetCells)): for p in range(len(popinds)): # find target cells for each layer #targetLayerCells = intersect1d(targetCells, where(cellLocations[:,1]==popinds[p])[0]) targetLayerCells = (cellids==targetCells[i]) * (celltypes==popinds[p]) # obtain indices for population p if targetLayerCells.any(): # it at least one cell was found if (p == 0): rasterPsubplot.scatter(xlocs[targetLayerCells], ylocs[targetLayerCells], c=targetColor, marker=popshape[7], linewidth=cellBorder*2, s=cellSize*targetSizeFactor) elif (p>=1 and p<=3): rasterSsubplot.scatter(xlocs[targetLayerCells], ylocs[targetLayerCells], c=targetColor, marker=popshape[7], linewidth=cellBorder*2, s=cellSize*targetSizeFactor) elif (p>=4 and p<=6): if i == 0: targetPlot =rasterMsubplot.scatter(xlocs[targetLayerCells], ylocs[targetLayerCells], c=targetColor, marker=popshape[7], linewidth=cellBorder*2, s=cellSize*targetSizeFactor, label = targetLabel) else: rasterMsubplot.scatter(xlocs[targetLayerCells], ylocs[targetLayerCells], c=targetColor, marker=popshape[7], linewidth=cellBorder*2, s=cellSize*targetSizeFactor) legendLabels=['E', 'I', 'ILS', 'P', 'target'] rasterSsubplot.legend([cellsScatter[1], cellsScatter[2], cellsScatter[3], cellsScatter[0], targetPlot], legendLabels, columnspacing=0,markerscale=0.8, loc='upper center', prop={'size':9}, scatterpoints=1, bbox_to_anchor=(0.94, 1.05), borderpad=0.07)#, borderpad=0.05, labelspacing=0.1) ###################### # show afferent cells weights (RF) rf = [None]*len(popinds); def calculateRF(mode,rf): onlyAMPA = 1 adaptScale = 0 scaleMax =[0.5,1,1] # find all cells projecting to the target cell for each layer afferentCells = array([], 'i') weightColors = [] for i in range(len(targetCells)): targetAfferents = array(conpreid[where(conpostid==targetCells[i])], 'i') # get afferent of next target cell if targetAfferents.any(): # if any for iAfferent in targetAfferents: # for each new afferent if (iAfferent in afferentCells): # check if already included in list if onlyAMPA: weightColors2 = (conweight1[iAfferent]) else: weightColors2 = ((conweight1[iAfferent]) +(conweight2[iAfferent])) weightColors[afferentCells==iAfferent] += weightColors2 else: # if not included in list afferentCells=append(afferentCells, iAfferent) # add to list of afferent cells if onlyAMPA: weightColors = append(weightColors, conweight1[targetAfferents]); # calculate weigths else: weightColors = append(weightColors, conweight1[afferentCells]-conweight2[afferentCells]); # calculate weigths if nSyn2: # 2 synaptic connections for targetCell2 in targetAfferents: # loop through all afferent cells (which now become target cells) targetAfferents2 = array(conpreid[where(conpostid==targetCell2)], 'i') # get new set of afferent cells if targetAfferents2.any(): for iAfferent in targetAfferents2: # loop through all afferent cells if (iAfferent in afferentCells): # if already included in list if onlyAMPA: weightColors2 = (conweight1[targetCell2]) * (conweight1[iAfferent]) else: weightColors2 = (conweight1[targetCell2]) * (conweight1[iAfferent]) weightColors[afferentCells==iAfferent] += weightColors2 else: afferentCells=append(afferentCells, iAfferent) # add to list of afferent cells if onlyAMPA: weightColors2 = (conweight1[targetCell2]) * (conweight1[iAfferent]) else: weightColors2 = (conweight1[targetCell2]+conweight2[targetCell2]) * (conweight1[iAfferent]+conweight2[iAfferent]) weightColors=append(weightColors, weightColors2) weightColors = weightColors/weightColors.max() # normalize weights to 1 #print afferentCells for p in range(len(popinds)): # find all cells projecting to the target cell for each layer afferentCellsL = intersect1d(afferentCells, where(celltypes==popinds[p])[0]) # find indices for population p #print afferentCellsL if afferentCellsL.any(): weightColorsL = weightColors[in1d(afferentCells, afferentCellsL)]; # obtain weight colors for this population #print weightColorsL if mode == "new": if (p == 0): rf[p] = rasterPsubplot.scatter(xlocs[afferentCellsL], ylocs[afferentCellsL], cmap=weightsCmap, c=weightColorsL, vmin=0, vmax=scaleMax[0], marker=popshape[p], linewidth=cellBorder, s=cellSize) if adaptScale and ('c1' in locals() or 'c1' in globals()): rf[p].set_clim([weightColorsL.min(), weightColorsL.max()]) c1.set_clim([weightColorsL.min(), weightColorsL.max()]) c1.draw_all() elif (p>=1 and p<=3): rf[p] = rasterSsubplot.scatter(xlocs[afferentCellsL], ylocs[afferentCellsL], cmap=weightsCmap, c=weightColorsL, vmin=0, vmax=scaleMax[1], marker=popshape[p], linewidth=cellBorder, s=cellSize) if adaptScale and ('c2' in locals() or 'c2' in globals()): rf[p].set_clim([weightColorsL.min(), weightColorsL.max()]) c2.set_clim([weightColorsL.min(), weightColorsL.max()]) c2.draw_all() elif (p>=4 and p<=6): rf[p] = rasterMsubplot.scatter(xlocs[afferentCellsL], ylocs[afferentCellsL], cmap=weightsCmap, c=weightColorsL,vmin=0, vmax=scaleMax[0], marker=popshape[p], linewidth=cellBorder, s=cellSize) if adaptScale and ('c3' in locals() or 'c1' in globals()): rf[p].set_clim([weightColorsL.min(), weightColorsL.max()]) c3.set_clim([weightColorsL.min(), weightColorsL.max()]) c3.draw_all() elif mode == "update": rf[p].set_color(weightColorsL) rf[p].set_cmap(weightsCmap) #print afferentCells calculateRF("new",rf) tight_layout() cfraction = 0.09 cpad = 0.01 cshrink = 0.75 cfontsize=9 if rf[0] != None: c1=colorbar(rf[0], ax=rasterPsubplot, fraction=cfraction, pad=cpad, shrink=cshrink) c1.ax.tick_params(labelsize=cfontsize) c2=colorbar(rf[1], ax=rasterSsubplot, fraction=cfraction, pad=cpad, shrink=cshrink) c2.set_label('normalized weight to target cell', fontsize=cfontsize+1) c2.ax.tick_params(labelsize=cfontsize) c3=colorbar(rf[4], ax=rasterMsubplot, fraction=cfraction, pad=cpad, shrink=cshrink) c3.ax.tick_params(labelsize=cfontsize) ######################################## # ANIMATE SPIKES AND SYNAPTIC CHANGES if animate: # spike parameters raster = [None]*len(popinds); spikeColor = 'chartreuse'#'DarkMagenta'#'lime'#'purple' spikeSizeFactor = 1.5 maxframes = 1000 # Maximum number of non-movie frames binsize = 50 # Bin size in ms ncells = len(xlocs) xmax = round(xlocs.max()) ymax = round(xlocs.max()) tmax = spikeTime.max() totalspikes = len(spikeTime) nbins = int(tmax/binsize)+1 # Calculate number of bins; +1 for edge effects spikecounts=zeros((ncells,nbins)) # Number of spike counts timebins = array(range(nbins))*binsize/1e3 # Calculate time bins spikebins = array(spikeTime/binsize,dtype=int) # Convert times to bins for s in range(totalspikes): # Loop over each spike spikecounts[spikeId[s],spikebins[s]] += 1 # Increment this bin spikingrate = sum(spikecounts,axis=0)*1e3/binsize/ncells # Get the total spike counts over time maxspikes = 5*sum(spikecounts,axis=0).mean() # Find out the maximum number of spikes in any given timestep maxiters = int(min(maxframes,maxmovieframes,len(timebins))) if dosave else int(min(maxframes,len(timebins))) # See how many iterations to go for # plot spikes and syn changes for every frame for b in range(maxiters): # for each bin rasterMsubplot.set_title('Motor population, t = %0.3f s' % timebins[b], fontsize=12) rasterSsubplot.set_title('Somatosensory population, t = %0.3f s' % timebins[b], fontsize=12) rasterPsubplot.set_title('Proprioceptive population = %0.3f s' % timebins[b], fontsize=12) ############################# # show spikes if showSpikes: fired = array(spikecounts[:,b]>0).flatten() # Find which neurons fired in this timestep print(' bin = %i of %i; %i spikes' % (b, maxiters, sum(fired))) numfired = sum(fired) # Total number of cells that fired for p in range(len(popinds)): firedL = fired * (celltypes==popinds[p]) # calculate cells that fired for population p #print firedL if (p == 0): raster[p] = rasterPsubplot.scatter(xlocs[firedL], ylocs[firedL], c=spikeColor, marker=popshape[p], linewidth=cellBorder-1, s=cellSize*spikeSizeFactor) elif (p>=1 and p<=3): raster[p] = rasterSsubplot.scatter(xlocs[firedL], ylocs[firedL], c=spikeColor, marker=popshape[p], linewidth=cellBorder-1, s=cellSize*spikeSizeFactor) elif (p>=4 and p<=6): raster[p] = rasterMsubplot.scatter(xlocs[firedL], ylocs[firedL], c=spikeColor, marker=popshape[p], linewidth=cellBorder-1, s=cellSize*spikeSizeFactor) show() else: print(' bin = %i of %i' % (b, maxiters)) ############################ # show changes in synaptic weights synBin = where(syntime == b*binsize)[0] if (size(synBin)>0 and size(synBin)", 0)') h('nqsy.select("t","[]", %d, %d)'%(t1,t2)) h('synChanges = nqsy') synpreid=array(h.synChanges.getcol("id1"), 'i') synpostid=array(h.synChanges.getcol("id2"), 'i') synweight=array(h.synChanges.getcol("wg")) syntime=array(h.synChanges.getcol("t")) savetime=h.syDT prevWeight=synweight[syntime==t1] if t1<50: prevWeight=prevWeight[:len(prevWeight)/2] t1=2*savetime else: t1=t1+savetime synChanged=[0,0,0,0] bins=0 for t in arange(t1, syntime.max(), savetime): print t bins=bins+1 # get data for this time currsynpreid = synpreid[syntime==t] currsynpostid = synpostid[syntime==t] currsyntime = syntime[syntime==t] # find and save connections that have changed currWeight = synweight[syntime==t] diffWeight = currWeight-prevWeight changedWeight = where(diffWeight != 0)[0] # CHECK IF CAN CHANGE LINE BELOW TO AVOID FOR! #for i in range(len(changedWeight)): #synChanged = vstack((synChanged, [currsyntime[changedWeight[i]], currsynpreid[changedWeight[i]], currsynpostid[changedWeight[i]], diffWeight[changedWeight[i]]])) synChanged = vstack((synChanged, array([currsyntime[changedWeight], currsynpreid[changedWeight], currsynpostid[changedWeight], diffWeight[changedWeight]]).T)) prevWeight=currWeight scipy.io.savemat('arch3d/synChanged.mat', mdict={'synChanged': synChanged}) # Calculate average weight of all incoming connections (2nd order) to each EM muscle subpopulation over time # Useful to analyse the effect that RL has on the weights as a function of - WORK IN PROGRESS-- def synWeightsEM(): print "Calculating average weight to each EM muscle subpopulation" EMstart=256 # starting cell index of EM population EMlength=192 # number of EM cells EMsubpopo = [None]*4 for i in range(4): EMsubpop[i] = [arange(EMstart+i,EMstart+EMlength,4)] # create array with list of ids for each EM cell subpopulation popnames=['P','ES','IS','ILS','EM','IM','IML']; popinds=[ 2, 41, 42, 43, 44, 45, 46]; popshape=['o', '^', 'h', '*', '^', 'h', '*', '8']; # convert connectivity to python arrays conpreid=array(h.col.connsnq.getcol("id1"), 'i') conpostid=array(h.col.connsnq.getcol("id2"), 'i') #condelay=array(h.col.connsnq.getcol("del")) #condistance=array(h.col.connsnq.getcol("dist")) conweight1=array(h.col.connsnq.getcol("wt1")) conweight2=array(h.col.connsnq.getcol("wt2")) order = lexsort((conpreid, conpostid)) # order by post and then pre conpreid = conpreid[order] conpostid = conpostid[order] #condelay = condelay[order] #condistance = condistance[order] conweight1 = conweight1[order] conweight2 = conweight2[order] maxW = max(conweight1.max(), conweight2.max()) conweight1 = conweight1/maxW # normalize so can multiply together conweight2 = conweight2/maxW # convert synaptic changes over time (since connsnq doesn't change with t, can add) h('objref synChanges') #h('nqsy.tog()') h('nqsy.select("t",">=", 0)') h('synChanges = nqsy') synpreid=array(h.synChanges.getcol("id1"), 'i') synpostid=array(h.synChanges.getcol("id2"), 'i') synweight=array(h.synChanges.getcol("wg")) syntime=array(h.synChanges.getcol("t")) order = lexsort((synpreid, synpostid)) # order syn by post and then pre synpreid = synpreid[order] synpostid = synpostid[order] synweight=synweight[order] syntime=syntime[order] # define t tMax = syntime.max() tstep = 50 T = arange(0, tMax, tstep) # create array to store average weight change for each subpopulation weightSubpops = array((T.len(), 4)) def showRF(targetCells): onlyAMPA = 1 # find all cells projecting to the target cell for each layer afferentCells = array([], 'i') weightColors = [] for i in range(len(targetCells)): targetAfferents = array(conpreid[where(conpostid==targetCells[i])], 'i') # get afferent of next target cell if targetAfferents.any(): # if any for iAfferent in targetAfferents: # for each new afferent if (iAfferent in afferentCells): # check if already included in list if onlyAMPA: weightColors2 = (conweight1[targetCell2]) * (conweight1[iAfferent]) else: weightColors2 = (conweight1[targetCell2]) * (conweight1[iAfferent]) weightColors[afferentCells==iAfferent] += weightColors2 else: # if not included in list afferentCells=append(afferentCells, iAfferent) # add to list of afferent cells if onlyAMPA: weightColors = append(weightColors, conweight1[targetAfferents]); # calculate weigths else: weightColors = append(weightColors, conweight1[afferentCells]-conweight2[afferentCells]); # calculate weigths if nSyn2: # 2 synaptic connections for targetCell2 in targetAfferents: # loop through all afferent cells (which now become target cells) targetAfferents2 = array(conpreid[where(conpostid==targetCell2)], 'i') # get new set of afferent cells if targetAfferents2.any(): for iAfferent in targetAfferents2: # loop through all afferent cells if (iAfferent in afferentCells): # if already included in list if onlyAMPA: weightColors2 = (conweight1[targetCell2]) * (conweight1[iAfferent]) else: weightColors2 = (conweight1[targetCell2]) * (conweight1[iAfferent]) weightColors[afferentCells==iAfferent] += weightColors2 else: afferentCells=append(afferentCells, iAfferent) # add to list of afferent cells if onlyAMPA: weightColors2 = (conweight1[targetCell2]) * (conweight1[iAfferent]) else: weightColors2 = (conweight1[targetCell2]+conweight2[targetCell2]) * (conweight1[iAfferent]+conweight2[iAfferent]) weightColors=append(weightColors, weightColors2) #weightColors = weightColors/weightColors.max() # normalize weights to 1 weight = weightColors.sum() return weight for b in T: # calculate sum of weight for each subpopulation for i in range(4): targetCells = EMsubpop[i] weight=calculateRF(targetCells) # plot new RF weightSubpops[b, i] = weight # update weights synBin = where(syntime == b )[0] if (size(synBin)>0 and size(synBin)ES, Pshflex->ES) # One subplot for each layer/pop - 1) Pshflex->,Pshext->, ... 2) ES-> 3) IS, ISL, 4) EMshflex->, EMshext->, 5) IM, IML def popWeights(loadnqs=0, nqsfile = "", nqsdir="", nqsparams=[0,0,0,0,0,0,0], savefig=0, savenpy=0, loadnpy=0, animate=0, saveanim=0, tinterval=0): def index2d(myList, v): for i, x in enumerate(myList): if v in x: return (i) def calculateWeightMatrix(): print "calculating final weight matrix..." #weightMatrix = ndarray((sum(popslen), sum(popslen))) w, h = len(p), len(p) weightMatrix = [[0] * w for i in range(h)] onlyweight1 = 1 for i in range(len(synBin)): if (conweight1[i]>0):# || conweight2[i]>0): if onlyweight1: weightMatrix[index2d(subpops,conpreid[i])][index2d(subpops,conpostid[i])] += conweight1[i] else: weightMatrix[index2d(subpops,conpreid[i])][index2d(subpops,conpostid[i])] += conweight1[i] + conweight2[i] weightMatrix=array(weightMatrix) for i in range(len(subpops)): for j in range(len(subpops)): weightMatrix[i][j]=weightMatrix[i][j]/(len(subpops[i])*len(subpops[j])) return weightMatrix # alternative method under construction def calculateWeightMatrix2(): #weightMatrix = ndarray((sum(popslen), sum(popslen))) w, h = len(p), len(p) weightMatrix = [[0] * w for i in range(h)] onlyAMPA = 1 for pre in range(len(subpops)): for post in range(len(subpops)): indicespre=[] indicespost=[] for i in conpreid: indicespre.append(i in subpops[pre]) for i in conpostid: indicespost.append(i in subpops[post]) indices = indicespre * indicespost if (conweight1[i]>0):# || conweight2[i]>0): if onlyAMPA: weightMatrix[pre][post] += conweight1[indices].sum() else: weightMatrix[pre][post] += conweight1[indices].sum() + conweight2[indices].sum() return weightMatrix # visualization options figsize = [1000,800] # Figure size in pixels weightsCmap = 'hot_r'# 'jet'#'YlOrRd' #'jet'#'hot'#'autumn' # create figures ion() if animate: # only create figure 1 (evolution over time) if aniamte=1 fig = figure(figsize=(figsize[0]/100,figsize[1]/100),dpi=100) #fig.subplots_adjust(left=0.02) # Less space on left #fig.subplots_adjust(right=0.93) # Less space on right fig.subplots_adjust(bottom=0.08) # Less space on bottom subplot1 = subplot(221) # create subplots subplot2 = subplot(222) subplot3 = subplot(223) subplot4 = subplot(224) #border = 2 #weightplot.set_xlim([xlocs.min()-border, xlocs.max()+border]) # set x-y lims # cell populations parameters popslen = [192, 44, 20, 192, 44, 20,192] #popnames=['ES','IS','ILS','EM','IM','IML', 'P']; popinds=[41, 42, 43, 44, 45, 46, 2]; popshape=['o', '^', 'h', '*', '^', 'h', '*', '8']; # cell subpopulations (incuding muscle groups) subpops= [None]*13 p = {'Pse':0, 'Psf':1,'Pee':2,'P':3,'ES':4,'IS':5,'ILS':6,'EMse':7,'EMsf':8,'EMee':9,'EMef':10,'IM':11,'IML':12} p2 = {0:'Pse', 1:'Psf',2:'Pee',3:'Pef',4:'ES',5:'IS',6:'ILS',7:'EMse',8:'EMsf',9:'EMee',10:'EMef',11:'IM',12:'IML'} cellslist=[] # list of cells with muscle groups together popstart=0 index=0 for i in range(len(popslen)): popend = popstart+popslen[i] if i==3 or i==6: # for P and EM divide into 4 groups for j in range(4): subpops[index] = list(arange(popstart+j,popend,4)) # create array with list of ids for each cell subpopulation index+=1 else: subpops[index]=list(arange(popstart,popend)) index+=1 popstart+=popslen[i] # increase popstart # reorder to have P first neworder=[9,10,11,12,0,1,2,3,4,5,6,7,8] subpops = [ subpops[i] for i in neworder] # load data from neuron variables if (not loadnpy): wseedvals =[120456, 398115, 534031, 796321, 895199] # seed values for filename iseedvals = [1235, 2837, 3955, 4506, 6789] if loadnqs: # load data from nqs saved file print "loading data from nqs files..." # load connectivity file if (nqsfile !=""): outfilestem = '"%s-con.nqs"' % (nqsfile) filename = '%s-con.nqs' % (nqsfile) else: outfilestem = '"%s/p1-%.2f_p2-%.2f_p3-%.2f_p4-%.2f_p5-%d_i-%d_w-%d_test-con.nqs"' % (nqsdir, nqsparams[0], nqsparams[1], nqsparams[2], nqsparams[3], nqsparams[4], iseedvals[nqsparams[5]], wseedvals[nqsparams[6]]) filename = '%s/p1-%.2f_p2-%.2f_p3-%.2f_p4-%.2f_p5-%d_i-%d_w-%d_test-con.nqs' % (nqsdir, nqsparams[0], nqsparams[1], nqsparams[2], nqsparams[3], nqsparams[4], iseedvals[nqsparams[5]], wseedvals[nqsparams[6]]) if os.path.isfile(filename): print "loading "+outfilestem # get errors from nqs h('objref nqaload') h('nqaload = new NQS(%s)'%outfilestem) # convert connectivity to python arrays conpreid=array(h.nqaload.getcol("id1"), 'i') conpostid=array(h.nqaload.getcol("id2"), 'i') #condelay=array(h.col.connsnq.getcol("del")) #condistance=array(h.col.connsnq.getcol("dist")) conweight1=array(h.nqaload.getcol("wt1")) conweight2=array(h.nqaload.getcol("wt2")) # load weights file if (nqsfile != ""): outfilestem = '"%s-syn.nqs"' % (nqsfile) filename = '%s-syn.nqs' % (nqsfile) else: outfilestem = '"%s/p1-%.2f_p2-%.2f_p3-%.2f_p4-%.2f_p5-%d_i-%d_w-%d_test-syn.nqs"' % (nqsdir, nqsparams[0], nqsparams[1], nqsparams[2], nqsparams[3], nqsparams[4], iseedvals[nqsparams[5]], wseedvals[nqsparams[6]]) filename = '%s/p1-%.2f_p2-%.2f_p3-%.2f_p4-%.2f_p5-%d_i-%d_w-%d_test-syn.nqs' % (nqsdir, nqsparams[0], nqsparams[1], nqsparams[2], nqsparams[3], nqsparams[4], iseedvals[nqsparams[5]], wseedvals[nqsparams[6]]) if os.path.isfile(filename): print "loadding "+outfilestem # get errors from nqs h('objref nqaload2') h('nqaload2 = new NQS(%s)'%outfilestem) # convert connectivity to python arrays #h('objref synChanges') #h('nqaload2.select("t",">=", 0)') #h('synChanges = nqaload2') synpreid=array(h.nqaload2.getcol("id1"), 'i') synpostid=array(h.nqaload2.getcol("id2"), 'i') synweight=array(h.nqaload2.getcol("wg")) syntime=array(h.nqaload2.getcol("t")) else: # load from current simulation environment print "loading data from current sim..." # convert connectivity to python arrays conpreid=array(h.col.connsnq.getcol("id1"), 'i') conpostid=array(h.col.connsnq.getcol("id2"), 'i') #condelay=array(h.col.connsnq.getcol("del")) #condistance=array(h.col.connsnq.getcol("dist")) conweight1=array(h.col.connsnq.getcol("wt1")) conweight2=array(h.col.connsnq.getcol("wt2")) h('objref synChanges') h('nqsy.select("t",">=", 0)') h('synChanges = nqsy') synpreid=array(h.synChanges.getcol("id1"), 'i') synpostid=array(h.synChanges.getcol("id2"), 'i') synweight=array(h.synChanges.getcol("wg")) syntime=array(h.synChanges.getcol("t")) if 'conpreid' in locals(): order = lexsort((conpostid, conpreid)) # order by post and then pre #condelay = condelay[order] #condistance = condistance[order] conpreid = conpreid[order] conpostid = conpostid[order] conweight1 = conweight1[order] conweight2 = conweight2[order] # normalize conweight1 and conweight2 separately #maxW = max(conweight1.max(), conweight2.max()) #conweight1 = conweight1/maxW # normalize so can multiply together #conweight2 = conweight2/maxW #conweight1Original = deepcopy(conweight1) # make copy of weights at t=0 # sum conweight1+conweight2 and normalize conweight = conweight1+conweight2 conweightOriginal = conweight / max(conweight) # convert synaptic changes over time (since connsnq doesn't change with t, can add) #synpreid=synpreid[0:len(conpreid)] order = lexsort((synpostid, synpreid, syntime)) # order syn by post and then pre synpreid = synpreid[order] synpostid = synpostid[order] synweight=synweight[order] syntime=syntime[order] else: print "Coulndn't load file: "+outfilestem fig2 = figure(figsize=(figsize[0]/100,figsize[1]/100),dpi=100) fontsiz=14 matrixsubplot = subplot(111) matrixsubplot.set_xlabel('postsynaptic population',fontsize=fontsiz) matrixsubplot.set_ylabel('presynaptic population',fontsize=fontsiz) # plot static weight matrix - use last set of weights if (not animate): if loadnpy: weightMatrix=np.load('weightMatrix.npy') else: # load last set of weights synBin = where(syntime == syntime.max())[0] if (size(synBin)>0 and size(synBin)0 and size(synBin) ES (4); IS (5)->ES (4); IM (11)->EM x4 (7:10) total: 9 subplot1.set_title('P->ES, IS->ES, IM->EM', fontsize=12) # titles icolor=0 for pre in arange(0,4): for post in arange(4,5): subplot1.plot(T,weightMatrixT[:, pre, post], colorlist[icolor], label=str(p2[pre])+'->'+str(p2[post])) icolor+=1 for pre in arange(5,6): for post in arange(4,5): subplot1.plot(T,weightMatrixT[:, pre, post], colorlist[icolor], label=str(p2[pre])+'->'+str(p2[post])) icolor+=1 for pre in arange(11,12): for post in arange(7,11): subplot1.plot(T,weightMatrixT[:, pre, post], colorlist[icolor], label=str(p2[pre])+'->'+str(p2[post])) icolor+=1 subplot1.legend(loc='upper right', bbox_to_anchor=(legendx, legendy), borderaxespad=0., prop={'size':legendfontsize}) subplot1.set_ylabel(ylabel) subplot1.set_xlabel(xlabel) subplot1.grid(True) # ES (4)-> ES, EMx4, IS, ISL (4:10) total: 8 subplot2.set_title('ES', fontsize=12) icolor=0 for pre in arange(4,5): for post in arange(4,11): subplot2.plot(T,weightMatrixT[:, pre, post], colorlist[icolor], label=str(p2[pre])+'->'+str(p2[post])) icolor+=1 subplot2.legend(loc='upper right', bbox_to_anchor=(legendx, legendy), borderaxespad=0., prop={'size':legendfontsize}) subplot2.set_ylabel(ylabel) subplot2.set_xlabel(xlabel) subplot2.grid(True) # EMx4 (7:10)-> EMx4 (7:10) total:16 (use dotted vs line)) subplot3.set_title('EM recurrent', fontsize=12) icolor=0 linesty='-' for pre in arange(7,11): for post in arange(7,11): subplot3.plot(T,weightMatrixT[:, pre, post], colorlist[icolor], linestyle = linesty, label=str(p2[pre])+'->'+str(p2[post])) icolor+=1 if icolor>7: icolor=0 linesty='--' subplot3.legend(loc='upper right', bbox_to_anchor=(legendx, legendy), borderaxespad=0., prop={'size':legendfontsize}) subplot3.set_ylabel(ylabel) subplot3.set_xlabel(xlabel) subplot3.grid(True) # EMx4 (7:10)-> ES, IM, IML (3, 11:12) total:12 subplot4.set_title('EM', fontsize=12) icolor=0 linesty='-' for pre in arange(7,11): for post in (4,11,12): subplot4.plot(T,weightMatrixT[:, pre, post], colorlist[icolor], linestyle = linesty, label=str(p2[pre])+'->'+str(p2[post])) icolor+=1 if icolor>5: icolor=0 linesty='--' subplot4.legend(loc='upper right', bbox_to_anchor=(legendx, legendy), borderaxespad=0., prop={'size':legendfontsize}) subplot4.set_ylabel(ylabel) subplot4.set_xlabel(xlabel) subplot4.grid(True) show() # call popWeight to plot the weights of the 4 different targets in a specific sim (with specific params) def popWeights4Targ(nqsdir, nqsparams=[0,0,0,0], savefig=0): for i in range(4): popWeights(1, nqsdir, [nqsparams[0],nqsparams[1],nqsparams[2],nqsparams[3],i, 0,0], savefig) # Compare population weights for each target after training def popMuscles(nqsdir="", plotfig = 0, savefig = 0, save2Matlab = 1): def index2d(myList, v): for i, x in enumerate(myList): if v in x: return (i) def calculateWeightMatrix(): print "calculating final weight matrix..." #weightMatrix = ndarray((sum(popslen), sum(popslen))) w, h = len(p), len(p) weightMatrix = [[0] * w for i in range(h)] onlyweight1 = 1 for i in range(len(synBin)): if (conweight1[i]>0):# || conweight2[i]>0): if onlyweight1: weightMatrix[index2d(subpops,conpreid[i])][index2d(subpops,conpostid[i])] += conweight1[i] else: weightMatrix[index2d(subpops,conpreid[i])][index2d(subpops,conpostid[i])] += conweight1[i] + conweight2[i] weightMatrix=array(weightMatrix) for i in range(len(subpops)): for j in range(len(subpops)): weightMatrix[i][j]=weightMatrix[i][j]/(len(subpops[i])*len(subpops[j])) return weightMatrix # visualization options figsize = [1000,800] # Figure size in pixels weightsCmap = 'hot_r'# 'jet'#'YlOrRd' #'jet'#'hot'#'autumn' # create figures ion() # cell populations parameters popslen = [192, 44, 20, 192, 44, 20,192] #popnames=['ES','IS','ILS','EM','IM','IML', 'P']; popinds=[41, 42, 43, 44, 45, 46, 2]; popshape=['o', '^', 'h', '*', '^', 'h', '*', '8']; # cell subpopulations (incuding muscle groups) subpops= [None]*13 p = {'Pse':0, 'Psf':1,'Pee':2,'P':3,'ES':4,'IS':5,'ILS':6,'EMse':7,'EMsf':8,'EMee':9,'EMef':10,'IM':11,'IML':12} p2 = {0:'Pse', 1:'Psf',2:'Pee',3:'Pef',4:'ES',5:'IS',6:'ILS',7:'EMse',8:'EMsf',9:'EMee',10:'EMef',11:'IM',12:'IML'} cellslist=[] # list of cells with muscle groups together popstart=0 index=0 for i in range(len(popslen)): popend = popstart+popslen[i] if i==3 or i==6: # for P and EM divide into 4 groups for j in range(4): subpops[index] = list(arange(popstart+j,popend,4)) # create array with list of ids for each cell subpopulation index+=1 else: subpops[index]=list(arange(popstart,popend)) index+=1 popstart+=popslen[i] # increase popstart # reorder to have P first neworder=[9,10,11,12,0,1,2,3,4,5,6,7,8] subpops = [ subpops[i] for i in neworder] # load data from neuron variables wseedvals =[120456, 398115, 534031, 796321, 895199] # seed values for filename iseedvals = [1235, 1235+(2*17),2837, 3955, 4506, 6789] print "loading data from nqs files..." # load connectivity file targets=[0,1,2,3] loaded = 0 for itarget in targets: iseedval = iseedvals[0] for wseedval in wseedvals: loaded = 0 outfilestem = '"%s/target-%d_i-%d_w-%d_train-con.nqs"' % (nqsdir, itarget, iseedval, wseedval) filename = '%s/target-%d_i-%d_w-%d_train-con.nqs' % (nqsdir,itarget, iseedval, wseedval) if os.path.isfile(filename): print "loading "+outfilestem # get errors from nqs h('objref nqaload') h('nqaload = new NQS(%s)'%outfilestem) # convert connectivity to python arrays conpreid=array(h.nqaload.getcol("id1"), 'i') conpostid=array(h.nqaload.getcol("id2"), 'i') #condelay=array(h.col.connsnq.getcol("del")) #condistance=array(h.col.connsnq.getcol("dist")) conweight1=array(h.nqaload.getcol("wt1")) conweight2=array(h.nqaload.getcol("wt2")) loaded += 1 # load weights file outfilestem = '"%s/target-%d_i-%d_w-%d_train-syn.nqs"' % (nqsdir, itarget, iseedval, wseedval) filename = '%s/target-%d_i-%d_w-%d_train-syn.nqs' % (nqsdir, itarget, iseedval, wseedval) if os.path.isfile(filename): print "loading "+outfilestem # get errors from nqs h('objref nqaload2') h('nqaload2 = new NQS(%s)'%outfilestem) # convert connectivity to python arrays #h('objref synChanges') #h('nqaload2.select("t",">=", 0)') #h('synChanges = nqaload2') synpreid=array(h.nqaload2.getcol("id1"), 'i') synpostid=array(h.nqaload2.getcol("id2"), 'i') synweight=array(h.nqaload2.getcol("wg")) syntime=array(h.nqaload2.getcol("t")) loaded += 1 if loaded == 2: #'conpreid' in locals(): order = lexsort((conpostid, conpreid)) # order by post and then pre #condelay = condelay[order] #condistance = condistance[order] conpreid = conpreid[order] conpostid = conpostid[order] conweight1 = conweight1[order] conweight2 = conweight2[order] # normalize conweight1 and conweight2 separately #maxW = max(conweight1.max(), conweight2.max()) #conweight1 = conweight1/maxW # normalize so can multiply together #conweight2 = conweight2/maxW #conweight1Original = deepcopy(conweight1) # make copy of weights at t=0 # sum conweight1+conweight2 and normalize conweight = conweight1+conweight2 conweightOriginal = conweight / max(conweight) # convert synaptic changes over time (since connsnq doesn't change with t, can add) #synpreid=synpreid[0:len(conpreid)] order = lexsort((synpostid, synpreid, syntime)) # order syn by post and then pre synpreid = synpreid[order] synpostid = synpostid[order] synweight=synweight[order] syntime=syntime[order] if plotfig: fig2 = figure(figsize=(figsize[0]/100,figsize[1]/100),dpi=100) fontsiz=14 matrixsubplot = subplot(111) matrixsubplot.set_xlabel('postsynaptic population',fontsize=fontsiz) matrixsubplot.set_ylabel('presynaptic population',fontsize=fontsiz) # plot static weight matrix - use last set of weights # load last set of weights synBin = where(syntime == syntime.max())[0] if (size(synBin)>0 and size(synBin)>size(conweight1)): synBin = synBin[0:(len(synBin)/2)-1] #synBin = where(syntime == 4000)[0] if (size(synBin)>0 and size(synBin)=", 0)') h('synChanges = nqsy') synpreid=array(h.synChanges.getcol("id1"), 'i') synpostid=array(h.synChanges.getcol("id2"), 'i') synweight=array(h.synChanges.getcol("wg")) syntime=array(h.synChanges.getcol("t")) order = lexsort((synpreid, synpostid)) # order syn by post and then pre synpreid = synpreid[order] synpostid = synpostid[order] synweight=synweight[order] syntime=syntime[order] def calculateWeightMatrix(): #weightMatrix = ndarray((sum(popslen), sum(popslen))) w, h = sum(popslen), sum(popslen) weightMatrix = [[0] * w for i in range(h)] onlyAMPA = 0 for i in range(len(conweight1)): if onlyAMPA: weightMatrix[conpreid[i]][conpostid[i]] = conweight1[i] else: weightMatrix[conpreid[i]][conpostid[i]] = conweight1[i] + conweight2[i] #weightMatrix = [ mylist[i] for i in myorder] # reorder weightMatrix2=deepcopy(weightMatrix) for i,sublist in enumerate(weightMatrix): weightMatrix2[i]=[sublist[j] for j in cellslist] #reorder rows weightMatrix2=[weightMatrix2[j] for j in cellslist] # reorder columns weightMatrix2=array(weightMatrix2) return weightMatrix2 # calculate sum of weight for each subpopulation weightMatrix=calculateWeightMatrix() # plot new RF # plot 2dmap im=weightplot.imshow(weightMatrix, cmap=weightsCmap) #im=imshow(weightMatrix, cmap=weightsCmap) weightplot.axis([0, sum(popslen), 0,sum(popslen)]) # set the limits of the plot to the limits of the data c=colorbar(im, ax=weightplot)#, fraction=0.09,pad=0.01) show() #fig.tight_layout() if animate: # define t tMax = syntime.max() tstep = tinterval T = arange(0, tMax, tstep) for b in T: # calculate sum of weight for each subpopulation weightMatrix=calculateWeightMatrix() # plot new RF #plot 2dmap , save and wait ; make video im=weightplot.imshow(weightMatrix, cmap=weightsCmap, vmin=0, vmax=1.5) #im=imshow(weightMatrix, cmap=weightsCmap, vmin=0, vmax=1.5) #plt.imshow(z) #plt.pcolor(Z) show() #fig.tight_layout() if dosave: fig.savefig('tmpmovie%04i.png' % b) # Save PNG files for movie if dosave!=1: pause(1e-10) # update weights synBin = where(syntime == b )[0] if (size(synBin)>0 and size(synBin)1: i = top # call runpbatchpbs to run sims saving muscle, weight and LFP data command = 'python runbatchpbs_iseeds_16params.py %s_best data/%s_island_%s/gen_%s_cand_%s %d 0 -1' % (folder,folder,all_islands[i], all_gens[i], all_cands[i], iseeds) print command os.system(command) print 'Sleeping for 10 mins to wait for results...' time.sleep(100) # for each of the top solutions run sim to get data if top > 1 and iseeds == 1: total_jobs = top converted = [None]*total_jobs num_iters = 0 jobs_completed=0 while jobs_completed < total_jobs: print str(num_iters)+" iterations, "+str(jobs_completed)+" / "+str(total_jobs)+" jobs completed" unfinished = [i for i, x in enumerate(converted) if x is None] print "unfinished:" + str(unfinished) for i in unfinished: # check if file exists subfolder = 'island_%s_gen_%s_cand_%s' % (all_islands[i], all_gens[i], all_cands[i]) simdatadir = 'data/%s/%s' % (folder+'_best', subfolder) for iseed in iseedvals: for wseed in wseedvals: try: for itarget in range(4): filename = '%s/target-%d_i-%d_w-%d_test-nqa.nqs' % (simdatadir, itarget, iseed, wseed) with open(filename) as f: print 'Reading file: ' + f.name save2Matlab_iseeds(simdatadir, 20, 1000) save2MatlabEMGs(simdatadir) if calculateWeights: popMuscles(simdatadir) converted[i] = 1 jobs_completed+=1 except: #print 'Not found: '+filename pass num_iters += 1 if num_iters >= timeout: print "max iterations reached without completing all jobs" for j in unfinished: converted[j] = 2 jobs_completed += 1 time.sleep(30) # for each of the iseeds -- NEEDS FIXING, SOMETIMES NOT ALL .MAT FILES ARE GENERATED elif top >= 1 and iseeds > 1: total_jobs = iseeds converted = [None]*total_jobs num_iters = 0 jobs_completed=0 while jobs_completed < total_jobs: print str(num_iters)+" iterations, "+str(jobs_completed)+" / "+str(total_jobs)+" jobs completed" unfinished = [i for i, x in enumerate(converted) if x is None] print "unfinished:" + str(unfinished) isol = top # top solution only # check if file exists subfolder = 'island_%s_gen_%s_cand_%s' % (all_islands[isol], all_gens[isol], all_cands[isol]) simdatadir = 'data/%s/%s' % (folder+'_best', subfolder) for iseed,iseedval in enumerate(iseedvals): for wseed in wseedvals: try: for itarget in range(4): filename = '%s/target-%d_i-%d_w-%d_test-nqa.nqs' % (simdatadir, itarget, iseedval, wseed) with open(filename) as f: print 'Reading file: ' + f.name converted[iseed] = 1 jobs_completed+=1 except: #print 'Not found: '+filename pass num_iters += 1 if num_iters >= timeout: print "max iterations reached without completing all jobs" for j in unfinished: converted[j] = 2 jobs_completed += 1 time.sleep(30) # after all iseeds have finished - convert all together save2Matlab_iseeds(simdatadir, 20, 1000) save2MatlabEMGs(simdatadir) if calculateWeights: popMuscles(simdatadir) else: print "Have to choose either top>1 and iseeds=1 or top=1 and iseeds>1" # Script code (run always) # # Load default parameters and initialize the network. # COMMENT OUT WHEN RUNNING SIM.PY !!! #h.xopen("/usr/site/nrniv/simctrl/hoc/setup.hoc") #h.xopen("/usr/site/nrniv/simctrl/hoc/nrnoc.hoc") #h.load_file("syncode.hoc") #h.load_file("decnqs.hoc") #h.load_file("analysis.hoc") #bestFitness('14dec18_evol')