AnimatLab  2
Test
snn_helper.cpp
1 /*
2  * Copyright (c) 2013 Regents of the University of California. All rights reserved.
3  *
4  * Redistribution and use in source and binary forms, with or without
5  * modification, are permitted provided that the following conditions
6  * are met:
7  *
8  * 1. Redistributions of source code must retain the above copyright
9  * notice, this list of conditions and the following disclaimer.
10  *
11  * 2. Redistributions in binary form must reproduce the above copyright
12  * notice, this list of conditions and the following disclaimer in the
13  * documentation and/or other materials provided with the distribution.
14  *
15  * 3. The names of its contributors may not be used to endorse or promote
16  * products derived from this software without specific prior written
17  * permission.
18  *
19  * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
20  * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
21  * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
22  * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
23  * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
24  * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
25  * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
26  * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
27  * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
28  * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
29  * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
30  *
31  * *********************************************************************************************** *
32  * CARLsim
33  * created by: (MDR) Micah Richert, (JN) Jayram M. Nageswaran
34  * maintained by: (MA) Mike Avery <averym@uci.edu>, (MB) Michael Beyeler <mbeyeler@uci.edu>,
35  * (KDC) Kristofor Carlson <kdcarlso@uci.edu>
36  *
37  * CARLsim available from http://socsci.uci.edu/~jkrichma/CARLsim/
38  * Ver 07/13/2013
39  */
40 
41 #include "snn.h"
42 
43 #include <opencv/cv.h>
44 #include <opencv/highgui.h>
45 using namespace cv;
46 
47 
48 int cvKeyCheck()
49 {
50  // wait for a key
51  keyVal = cvWaitKey(10);
52 // if(keyVal != -1) {
53 // fprintf(stderr, "keyVal = %c %d %d %d \n", (char) keyVal, keyVal, (int) 'p', (int) 's', (int) 'q');
54 // cvWaitKey(0);
55 // }
56  if ((char) keyVal == 'p') {
57  fprintf(stderr, "Pause key pressed ! Press any to continue\n");
58  rasterPlotAll(10, false);
59  cvWaitKey(0);
60  }
61  else if( (char) keyVal == 's') {
62  //saveConnectionWeights();
63  rasterPlotAll(10, false);
64  cvWaitKey(0);
65  }
66  else if( (char) keyVal == 'q') {
67  cvWaitKey(0);
68  exitSimulation(0);
69  }
70  else if( (char) keyVal == 'b') {
71  return keyVal;
72  }
73  else if( (char) keyVal == 'n') {
74  return keyVal;
75  }
76 }
77 
78 
80  public:
82  static int winCounter;
83  winID = winCounter++;
84 
85  CvMat* imgWin;
86  bool firstDisplay;
87  int offset;
88  int maxSize;
89  int yScale;
90  int xPos;
91  int yPos;
92  int winID;
93  char winName[100];
94 };
95 
96 
97 void spikeRaster(CpuSNN* s, int grpId, unsigned int* Nids, unsigned int* timeCnts, spikeRaster_t* sR)
98 {
99  group_info2_t gInfo2 = s->getGroupInfo2(gid);
100 
101  cvNamedWindow(sR->winName);
102  if(sR->firstDisplay) {
103  cvMoveWindow(sR->winName, sR->xPos, sR->yPos);
104 
105  sR->imgWin = cvCreateMat(160, 160, CV_8UC1);
106  }
107  sR->firstDisplay = false;
108 
109  CvMat* imgWin = sR->imgWin;
110 
111  cvSetZero(imgWin);
112  int pos = 0;
113  for (int t=0; t < 1000; t++) {
114  for(int i=0; i<timeCnts[t];i++,pos++) {
115  int id = Nids[pos];
116  assert(id <= grp_Info[gid].EndN);
117  assert(id >= grp_Info[gid].StartN);
118  int val = id-grp_Info[gid].StartN-sR->offset;
119  if( (val < sR->maxSize) && (val >= 0)) {
120 
121  if ( sR->yScale < 2) {
122  if( (sR->maxSize+10-val) < MAX_CV_WINDOW_PIXELS) {
123  *((uchar*)CV_MAT_ELEM_PTR( *imgWin, sR->maxSize+10-val, t/2)) = 255.0;
124  }
125  }
126  else {
127  if ( sR->maxSize+10-val*sR->yScale < MAX_CV_WINDOW_PIXELS) {
128  *((uchar*)CV_MAT_ELEM_PTR( *imgWin, sR->maxSize+10-val*sR->yScale, t/2)) = 255.0;
129  *((uchar*)CV_MAT_ELEM_PTR( *imgWin, sR->maxSize+10-1-val*sR->yScale, t/2)) = 255.0;
130  *((uchar*)CV_MAT_ELEM_PTR( *imgWin, sR->maxSize+10-val*sR->yScale, 1+t/2)) = 255.0;
131  *((uchar*)CV_MAT_ELEM_PTR( *imgWin, sR->maxSize+10-1-val*sR->yScale, 1+t/2)) = 255.0;
132  }
133  }
134  }
135  }
136  }
137 
138  cvShowImage(winName, imgWin);
139 }
140 
141 
142 /*
143 
144 
145  int showInputPattern(GaborFilter* gb, int radius, float angle, bool showImage, bool firstDisplay)
146  {
147  static CvMat* imgWin = cvCreateMat(160, 160, CV_8UC1);
148  char winName[]="mainWin";
149 
150  int factor=1;
151  //float angle = angles[(int)((sizeof(angles)/4)*drand48())]; //45.0;// = atof(argv[2]);
152  float freq = 1/10.0; //0.1105/factor; // atof(argv[3]);
153  float bw = 1.0; // atof(argv[4]);
154  float phase = 0.0; // atof(argv[5]);
155  float rho = 1.5; //atof(argv[6]);
156  float sig = 2*factor;
157 
158  gb->GenerateFilter(radius, angle, freq, sig, phase, bw, rho);
159 
160  CvMat* img = gb->GetPixel();
161 
162  if((!showImage) && (!firstDisplay))
163  return 0;
164 
165  // create a window
166  cvNamedWindow(winName);//, CV_WINDOW_AUTOSIZE);
167  if(firstDisplay)
168  cvMoveWindow("mainWin", 300, 500);
169 
170  cvResize(img, imgWin);
171 
172  cvShowImage(winName, imgWin);
173 
174  return 0;
175  }
176 
177  void CpuSNN::getScaledWeights(void* imgPtr, int nid, int src_grp, int repx, int repy)
178  {
179  if(!plotUsingOpenCV)
180  return;
181 
182  CvMat* img = (CvMat*) imgPtr;
183  cvSetZero(img);
184  int dest_grp=findGrpId(nid);
185  post_info_t* preIds = &preSynapticIds[cumulativePre[nid]];
186  int cols = img->cols;
187  int rows = img->rows;
188  float* synWts = &wt[cumulativePre[nid]];
189  // find a suitable match for each pre-syn id that we are interested in ..
190  float maxWt = grpConnInfo[src_grp][dest_grp]->maxWt;
191  for(int i=0; i < Npre[nid]; i++, preIds++, synWts++) {
192  //int preId = (*preIds) & POST_SYN_NEURON_MASK;
193  int preId = GET_CONN_NEURON_ID((*preIds));
194  assert(preId < (numN));
195  // preId matches the src_grp that we are interested..
196  if(src_grp == findGrpId(preId)) {
197  int imgId = preId - grp_Info[src_grp].StartN;
198  assert((imgId*repx*repy) < (cols*rows));
199  int xpt = imgId%(cols/repx);
200  int ypt = imgId/(cols/repx);
201  for(int p=0; p < repy; p++)
202  for(int q=0; q < repx; q++) {
203  *((uchar*)CV_MAT_ELEM_PTR( *img, repy*ypt+p, repx*xpt+q)) = (uchar) ((255.0*(*synWts))/maxWt);
204  }
205  }
206  }
207  }
208 
209  void CpuSNN::getScaledWeights1D(void* imgPtr, unsigned int nid, int src_grp, int repx, int repy)
210  {
211  char fname[100];
212  sprintf(fname, "weightsSrc%dDest%d.txt", src_grp, nid);
213  //FILE *fp = fopen(fname, "w");
214  //if(fp == NULL)
215 
216  if(!plotUsingOpenCV)
217  return;
218 
219  CvMat* img = (CvMat*) imgPtr;
220  cvSetZero(img);
221 
222  int dest_grp = findGrpId(nid);
223  post_info_t* preIds = &preSynapticIds[cumulativePre[nid]];
224 
225  // find a suitable match for each pre-syn id that we are interested in ..
226  float maxWt = grpConnInfo[src_grp][dest_grp]->maxWt;
227  int cols = img->cols;
228  float rowFactor = (img->rows-8)/(repy*maxWt);
229  float* synWts = &wt[cumulativePre[nid]];
230  float* synWtChange = &wtChange[cumulativePre[nid]];
231 
232  if(currentMode == GPU_MODE) {
233  copyWeightsGPU(nid, src_grp);
234  }
235 
236  //fprintf(stderr, "%d => %d : ", src_grp, nid);
237  for(int i=0; i < Npre[nid]; i++, preIds++, synWts++, synWtChange++) {
238  int preId = GET_CONN_NEURON_ID((*preIds));
239  //int preId = (*preIds) & POST_SYN_NEURON_MASK;
240  assert(preId < (numN));
241  // preId matches the src_grp that we are interested..
242  if( src_grp == findGrpId(preId)) {
243  int imgId = preId - grp_Info[src_grp].StartN;
244  assert((imgId*repx) < cols);
245  int xpt = imgId;
246  if (*synWts > maxWt) {
247  fprintf(stderr, "Maximum synaptic weight (%f) exceeded for this Weight (%f)...\n", maxWt, *synWts);
248  assert (*synWts <= maxWt);
249  }
250  int ypt = (uchar)(rowFactor*(*synWts));
251  //fprintf(stderr, "[%d] %f (%f) ", preId, *synWts, *synWtChange);
252  for(int p=0; p < repy; p++)
253  for(int q=0; q < repx; q++) {
254  *((uchar*)CV_MAT_ELEM_PTR( *img, img->rows - 1 -(4+repy*ypt+p), repx*xpt+q )) = 255.0;
255  }
256  }
257  }
258  //fprintf(stderr, "\n");
259  }
260 
261  void CpuSNN::getScaledWeightRates1D(unsigned int nid, int src_grp)
262  {
263  // find a suitable match for each pre-syn id that we are interested in ..
264  int dest_grp = findGrpId(nid);
265  float maxWt = grpConnInfo[src_grp][dest_grp]->maxWt;
266  char fname[100];
267  sprintf(fname, "weightRatesSrc%dDest%d.txt(max=%3.3f)", src_grp, nid, maxWt);
268 
269  post_info_t* preIds = &preSynapticIds[cumulativePre[nid]];
270 
271  float* synWts = &wtChange[cumulativePre[nid]];
272  fprintf(stderr, "wtChange: %d => %d : ", src_grp, nid);
273  for(int i=0; i < Npre[nid]; i++, preIds++, synWts++) {
274  //int preId = (*preIds) & POST_SYN_NEURON_MASK;
275  int preId = GET_CONN_NEURON_ID((*preIds));
276  assert(preId < (numN));
277  // preId matches the src_grp that we are interested..
278  if( src_grp == findGrpId(preId)) {
279  fprintf(stderr, "%d:%f ", preId, *synWts);
280  }
281  }
282 
283  fprintf(stderr, "\n");
284  //fclose(fp);
285  }
286 
287  void CpuSNN::showWeightRatePattern1D (int destGrp, int srcGrp)
288  {
289 
290  checkNetworkBuilt();
291 
292  if(grpConnInfo[srcGrp][destGrp]==NULL) {
293  fprintf(stderr, "showWeightPattern1D failed\n");
294  fprintf(stderr, "No connections exists between %s(%d) to %s(%d)\n", grp_Info2[srcGrp].Name.c_str(), srcGrp, grp_Info2[destGrp].Name.c_str(), destGrp);
295  return;
296  }
297 
298  //char winName[100];
299  //int wtImgSizeX = 2*grp_Info[srcGrp].SizeN;
300  //int wtImgSizeY = 128;
301  //int repSize = 2;
302  //static CvMat* wtImg = cvCreateMat(wtImgSizeY, wtImgSizeX, CV_8UC1);
303 
304  for(int k=0, n = grp_Info[destGrp].StartN; n <= grp_Info[destGrp].EndN; n++,k++)
305  {
306  //sprintf(winName, "weightRateNeuron%d%d", srcGrp, n);
307  //cvNamedWindow(winName, CV_WINDOW_AUTOSIZE);
308  //if(firstDisplay)
309  //cvMoveWindow(winName, col+0*(wtImg->cols+40), row+k*(wtImg->rows+40));
310  //getScaledWeightRates1D((void*)wtImg, n, srcGrp, repSize, repSize);
311  getScaledWeightRates1D(n, srcGrp);
312  //cvShowImage(winName, wtImg );
313  }
314  }
315 
316  void CpuSNN::showWeightPattern1D(int destGrp, int srcGrp, int row, int col)
317  {
318  checkNetworkBuilt();
319 
320  if(!plotUsingOpenCV)
321  return;
322 
323  if(grpConnInfo[srcGrp][destGrp]==NULL) {
324  fprintf(stderr, "showWeightPattern1D cannot proceed\n");
325  fprintf(stderr, "No connections exists between %s(%d) to %s(%d)\n", grp_Info2[srcGrp].Name.c_str(), srcGrp, grp_Info2[destGrp].Name.c_str(), destGrp);
326  return;
327  }
328 
329  char winName[100];
330  int wtImgSizeX = 2*grp_Info[srcGrp].SizeN;
331  int wtImgSizeY = 128;
332  int repSize = 2;
333  static CvMat* wtImg = cvCreateMat(wtImgSizeY, wtImgSizeX, CV_8UC1);
334 
335  for(int k=0, n = grp_Info[destGrp].StartN; n <= grp_Info[destGrp].EndN; n++,k++)
336  {
337  sprintf(winName, "g=%d:%dweightNeuron1D", srcGrp, n);
338  cvNamedWindow(winName, CV_WINDOW_AUTOSIZE);
339  if(firstDisplay)
340  cvMoveWindow(winName, col, row+k*(wtImg->rows+30));
341  getScaledWeights1D((void*)wtImg, n, srcGrp, repSize, repSize);
342  cvShowImage(winName, wtImg );
343  }
344  }
345 
346  void CpuSNN::showWeightPattern (int destGrp, int srcGrp, int row, int col, int size)
347  {
348  checkNetworkBuilt();
349 
350  if(!plotUsingOpenCV)
351  return;
352 
353  if(grpConnInfo[srcGrp][destGrp]==NULL) {
354  fprintf(stderr, "showWeightPattern1D failed\n");
355  fprintf(stderr, "No connections exists between %s(%d) to %s(%d)\n", grp_Info2[srcGrp].Name.c_str(), srcGrp, grp_Info2[destGrp].Name.c_str(), destGrp);
356  return;
357  }
358 
359  int wtImgSize = 160;
360  static CvMat* wtImg = cvCreateMat(wtImgSize, wtImgSize, CV_8UC1);
361  int repSize = (wtImgSize/size);
362 
363  char winName[100];
364 
365  for(int k=0, n = grp_Info[destGrp].StartN; n <= grp_Info[destGrp].EndN; n++,k++)
366  {
367  sprintf(winName, "g=%d:id=%dweightNeuron", srcGrp, n);
368  cvNamedWindow(winName, CV_WINDOW_AUTOSIZE);
369  if(firstDisplay)
370  cvMoveWindow(winName, col+0*(wtImg->cols+40), row+k*(wtImg->rows+40));
371  getScaledWeights((void*)wtImg, n, srcGrp, repSize, repSize);
372  cvShowImage(winName, wtImg );
373  }
374  }
375 
376  void CpuSNN::rasterPlot(int gid, const string& fname, int row, int col, bool dontOverWrite)
377  {
378  DBG(2, fpLog, AT, "rasterPlot() called");
379 
380  FILE* fpDumpFile = getRasterFilePointer(fname, dontOverWrite);
381 
382  // no we got the file pointer.. go and dump
383  // if fp=null, the GPU will atleast update
384  // the CVMat array with spike info to be displayed later.
385  // if fp=null, then the CPU will mostly just return without
386  // dumping the spike information to the file...
387  dumpSpikeBuffToFile(fpDumpFile, gid);
388 
389  // enable plotting..
390  if(plotUsingOpenCV) {
391  if (gid==-1) {
392  for (int i=0; i < numSpikeMonitor; i++) {
393  int gid = monGrpId[i];
394  plotSpikeBuff(gid, row, col);
395  }
396  }
397  else
398  plotSpikeBuff(gid, row, col);
399  }
400  }
401 
402  void CpuSNN::plotBuffInit(int gid)
403  {
404  DBG(2, fpLog, AT, "plotBufInit()");
405  int monId = grp_Info[gid].MonitorId;
406  if(monId == -1) {
407  fprintf(stderr, "RasterPlot(gid=%d) failed... Group %s not monitored..\n", gid, grp_Info2[gid].Name.c_str());
408  fprintf(stderr, "call spikeMonitor(gid=%d) function in your code to ensure monitoring of group %s\n", gid, grp_Info2[gid].Name.c_str());
409  return;
410  }
411 
412  int maxSize = (grp_Info[gid].SizeN);
413  maxSize = (maxSize >= MAX_CV_WINDOW_PIXELS) ? MAX_CV_WINDOW_PIXELS : maxSize;
414  maxSize = (maxSize < MIN_CV_WINDOW_PIXELS) ? MIN_CV_WINDOW_PIXELS : maxSize;
415  int yscale = maxSize/grp_Info[gid].SizeN;
416 
417  CvMat* imgWin = cvCreateMat(maxSize+20, 501, CV_8UC1);
418  assert((gid >= 0)&& (gid < numGrp));
419 
420  // save the CV pointer so that we can refer to it in the future when
421  // plotting useful information ....
422 // monCvMatPtr[monId] = (void*) imgWin;
423  monMaxSizeN[monId] = maxSize;
424  monYscale[monId] = yscale;
425 
426  return;
427  }
428 
429  void CpuSNN::plotSpikeBuff(int gid, int row, int col)
430  {
431  static int cumSize = 0;
432  static int cntNext = 0;
433 
434  if(!plotUsingOpenCV)
435  return;
436 
437  DBG(2, fpLog, AT, "plotSpikeBuff()");
438 
439  int monId = grp_Info[gid].MonitorId;
440  if(monId == -1) {
441  fprintf(stderr, "RasterPlot(gid=%d) failed... Group %s not monitored..\n", gid, grp_Info2[gid].Name.c_str());
442  fprintf(stderr, "call spikeMonitor(gid=%d) function in your code to ensure monitoring of group %s\n", gid, grp_Info2[gid].Name.c_str());
443  return;
444  }
445 
446  int maxSize = monMaxSizeN[monId];
447  //int yscale = monYscale[monId];
448 
449  }
450 
451  void CpuSNN::setImgWin(int monId, int localId, int t)
452  {
453  assert(monId != -1);
454  assert(localId < numN);
455 
456  if(!plotUsingOpenCV)
457  return;
458  return;
459  }
460 
461  void CpuSNN::plotProbes()
462  {
463  if(!plotUsingOpenCV)
464  return;
465 
466  char winNameI[100];
467  char winNameV[100];
468  char winNameH[100];
469  char winNameF[100];
470 
471  static CvMat* imgWinF;
472  static CvMat* imgWinH;
473  static CvMat* imgWinV;
474  static CvMat* imgWinI;
475 
476  static int firstSet = 0;
477 
478  int imgSizeY = 100;
479  int imgSizeX = 500;
480  float scaleX = 1000.0/imgSizeX;
481 
482  int prevGid = -1;
483  int cnt=0;
484  probeParam_t* n = neuronProbe;
485 
486  float fmin = 0.0; float hfmin = 0.0;
487 
488  while(n) {
489  int retVal = 0;
490  int nid = n->nid;
491  int gid = findGrpId(nid);
492  if(prevGid == -1) prevGid = gid;
493  assert((gid >= 0)&& (gid < numGrp));
494  int len = 0;
495 
496  if (n->type & PROBE_CURRENT) {
497  retVal = sprintf(winNameI, "probeCurrent:g=%d,n=%d:%s(max=%3.1f,min=%3.1f)", gid, nid-grp_Info[gid].StartN, grp_Info2[gid].Name.c_str(), n->imax, n->imin);
498  if(retVal < 0) perror("string length error\n");
499  if(firstSet==0) {
500  imgWinI = cvCreateMat(imgSizeY, imgSizeX, CV_8UC1);
501  cvNamedWindow(winNameI);
502  cvMoveWindow(winNameI, 10+cnt*imgSizeX, 100+len*(imgSizeY+30)+10);
503  }
504  cvSetZero(imgWinI);
505  len++;
506  }
507 
508  if (n->type & PROBE_VOLTAGE) {
509  sprintf(winNameV, "probeVoltage:g=%d,n=%d:%s(max=%3.1f,min=%3.1f)", gid, nid-grp_Info[gid].StartN, grp_Info2[gid].Name.c_str(), n->vmax, n->vmin);
510  if(retVal < 0) perror("string length error\n");
511  if(firstSet==0) {
512  imgWinV = cvCreateMat(imgSizeY, imgSizeX, CV_8UC1);
513  cvNamedWindow(winNameV);
514  cvMoveWindow(winNameV, 10+cnt*imgSizeX, 100+len*(imgSizeY+30)+10);
515  }
516  cvSetZero(imgWinV);
517  len++;
518  }
519 
520  if (n->type & PROBE_HOMEO_RATE) {
521  sprintf(winNameH, "probeHomeoRate:g=%d,n=%d:%s(max=%3.1f,base=%3.1f)", gid, nid-grp_Info[gid].StartN, grp_Info2[gid].Name.c_str(), n->hfmax, baseFiring[nid]);
522  if(retVal < 0) perror("string length error\n");
523  if(firstSet==0) {
524  imgWinH = cvCreateMat(imgSizeY, imgSizeX, CV_8UC1);
525  cvNamedWindow(winNameH);
526  cvMoveWindow(winNameH, 10+cnt*imgSizeX, 100+len*(imgSizeY+30)+10);
527  }
528  cvSetZero(imgWinH);
529  len++;
530  }
531  if (n->type & PROBE_FIRING_RATE) {
532  sprintf(winNameF, "probeFiringRate:g=%d,n=%d:%s(max=%3.1f,base=%3.1f)", gid, nid-grp_Info[gid].StartN, grp_Info2[gid].Name.c_str(), n->fmax, baseFiring[nid]);
533  if(retVal < 0) perror("string length error\n");
534  if(firstSet==0) {
535  imgWinF = cvCreateMat(imgSizeY, imgSizeX, CV_8UC1);
536  cvNamedWindow(winNameF);
537  cvMoveWindow(winNameF, 10+cnt*imgSizeX, 100+len*(imgSizeY+30)+10);
538  }
539  cvSetZero(imgWinF);
540  len++;
541  }
542 
543  if(prevGid != gid) {
544  cnt = cnt+1;
545  }
546 
547  float vScale = (imgSizeY-1)/(n->vmax-n->vmin);
548  float iScale = (imgSizeY-1)/(n->imax-n->imin);
549  float hScale = (imgSizeY-1)/(n->hfmax-hfmin);
550  float fScale = (imgSizeY-1)/(n->fmax-fmin);
551 
552  for(int i=0; i < 1000; i++) {
553  int xpt = (int) (i/scaleX);
554  if (n->type & PROBE_VOLTAGE) {
555  int yptV = (int)(vScale*(n->bufferV[i]-n->vmin));
556  if (yptV >= imgSizeY) yptV = imgSizeY-1;
557  if (yptV < 0) yptV = 0;
558  *((uchar*) CV_MAT_ELEM_PTR( *imgWinV, imgSizeY - 1 - yptV, xpt)) = 255.0;
559  }
560 
561  if (n->type & PROBE_CURRENT) {
562  int yptI = (int)(iScale*(n->bufferI[i])-n->imin);
563  if (yptI >= imgSizeY) yptI = imgSizeY-1;
564  if (yptI < 0) yptI = 0;
565  *((uchar*) CV_MAT_ELEM_PTR( *imgWinI, imgSizeY - 1 - yptI, xpt)) = 255.0;
566  }
567 
568  if (n->type & PROBE_HOMEO_RATE) {
569  int yptH = (int)(hScale*(n->bufferHomeo[i])-hfmin);
570  if (yptH >= imgSizeY) yptH = imgSizeY-1;
571  if (yptH < 0) yptH = 0;
572  *((uchar*) CV_MAT_ELEM_PTR( *imgWinH, imgSizeY - 1 - yptH, xpt)) = 255.0;
573  }
574 
575  if (n->type & PROBE_FIRING_RATE) {
576  int yptF = (int)(fScale*(n->bufferFRate[i])-fmin);
577  if (yptF >= imgSizeY) yptF = imgSizeY-1;
578  if (yptF < 0) yptF = 0;
579  *((uchar*) CV_MAT_ELEM_PTR( *imgWinF, imgSizeY - 1 - yptF, xpt)) = 255.0;
580  }
581  }
582  if (n->type & PROBE_VOLTAGE) cvShowImage(winNameV, imgWinV);
583  if (n->type & PROBE_CURRENT) cvShowImage(winNameI, imgWinI);
584  if (n->type & PROBE_HOMEO_RATE) cvShowImage(winNameH, imgWinH);
585  if (n->type & PROBE_FIRING_RATE) cvShowImage(winNameF, imgWinF);
586  n = n->next;
587  prevGid = gid;
588  }
589 
590  firstSet = 1;
591 
592  }
593 
594 
595 typedef struct fileInfo_s {
596  FILE* fp;
597  uint32_t simTime;
598 } fileInfo_t;
599 
600 
601  // close files and also clear all data used
602  // by raster generation function
603  void CpuSNN::clearRasterData()
604  {
605  DBG(2, fpLog, AT, "clearRasterData()");
606 
607  map<string, fileInfo_t*>::const_iterator itr;
608 
609  for(itr = rasterFileInfo.begin(); itr != rasterFileInfo.end(); ++itr){
610  fileInfo_t* rInfo = (*itr).second;
611  fclose(rInfo->fp);
612  delete rInfo;
613  }
614  rasterFileInfo.erase(rasterFileInfo.begin(), rasterFileInfo.end());
615  }
616 
617 
618  void CpuSNN::rasterPlotAll(int row, int col, bool newFileEveryTime)
619  {
620  DBG(2, fpLog, AT, "rasterPlotAll() called");
621 
622  // its always best to store the results in a single file...
623  assert(newFileEveryTime == false);
624 
625  if ((currentMode == GPU_MODE) && (BLK_CONFIG_VERSION)) {
626  //rasterPlot(-1, fname, row, dontOverWrite);
627  for (int monId=0; monId < numSpikeMonitor; monId++) {
628  string& fname = monBufferFileName[monId];
629  FILE* fp = getRasterFilePointer(fname, newFileEveryTime);
630  monBufferFp[monId] = fp;
631  }
632 
633  // now we got the file pointer.. go and dump
634  // if fp=null, the GPU will atleast update
635  // the CVMat array with spike info to be displayed later.
636  // if fp=null, then the CPU will mostly just return without
637  // dumpign the spike information to the file..
638  dumpSpikeBuffToFile(NULL, -1);
639 
640  for (int monId=0; monId < numSpikeMonitor; monId++) {
641  if(monBufferFp[monId])
642  fflush(monBufferFp[monId]);
643  }
644 
645  // enable plotting..
646  if(plotUsingOpenCV) {
647  for (int i=0; i < numSpikeMonitor; i++) {
648  int gid = monGrpId[i];
649  plotSpikeBuff(gid, row, col);
650  }
651  }
652  }
653  else {
654  // when running on CPU mode, we dump info. separately.
655  for (int monId=0; monId < numSpikeMonitor; monId++) {
656  string& fname = monBufferFileName[monId];
657  int gid = monGrpId[monId];
658  rasterPlot(gid, fname, row, col, newFileEveryTime);
659  }
660  }
661  }
662 
663  FILE* CpuSNN::getRasterFilePointer(const string& fname, bool newFileEveryTime)
664  {
665  DBG(2, fpLog, AT, "getRasterPointer() called");
666  FILE* fpDumpFile = NULL;
667 
668  assert(newFileEveryTime == false);
669 
670 #define MAXIMUM_OPEN_RASTER_FILE 100
671 
672  assert(rasterFileInfo.size() < MAXIMUM_OPEN_RASTER_FILE);
673 
674  if (fname != "")
675  {
676  fileInfo_t* rInfo=NULL;
677  string new_fname(fname);
678 
679  if (rasterFileInfo.count(fname)) {
680  rInfo = rasterFileInfo[fname];
681  }
682 
683  // file does not exists
684  if (rInfo==NULL) {
685  rInfo = new fileInfo_t;
686  rInfo->simTime = -1;
687  rInfo->fp = NULL;
688  rasterFileInfo[fname] = rInfo;
689  }
690 
691  if (newFileEveryTime) {
692  if (rInfo->simTime != simTime) {
693  if (rInfo->fp != NULL)
694  fclose(rInfo->fp);
695  appendFileName(new_fname, simTime);
696  rInfo->fp = fopen(new_fname.c_str(), "w");
697  }
698  }
699  else {
700  if (rInfo->fp == NULL) {
701  rInfo->fp = fopen(fname.c_str(), "w");
702  }
703  }
704 
705  fpDumpFile = rInfo->fp;
706  }
707 
708  return fpDumpFile;
709 
710  }
711 
712 
713  void CpuSNN::plotFiringRate(const string& fname, int x, int y, int y_limit)
714  {
715  FILE* fp = fopen(fname.c_str(), "a");
716 
717  plotFiringRate(fp, x, y, y_limit);
718 
719  fclose(fp);
720  }
721 
722  void CpuSNN::plotFiringRate(FILE* fpAvg, int x, int y, int y_limit)
723  {
724 
725 #if _DEBUG
726  return;
727 #endif
728  //FILE* fpAvg = fopen("avg_firing.txt", "a");
729  if(fpAvg) fprintf(fpAvg, "#-------------------\n");
730  int xImgPos = x;
731  int yImgPos = y;
732  // display the post connectivity information as an image
733  for(int g=0; g < numGrp; g++) {
734  int sizeX = 128;
735  int sizeY = 128;
736  int scaleX = sizeX/grp_Info2[g].numX;
737  int scaleY = sizeY/grp_Info2[g].numY;
738  sizeX = (scaleX <= 0) ? grp_Info2[g].numX: sizeX;
739  sizeY = (scaleY <= 0) ? grp_Info2[g].numY: sizeY;
740  if(scaleX <=0) scaleX = 1;
741  if(scaleY <=0) scaleY = 1;
742  Mat m(Size(sizeX, sizeY), CV_8UC1);
743  float maxFiring = 50.0f;
744  float scaleFactor = 255.0/maxFiring;
745  //fprintf(stderr, "sizex=%d, sizey=%d, scalex=%d, scaley=%d\n", sizeX, sizeY, scaleX, scaleY);
746  bool poissonType = grp_Info[g].Type&POISSON_NEURON;
747  bool excitatoryType = (grp_Info[g].Type&TARGET_AMPA) || (grp_Info[g].Type&TARGET_NMDA);
748 // if (poissonType) {
749 // fprintf(stderr, "poisson group = %s\n", grp_Info2[g].Name.c_str());
750 // }
751  int nid = grp_Info[g].StartN;
752  float totAvg=0.0;
753  float printAvg=0.0;
754  for (int j=0; (j < grp_Info2[g].numY); j++) {
755  for (int i=0; i < grp_Info2[g].numX; i++, nid++) {
756  float avg = nSpikeCnt[nid];
757  totAvg += avg;
758  for (int x=0; x < scaleX; x++) {
759  for (int y=0; y < scaleY; y++) {
760  int row = scaleY*j+y; assert(row < sizeX);
761  int col = scaleX*i+x; assert(col < sizeY);
762  m.at<char>(row,col)= (char) ((int) avg*scaleFactor)&0xff;
763  }
764  }
765  if ((!poissonType) && (excitatoryType))
766  if((i== grp_Info2[g].numX/2) && (j == grp_Info2[g].numY/2))
767  if(fpAvg) fprintf(fpAvg, "%3d %3d : %3d => %03.3f (%s)\n", nid, i, j, avg, grp_Info2[g].Name.c_str());
768  }
769  }
770 
771 // if ((!poissonType) && (IS_EXCITATORY(nid, numNInhPois, numNReg, numNExcReg, numN)))
772 // fprintf(fpAvg, "%3d %3d : %3d => %03.3f \n", nid, p_Info2[g].numX/2, p_Info2[g].numY/2, totAvg);
773 
774  string name(grp_Info2[g].Name);
775  imshow(name+"-conn", m);
776  cvMoveWindow((name+"-conn").c_str(), xImgPos, yImgPos);
777 
778  yImgPos = yImgPos+sizeX + 30;
779  if ( yImgPos > y_limit ) {
780  yImgPos = y;
781  xImgPos = xImgPos + sizeY + 10;
782  }
783  }
784  }
785 
786 
787 
788 
789  if(plotUsingOpenCV) {
790  // wait for a key
791  keyVal = cvWaitKey(10);
792 // if(keyVal != -1) {
793 // fprintf(stderr, "keyVal = %c %d %d %d \n", (char) keyVal, keyVal, (int) 'p', (int) 's', (int) 'q');
794 // cvWaitKey(0);
795 // }
796  if ((char) keyVal == 'p') {
797  fprintf(stderr, "Pause key pressed ! Press any to continue\n");
798  rasterPlotAll(10, false);
799  cvWaitKey(0);
800  }
801  else if( (char) keyVal == 's') {
802  //saveConnectionWeights();
803  rasterPlotAll(10, false);
804  cvWaitKey(0);
805  }
806  else if( (char) keyVal == 'q') {
807  cvWaitKey(0);
808  exitSimulation(0);
809  }
810  else if( (char) keyVal == 'b') {
811  return keyVal;
812  }
813  else if( (char) keyVal == 'n') {
814  return keyVal;
815  }
816  }
817 
818 
819 
820 
821  void dumpToFile(CvMat* mat)
822  {
823  static int cnt = 0;
824 
825  //std::stringstream fname;
826  //fname << "dumpCvMat" << cnt++ << ".txt";
827  char fname[100];
828  sprintf(fname, "dumpCvMat%d.txt", cnt++);
829  FILE* fp = fopen(fname, "w");
830 
831  if (((mat->type&0xff)==CV_32FC1)) {
832  fprintf(stdout, "Values are %d\n", CV_32FC1);
833  for(int row=0; row<mat->rows; row++ ) {
834  const float* ptr = (const float*)(mat->data.ptr + row * mat->step);
835  for( int col=0; col<mat->cols; col++ ) {
836  fprintf(fp, "%2.1f ", *ptr);
837  ptr++;
838  }
839  fprintf(fp, "\n");
840  }
841  }
842  else if ((mat->type&0xff)==CV_8UC1) {
843  int k=2;
844  while(k > 0) {
845  fprintf(stdout, "Values are %d\n", CV_8UC1);
846  for(int row=0; row<mat->rows; row++ ) {
847  const char* ptr = (const char*)(mat->data.ptr + row * mat->step);
848  for( int col=0; col<mat->cols; col++ ) {
849  if(((k==2) && (*ptr > 0)) || ((k==1) && (*ptr < 0)))
850  fprintf(fp, " ");
851  else
852  fprintf(fp, "%x ", ((int) *ptr)&0xff);
853  ptr++;
854  }
855  fprintf(fp, "\n");
856  }
857  k=k-1;
858  }
859  }
860 
861  fclose(fp);
862  }
863 
864  CvMat* getRampPattern ( int size, float min, float max, string rampType, float freq, CvMat* mat)
865  {
866  if (mat==NULL)
867  mat = cvCreateMat(1, size, CV_32FC1);
868 
869 #if _DEBUG_
870  fprintf(stdout, " Printing Ramp Patter Rates : \n");
871 #endif
872 
873  if(rampType.find("ramp") != string::npos) {
874  float step = (max - min)/size;
875  float rate = min;
876  for(int row=0; row<mat->rows; row++ ) {
877  float* ptr = (float*)(mat->data.ptr + row * mat->step);
878  for( int col=0; col<mat->cols; col++) {
879  *ptr = rate; ptr++; rate += step;
880  }
881  }
882  }
883  else if ( rampType.find("sine") != string::npos) {
884  float range = (max - min)/2;
885  float sinFactor = (2*3.14159265)/(size/freq);
886  for(int row=0; row<mat->rows; row++ ) {
887  float* ptr = (float*)(mat->data.ptr + row * mat->step);
888  for( int col=0; col<mat->cols; col++) {
889  *ptr = range + range*sin(sinFactor*col);
890 #if _DEBUG_
891  fprintf(stdout, " %f ", *ptr);
892 #endif
893  ptr++;
894  }
895  }
896  }
897 #if _DEBUG_
898  fprintf( stdout, " Printing Ramp Patter Rates : \n");
899 #endif
900  fflush(stdout);
901  return mat;
902  }
903 
904  int setGaborParameters(GaborFilter* gb, int radius, float angle)
905  {
906  int factor=1;
907  //float angle = angles[(int)((sizeof(angles)/4)*drand48())]; //45.0;// = atof(argv[2]);
908  float freq = 1/10.0; //0.1105/factor; // atof(argv[3]);
909  float bw = 1.0; // atof(argv[4]);
910  float phase = 0.0; // atof(argv[5]);
911  float rho = 1.5; //atof(argv[6]);
912  float sig = 2*factor;
913  gb->GenerateFilter(radius, angle, freq, sig, phase, bw, rho);
914  return 0;
915  }
916 
917  int displayPattern (GaborFilter *gb, CvMat* spikeRate)
918  {
919  static CvMat* imgWin = cvCreateMat(160, 160, CV_8UC1);
920  static bool firstDisplay = true;
921  char winName[]="mainWin";
922 
923  CvMat* spikePixel = cvCreateMat(spikeRate->rows, spikeRate->cols, CV_8UC1);
924 
925  double minVal, maxVal;
926  cvMinMaxLoc(spikeRate, &minVal, &maxVal);
927 
928  for(int i=0; i < spikeRate->rows; i++) {
929  for (int j=0; j < spikeRate->cols; j++) {
930  CvScalar rate = cvGet2D(spikeRate, i, j);
931  double val = (int) 255*rate.val[0]/maxVal;
932  CvScalar pixel;
933  pixel.val[0] = val;
934  cvSet2D(spikePixel, i, j, pixel);
935  }
936  }
937 
938  // create a window
939  cvNamedWindow(winName);
940 
941  if (firstDisplay) {
942  cvMoveWindow("mainWin", 300, 500);
943  firstDisplay = false;
944  }
945 
946  cvResize(spikePixel, imgWin);
947 
948  cvShowImage(winName, imgWin);
949 
950  return 0;
951  }
952  */
Contains all of CARLsim's core functionality.
Definition: snn.h:619