Debian Codegraph @

utils/VisualiseNeurons.cpp

raw
1 /*
2 * This file is part of MUSIC.
3 * Copyright (C) 2009, 2022 INCF
4 *
5 * MUSIC is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 3 of the License, or
8 * (at your option) any later version.
9 *
10 * MUSIC is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License
16 * along with this program. If not, see <http://www.gnu.org/licenses/>.
17 */
18
19 // VisualiseNeurons.cpp written by Johannes Hjorth, [email protected]
20
21
22 #include "VisualiseNeurons.h"
23
24 #include <unistd.h>
25
26 void VisualiseNeurons::printHelp() {
27 std::cerr << "Usage: viewevents [OPTION...] CONFIGFILE" << std::endl
28 << "`viewevents' receives spikes through a MUSIC input port" << std::endl
29 << "and displays them as a 3D graphical representation." << std::endl << std::endl
30 << " -t, --timestep TIMESTEP time between tick() calls (default 1 ms)" << std::endl
31 << " -s, --scaletime SCALING real time to simulated time scale factor (s)" << std::endl
32 << " If omitted, the visualisation runs at full speed." << std::endl
33 << " -h, --help print this help message" << std::endl
34 << " -T, --title TITLE window title" << std::endl << std::endl
35 << "CONFIGFILE format:" << std::endl
36 << "<Number of neuron types (1 int)>" << std::endl
37 << "<Baseline colour neuron 1 (3 double): R G B>" << std::endl
38 << "<Excited colour neuron 1 (3 double): R G B>" << std::endl
39 << "[Baseline colour neuron i: R G B]" << std::endl
40 << "[Excited colour neuron i: R G B]" << std::endl
41 << "<Neuron 1 information (4 double, 1 int): X Y Z RADIE NEURONTYPEINDEX>" << std::endl
42 << "[Neuron i information: X Y Z RADIE NEURONTYPEINDEX]" << std::endl << std::endl
43 << "Report bugs to <[email protected]>." << std::endl;
44 exit(1);
45 }
46
47 void VisualiseNeurons::getArgs(int argc, char* argv[]) {
48
49 opterr = 0; // handle errors ourselves
50 while (1)
51 {
52 static struct option long_options[] =
53 {
54 {"timestep", required_argument, 0, 't'},
55 {"scaletime", required_argument, 0, 's'},
56 {"help", no_argument, 0, 'h'},
57 {"title", required_argument, 0, 'T'},
58 {0, 0, 0, 0}
59 };
60 /* `getopt_long' stores the option index here. */
61 int option_index = 0;
62
63 // the + below tells getopt_long not to reorder argv
64 int c = getopt_long (argc, argv, "+t:s:T:h", long_options, &option_index);
65
66 /* detect the end of the options */
67 if (c == -1)
68 break;
69
70 switch (c)
71 {
72 case 't':
73 dt_ = atof (optarg); //*fixme* error checking
74 std::cout << "Using dt = " << dt_ << std::endl;
75 continue;
76 case 's':
77 synchFlag_ = 1;
78 scaleTime_ = atof(optarg);
79 std::cout << "Using scaletime: " << scaleTime_ << std::endl;
80 continue;
81 case '?':
82 break; // ignore unknown options
83 case 'T':
84 windowTitle_ = optarg; //new string(optarg);
85 continue;
86 case 'h':
87 printHelp();
88 // fall through...
89 default:
90 abort ();
91 }
92 }
93
94 if (argc < optind + 1 || argc > optind + 1) {
95 printHelp(); // exits
96 }
97
98 confFile_ = string(argv[optind]);
99
100 }
101
102
103 void VisualiseNeurons::run(int argc, char **argv) {
104
105 // Add this object to the static-wrapper
106 objTable_.push_back(this);
107
108 // Init music
109 setup_ = new MUSIC::Setup(argc, argv);
110 MPI_Comm comm = setup_->communicator();
111 MPI_Comm_rank (comm, &rank_);
112
113 if(rank_ > 0) {
114 std::cerr << argv[0] << " only supports one process currently!"
115 << std::endl;
116 exit(-1);
117 }
118
119 // Init glut
120 glutInit(&argc,argv);
121 glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION);
122
123
124 // Store the stop time
125 setup_->config ("stoptime", &stopTime_);
126
127 // Parse inparameters
128 getArgs(argc,argv);
129
130 readConfigFile(confFile_);
131
132 MUSIC::EventInputPort* evport = setup_->publishEventInput("plot");
133
134
135 if (!evport->isConnected()) {
136 if (rank_ == 0)
137 std::cerr << "port `plot' is not connected" << std::endl;
138 MPI_Abort (comm, 1);
139 }
140
141 if(evport->width() != (int) coords_.size()) {
142 std::cerr << "Size mismatch: port width " << evport->width()
143 << " number of neurons to plot " << coords_.size()
144 << std::endl;
145 }
146
147
148 MUSIC::LinearIndex indexmap(0, evport->width());
149 evport->map (&indexmap, this, 0.0);
150
151 double stoptime;
152 setup_->config ("stoptime", &stoptime);
153
154
155 // GLUT
156 glutInitDisplayMode(GLUT_DOUBLE | GLUT_DEPTH);
157 glutInitWindowSize(500, 500);
158 glutInitWindowPosition(50, 50);
159 glutCreateWindow(windowTitle_.c_str());
160
161 // Initialise
162 glEnable(GL_DEPTH_TEST);
163 glClearColor (0.0,0.0,0.0,1.0);
164
165 GLfloat pos[4] = { -100, 100, 200, 0.0 };
166 GLfloat light[4] = { 1.0, 1.0, 1.0, 1.0};
167
168 // Lightsources
169 glLightfv(GL_LIGHT0, GL_POSITION, pos);
170 glLightfv(GL_LIGHT0, GL_DIFFUSE, light);
171 glLightfv(GL_LIGHT0, GL_SPECULAR, light);
172 glEnable(GL_LIGHT0);
173 glEnable(GL_LIGHTING);
174
175 // Default materials
176 glColorMaterial(GL_FRONT_AND_BACK, GL_AMBIENT_AND_DIFFUSE);
177 glEnable(GL_COLOR_MATERIAL);
178 glEnable(GL_NORMALIZE);
179
180 // Setup camera
181 glMatrixMode(GL_PROJECTION);
182 glLoadIdentity();
183 double fov = (is3dFlag_) ? 0.7*maxDist_/2 : 0.5*maxDist_/2;
184
185 // std::cout << "MAX DIST: " << maxDist_ << std::endl;
186 glFrustum(-fov,fov,-fov,fov,maxDist_/2,3.1*maxDist_); // Visible range 50-800
187 glTranslated(0,0,-2.2*maxDist_); //-600
188
189 double camAng = (is3dFlag_) ? 30 : -30;
190 glRotated(camAng,1,0,0);
191 glMatrixMode(GL_MODELVIEW);
192
193 // Create displaylist for neuron(s)
194 GLUquadric* neuronQuad = gluNewQuadric();
195
196 int nVert = (coords_.size() < 500) ? 10 : 2;
197
198 neuronList_ = glGenLists(1);
199
200 glNewList(neuronList_, GL_COMPILE);
201 gluSphere(neuronQuad, 1, nVert*2, nVert);
202 //gluSphere(neuronQuad, 1, 20, 10);
203 glEndList();
204
205 glutDisplayFunc(displayWrapper);
206
207 glutPostRedisplay();
208 glFinish();
209
210
211
212 // Music done.
213
214
215 if(rank_ == 0) {
216 void *exitStatus;
217
218 glutTimerFunc(25,rotateTimerWrapper, 1);
219
220 pthread_create(&tickThreadID_, NULL, runMusic, &synchFlag_);
221
222 glutPostRedisplay();
223 glFinish();
224
225 glutMainLoop();
226 pthread_join(tickThreadID_,&exitStatus);
227
228 } else {
229 std::cerr << "Only run start() on rank 0" << std::endl;
230 }
231
232 }
233
234 void VisualiseNeurons::finalize() {
235 runtime_->finalize ();
236
237 delete runtime_;
238
239 // std::cout << "Rank " << rank_
240 // << ": Searching for VisualiseNeurons wrapper object";
241 for(unsigned int i = 0; i < objTable_.size(); i++) {
242 if(objTable_[i] == this) {
243 //std::cout << "found.";
244 }
245 else {
246 //std::cout << ".";
247 }
248 }
249 //std::cout << std::endl;
250
251 // Should delete all other objects also.
252
253 }
254
255
256 void VisualiseNeurons::display() {
257
258 glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT);
259
260 glLoadIdentity();
261 glRotated(rotAngle_,0.1*sin(rotAngle_/100),1,0);
262
263 for(unsigned int i = 0; i < coords_.size(); i++) {
264 // Here we translate coordinate system and draw a neuron
265 glPushMatrix();
266
267 //double vMin = -100e-3;
268 //double vMax = 100e-3;
269
270 double col = volt_[i]; //(volt_[i] - vMin)/(vMax - vMin);
271
272 // maxCol is [1 0.9 0]
273 // GLdouble red = 0.25 + 0.75*col;
274 // GLdouble green = 0.53 + 0.37*col;
275 // GLdouble blue = 0.10 - 0.10*col;
276 neuronColour tmpColB = baseLineCol_[cMap_[i]];
277 neuronColour tmpColE = excitedCol_[cMap_[i]];
278
279 GLdouble red = tmpColB.r + (tmpColE.r-tmpColB.r)*col;
280 GLdouble green = tmpColB.g + (tmpColE.g-tmpColB.g)*col;
281 GLdouble blue = tmpColB.b + (tmpColE.b-tmpColB.b)*col;
282
283 glColor3d(red,green,blue);
284 //float specReflection[] = { 0.2*col, 0.2*col, 0.2*col, 1 };
285 //glMaterialfv(GL_FRONT, GL_SPECULAR, specReflection);
286
287 glTranslated(coords_[i].x,coords_[i].y,coords_[i].z);
288
289 double scale = coords_[i].r*(1+spikeScale_*col);
290 glScaled(scale,scale,scale);
291 glCallList(neuronList_);
292 glPopMatrix();
293 }
294
295 char buffer[20];
296
297 sprintf(buffer,"%.3f s",time_);
298 //std::cout << "Buffer: " << buffer << std::endl;
299 //std::cout << time_ << std::endl;
300
301 glLoadIdentity();
302 glColor3d(0.2,0.2,0.4);
303 // glRasterPos2d(-maxDist_*1.7,-maxDist_*1.75);
304 // glRasterPos3d(-maxDist_*2,-1.7*maxDist_,0*maxDist_);
305 if(is3dFlag_) {
306 glColor3d(1,1,1);
307 glRasterPos3d(-maxDist_*0.9,-maxDist_*0.5,maxDist_);
308 }
309 else {
310 glRasterPos3d(-maxDist_*0.8,maxDist_*0.8,0.3*maxDist_);
311 }
312 for(unsigned int i = 0; i < strlen(buffer); i++) {
313 glutBitmapCharacter(GLUT_BITMAP_HELVETICA_18,buffer[i]);
314 }
315
316 glutSwapBuffers();
317
318 }
319
320
321
322 void VisualiseNeurons::addNeuron(double x, double y, double z, double r, double cIdx) {
323
324 if(cIdx >= cMap_.size()) {
325 std::cerr << "VisualiseNeurons: Neuron colour index "
326 << cIdx << " out of range, using 0." << std::endl;
327 cIdx = 0;
328 }
329
330 // std::cout << "Adding neuron " << x << "," << y << "," << z
331 // << "," << r << "," << cIdx << std::endl;
332
333 neuronCoord p;
334 p.x = x; p.y = y; p.z = z; p.r = r;
335 coords_.push_back(p);
336 volt_.push_back(0);
337 cMap_.push_back(cIdx);
338 }
339
340 void VisualiseNeurons::rotateTimer() {
341 rotAngle_ += 0.5;
342
343 if(rotAngle_ >= 36000) {
344 rotAngle_ -= 36000;
345 }
346
347 }
348
349 void VisualiseNeurons::operator () (double t, MUSIC::GlobalIndex id) {
350 //std::cout << "Event " << id << " detected at " << t
351 // << " (vis time = " << time_ << ")" << std::endl;
352
353 assert(0 <= id && id < (int) volt_.size()); // Check that it is within range
354
355 if(t < time_) // time_ is old timestep
356 {
357 std::cerr << "Received old spike " << t << " at " << time_ << std::endl;
358 }
359
360 TimeIdPair *tmpPair = new TimeIdPair(t,id);
361
362 // Add time to priority queue
363 priorityQueue_.push(*tmpPair);
364
365 }
366
367
368 void VisualiseNeurons::tick() {
369
370 if(!done_){
371
372 // Reinitialize realtime clock at first tick
373 if (runtime_->time () == 0.0)
374 gettimeofday(&tickStartTime_,NULL);
375
376
377 #if 0
378 // Call music to get the latest simulation data
379 std::cerr << "Size: " << volt_.size() << " ";
380 std::cerr << "Entering tick (" << time_ <<")...";
381 #endif
382
383 runtime_->tick();
384
385 #if 0
386 std::cerr << "done(" << time_ <<")." << std::endl;
387 #endif
388
389
390 oldTime_ = time_;
391 time_ = runtime_->time ();
392
393 // Make sure the time steps are correct
394 assert(dt_ - 1e-9 < time_ - oldTime_
395 && time_ - oldTime_ < dt_ + 1e-9);
396
397
398 // Should we make the visualisation go in realTime=scaleTime_*simTime?
399 if(synchFlag_) {
400 // Yes, how long did we spend in the tick?
401 gettimeofday(&tickEndTime_,NULL);
402
403 // How much of the time allocated for this timestep remains?
404 double delayLeft = dt_*scaleTime_
405 - (tickEndTime_.tv_sec - tickStartTime_.tv_sec)
406 - (tickEndTime_.tv_usec - tickStartTime_.tv_usec) / 1000000.0;
407
408
409 if(delayLeft > 0) {
410
411 // We reuse the timeval for the delay
412 tickDelay_.tv_sec = 0;
413 tickDelay_.tv_usec = (int) (delayLeft*1e6);
414
415 // std::cerr << "Delay left : " << tickDelay_.tv_usec
416 // << " milliseconds" << std::endl;
417
418 // Delay so that enough time passes
419 //select(0,0,0,0,&tickDelay_);
420 usleep(tickDelay_.tv_usec);
421
422
423 } else {
424 // Whoops, simulation were too slow... print error.
425 std::cerr << "t = " << time_
426 << ": Music's tick() took "
427 << -delayLeft*1e6 << " microseconds too long to execute"
428 << std::endl;
429
430 }
431
432 // Set end of this tick as start of next tick
433 gettimeofday(&tickStartTime_,NULL);
434 }
435
436
437 // Decay the volt/activity
438 for(unsigned int i = 0; i < volt_.size(); i++) {
439 volt_[i] *= 1-(time_-oldTime_)/tau_;
440 }
441
442 // Add any new spikes that occured since last tick()
443 while(!priorityQueue_.empty() && priorityQueue_.top().getTime() <= time_)
444 {
445 volt_[priorityQueue_.top().getId()] = 1;
446 priorityQueue_.pop();
447
448 }
449
450
451 // Tell GLUT to update the screen
452 //glutPostRedisplay();
453
454 // Have we reached the end?
455 if(time_ >= stopTime_ - dt_/2.0) {
456 done_ = 1;
457 }
458 } else {
459 std::cout << "Last tick." << std::endl;
460 }
461
462 }
463
464
465 void VisualiseNeurons::displayWrapper() {
466 for(unsigned int i = 0; i < objTable_.size(); i++) {
467 VisualiseNeurons *vn = objTable_[i];
468 vn->display();
469 }
470 }
471
472 void VisualiseNeurons::rotateTimerWrapper(int v) {
473 VisualiseNeurons *vn = 0;
474
475 for(unsigned int i = 0; i < objTable_.size(); i++) {
476 vn = objTable_[i];
477 if(vn->is3dFlag_) {
478 vn->rotateTimer();
479 }
480 }
481
482 glutPostRedisplay();
483 glFinish();
484
485 if(vn && !(vn->done_)) {
486 glutTimerFunc(100,rotateTimerWrapper, 1);
487 }
488 }
489
490
491
492 void* VisualiseNeurons::runMusic(void *arg) {
493 VisualiseNeurons *vn = 0;
494
495 for(unsigned int i = 0; i < objTable_.size(); i++) {
496 vn = objTable_[i];
497
498 // Switch to runtime mode
499 // If the code is extended to handle more than one process
500 // then this will actually be SLOWER since the runtimes
501 // are *not* created in parallell
502
503 // Reason for this current setup is that we want to start
504 // the GLUT-loop as fast as possible, to get something on screen.
505 vn->runtime_ = new MUSIC::Runtime (vn->setup_, vn->dt_);
506
507 }
508
509 int allDone = 0;
510
511
512 while(!allDone && objTable_.size() > 0) {
513
514 allDone = 1;
515
516 for(unsigned int i = 0; i < objTable_.size(); i++) {
517 vn = objTable_[i];
518 vn->tick();
519
520 if(vn && !vn->done_) {
521 allDone = 0;
522 }
523 }
524 }
525
526 std::cout << "Simulation done." << std::endl;
527
528 // Simulation done.
529 glutLeaveMainLoop();
530
531 // Thread ends, return null
532 return NULL;
533
534
535 }
536
537
538 void VisualiseNeurons::readConfigFile(string filename) {
539 double x, y, z, r, dist;
540 double minDist = 1e66, maxR = 0;
541
542 neuronColour tmp;
543 int i = 0;
544 int nCols, cIdx;
545
546 std::cout << "Reading : " << filename << std::endl;
547
548 Datafile in(filename);
549
550 if (!in) {
551 std::cerr << "eventsource: could not open "
552 << filename << std::endl;
553 abort ();
554 }
555
556
557 // !!! WHY?!!
558 // VisualiseNeurons.cpp:246: undefined reference to `datafile::skip_header()'
559 //in.skip_header();
560
561 // How many different colours are there
562 in >> nCols;
563 std::cout << "VisualiseNeurons: Reading " << nCols
564 << " different neuron types" << std::endl;
565
566 for(i = 0; i < nCols; i++) {
567 // Read in neuron base colours
568 in >> tmp.r >> tmp.g >> tmp.b;
569 baseLineCol_.push_back(tmp);
570
571 // Read in neuron excited colour
572 in >> tmp.r >> tmp.g >> tmp.b;
573 excitedCol_.push_back(tmp);
574 }
575
576
577 // Read in neuron coordinates and colour
578 in >> x >> y >> z >> r >> cIdx;
579
580
581 while(!in.eof()) {
582 addNeuron(x,y,z,r,cIdx);
583 dist = sqrt(x*x + y*y + z*z);
584 maxDist_ = (dist > maxDist_) ? dist : maxDist_;
585
586 // All neurons are not in one plane
587 if(abs(x) > 1e-9 && abs(y) > 1e-9 && abs(z) > 1e-9) {
588 is3dFlag_ = 1;
589 }
590
591
592 // Dist and R are used to calculate spikeScale_
593 if(dist > 0) {
594 minDist = (dist < minDist) ? dist : minDist;
595 }
596
597 maxR = (r > maxR) ? r : maxR;
598
599 // std::cout << "Neuron " << i << " at " << x << "," << y << "," << z
600 // << " radie " << r << std::endl;
601 i++;
602
603 // Read in neuron coordinates and colour index
604 in >> x >> y >> z >> r >> cIdx;
605
606 }
607
608 spikeScale_ = (minDist/(3*maxR))-1;
609 spikeScale_ = (spikeScale_ > 0) ? spikeScale_ : 0;
610
611 std::cout << "Read " << i << " neuron positions" << std::endl;
612 std::cout << "Setting spike scaling to " << spikeScale_ << std::endl;
613 }
614
615
616 /*
617 bool VisualiseNeurons::TimeIdPair::operator<(const TimeIdPair& right) const
618 {
619 return time_ < right.getTime();
620 }
621 */
622
623 //bool VisualiseNeurons::TimeIdPair::operator>(const TimeIdPair& right) const
624 bool TimeIdPair::operator<(const TimeIdPair& right) const
625 {
626
627 // Note that we use > here, since we want lowest items first
628 return time_ > right.getTime();
629 }
630
631