001    package cnslab.cnsnetwork;
002    
003    import java.io.*;
004    import java.util.*;
005    import org.w3c.dom.bootstrap.*;
006    import org.w3c.dom.ls.*;
007
008    import jpvm.*;
009    import org.slf4j.Logger;
010    import org.slf4j.LoggerFactory;
011
012    import cnslab.cnsmath.*;
013    
014    /***********************************************************************
015    * The class for main host, which  spawn all the trial hosts and
016    * NetNosts, setup timer to check progress of the simulation and collect
017    * recorded data from all NetHosts.
018    * 
019    * @version
020    *   $Date: 2012-08-04 13:43:22 -0500 (Sat, 04 Aug 2012) $
021    *   $Rev: 104 $
022    *   $Author: croft $
023    * @author
024    *   Yi Dong
025    * @author
026    *   David Wallace Croft, M.Sc.
027    * @author
028    *   Jeremy Cohen
029    ***********************************************************************/
030    public class  MainSimulator
031    ////////////////////////////////////////////////////////////////////////
032    ////////////////////////////////////////////////////////////////////////
033    {
034      
035    private static final Class<MainSimulator>
036      CLASS = MainSimulator.class;
037
038//    private static final String
039//      CLASS_NAME = CLASS.getName ( );
040  
041    private static final Logger
042      LOGGER = LoggerFactory.getLogger ( CLASS );
043    
044    protected static final String
045      RESULTS_DIR = "results",
046      RESULTS_DIR_PREFIX = RESULTS_DIR + File.separator;
047    
048    // final instance variables
049      
050    /** Seed number used in simulation. */
051    public final Seed  idum;
052
053    /** Simulation XML file */
054    public final File  modelFile;
055
056    /** Heapsize for each of the nethosts. */
057    public final int  heapSize;
058
059    // non-final instance variables
060      
061    /** Seed integer provided by user */
062    public int  seedInt;
063    
064    /** Stores all the nethosts, first dimension is trialhosts, second
065    dimension is nethosts. */
066    public jpvmTaskId [ ] [ ]  netJpvmTaskIds;
067    
068    /** Information of JPVM */
069    public JpvmInfo  info;
070
071    /** Neuron end index for each of the Net Hosts correponding to one trial
072    host, endIndex.size is the number of nethost for one trial host */
073    public int [ ]  endIndex;
074
075    //  public Neuron [] neurons;
076
077    /**  Experiment instance. */
078    public Experiment  experiment;
079
080    /** Minimum synaptic delay */
081    public double  minDelay;
082
083    @Deprecated
084    public double  backFire;
085    
086    // private final instance variables
087    
088    private final RecorderData
089      recorderData = new RecorderData ( );    
090
091    // private non-final instance variables
092    
093    private int
094      aliveHost,
095      countDis,
096      countHosts,
097      expId   = 0,
098      totalTrials,
099      trialId = -1;
100    
101    // TODO:  What calls the toDo.run() method?
102    
103    private ToDo
104      toDo;
105
106    private LinkedList<IntraInfo> [ ]
107      intraReceiver;
108    
109    private double [ ]
110      per;
111    
112    private int [ ]
113      eeId,
114      ttId;    
115
116    ////////////////////////////////////////////////////////////////////////
117    ////////////////////////////////////////////////////////////////////////
118    
119    /***********************************************************************
120    * Main method with default values for step debugging.
121    ***********************************************************************/
122    public static void  main ( final String [ ]  args )
123    ////////////////////////////////////////////////////////////////////////
124    {
125      final MainSimulator  mainSimulator = new MainSimulator (
126        new Seed ( -2 ),
127        "gigTestUserSen.xml", // "test001.xml",
128        512 );
129      
130      mainSimulator.run ( );
131    }
132
133    ////////////////////////////////////////////////////////////////////////
134    ////////////////////////////////////////////////////////////////////////
135
136    /** Timer to check progress of the nethosts periodically. */
137    public final class  ToDo
138    ////////////////////////////////////////////////////////////////////////
139    ////////////////////////////////////////////////////////////////////////
140    {
141      
142    private final Timer  timer;
143
144    ////////////////////////////////////////////////////////////////////////
145    ////////////////////////////////////////////////////////////////////////
146    
147    public  ToDo ( final int  seconds )
148    ////////////////////////////////////////////////////////////////////////
149    {
150      timer = new Timer ( ) ;
151      
152      timer.schedule (
153        new ToDoTask (  ),
154        seconds * 1000,
155        seconds * 1000 ) ;
156    }
157
158    final class  ToDoTask
159      extends TimerTask
160    ////////////////////////////////////////////////////////////////////////
161    ////////////////////////////////////////////////////////////////////////
162    {
163      
164    @Override
165    public void  run ( )
166    ////////////////////////////////////////////////////////////////////////
167    {
168      jpvmBuffer  buf;
169
170      try
171      {
172        if ( info.endIndex.length == 1
173          && experiment.recorder.intraEle.size ( ) == 0 )
174        {
175          for ( int  i = 0; i < info.numTasks; i++ )
176          {
177            buf = new jpvmBuffer ( );
178            
179            buf.pack ( i );
180            
181            // LOGGER.finer("pack "+i);
182            
183            info.jpvm.pvm_mcast (
184              buf,
185              netJpvmTaskIds [ i ],
186              info.endIndex.length,
187              NetMessageTag.checkTime );
188          }
189        }
190        else
191        {
192          buf = new jpvmBuffer ( );
193          
194          info.jpvm.pvm_mcast (
195            buf,
196            info.tids,
197            info.numTasks,
198            NetMessageTag.checkTime );
199        }
200      }
201      catch ( jpvmException  ex )
202      {
203        ex.printStackTrace ( );
204        
205        System.exit ( -1 );
206      }
207    }
208    
209    ////////////////////////////////////////////////////////////////////////
210    // end of class ToDoTask
211    ////////////////////////////////////////////////////////////////////////
212    }
213
214    public void  stop ( )
215    ////////////////////////////////////////////////////////////////////////
216    {
217      timer.cancel ( );
218    }
219    
220    ////////////////////////////////////////////////////////////////////////
221    // end of class ToDo
222    ////////////////////////////////////////////////////////////////////////
223    }
224    
225    ////////////////////////////////////////////////////////////////////////
226    // constructor methods
227    ////////////////////////////////////////////////////////////////////////
228    
229    public  MainSimulator (
230      final Seed  idum,
231      final File  modelFile,
232      final int   heapSize )
233    ////////////////////////////////////////////////////////////////////////
234    {
235      this.idum      = idum;
236      
237      this.modelFile = modelFile;
238      
239      this.seedInt   = idum.seed;
240      
241      this.heapSize  = heapSize;
242    }
243    
244    public  MainSimulator (
245      final Seed    idum,
246      final String  modelFilename,
247      final int     heapSize )
248    ////////////////////////////////////////////////////////////////////////
249    {
250      this (
251        idum,
252        new File ( "model/" + modelFilename ),
253        heapSize );
254    }
255    
256    ////////////////////////////////////////////////////////////////////////
257    ////////////////////////////////////////////////////////////////////////
258
259    /***********************************************************************
260    * Organize the whole simulation in following steps:
261    * 1. start to parse the XML file
262    * 2. map cells, finding the numbers of neuron IDs.
263    * 3. parse neuronal definitions
264    * 4. parse the experiment
265    * 5. find the minimum synaptic delay
266    * 6. startup the JPVM
267    * 7. spawn all the trial hosts
268    * 8. spawn all the net hosts
269    * 9. fill up the jpvm info structure
270    * 10. setup the timing to send check progress message to all the
271    *     NetHosts periodically.
272    * 11. listing in background to communicate with TrialHosts and NetHosts
273    *     to initialize new trials, collect recorded data etc.
274    * 12. organize collected data and record it
275    * 13. end the simulation
276    ***********************************************************************/
277    public void  run ( )
278    ////////////////////////////////////////////////////////////////////////
279    {
280      try
281      {
282        // read network DOM info
283        
284        final long  simulationStartTime = System.currentTimeMillis ( );
285        
286        final SimulatorParser
287          simulatorParser = new SimulatorParser ( idum, modelFile );
288        
289        LOGGER.trace ( "begin to map cells" );
290        
291        simulatorParser.parseMapCells ( );
292        
293        simulatorParser.parseNeuronDef ( );
294        
295        LOGGER.trace ( "begin to parseexp" );
296        
297        simulatorParser.parseExperiment ( );
298        
299        LOGGER.trace ( "experiment is parsed" );
300        
301        // experiment information
302        
303        experiment = simulatorParser.experiment;
304        
305        simulatorParser.findMinDelay ( );
306        
307        if ( simulatorParser.documentType != null )
308        {
309          simulatorParser.document.removeChild (
310            simulatorParser.documentType );
311        }
312        
313        final DOMImplementationRegistry  domImplementationRegistry
314          = DOMImplementationRegistry.newInstance ( );
315        
316        final DOMImplementationLS  domImplementationLs
317          = ( DOMImplementationLS )
318            domImplementationRegistry.getDOMImplementation ( "LS" );
319        
320        final LSSerializer  lsSerializer
321          = domImplementationLs.createLSSerializer ( );
322        
323        final LSOutput  output = domImplementationLs.createLSOutput ( );
324        
325        final ByteArrayOutputStream  bArray = new ByteArrayOutputStream ( );
326        
327        output.setByteStream ( bArray );
328        
329        lsSerializer.write (
330          simulatorParser.document,
331          output );
332        
333        if ( simulatorParser.documentType != null )
334        {
335          simulatorParser.document.appendChild (
336            simulatorParser.documentType );
337        }
338        
339        final byte [ ]  ba = bArray.toByteArray ( );
340
341        info = new JpvmInfo ( );
342        
343        // Enroll in the parallel virtual machine...
344        
345        info.jpvm = new jpvmEnvironment ( );
346
347        // Get my task id...
348        
349        info.myJpvmTaskId = info.jpvm.pvm_mytid ( );
350        
351        LOGGER.trace ( "Task Id: " + info.myJpvmTaskId.toString ( ) );
352        
353        // total number of trial hosts
354
355        info.numTasks = simulatorParser.parallelHost;
356        
357        // root id
358        // not used at all
359        
360        info.idIndex = info.numTasks;
361        
362        info.tids = new jpvmTaskId [ info.numTasks ];
363
364        // Spawn some trialHosts
365        
366        info.jpvm.pvm_spawn (
367          "cnslab.cnsnetwork.TrialHost", // task_name
368          info.numTasks,                 // num
369          info.tids,                     // jpvmTaskId [ ]
370          48 );                          // heapSize
371        
372        LOGGER.trace ( "spawn successful" );
373
374        final jpvmBuffer  jpvmBufferInstance2 = new jpvmBuffer ( );
375        
376        // buf.pack(ba.length);   //just send the 
377        // buf.pack(ba, ba.length, 1);
378
379        jpvmBufferInstance2.pack ( info.numTasks );
380        
381        jpvmBufferInstance2.pack (
382          info.tids,
383          info.numTasks,
384          1 );
385        
386        jpvmBufferInstance2.pack ( simulatorParser.minDelay );
387
388        info.jpvm.pvm_mcast (
389          jpvmBufferInstance2,
390          info.tids,
391          info.numTasks,
392          NetMessageTag.sendTids );
393        
394        //send the different seed to the trialHost
395        /*
396        for(int i =0 ; i < info.numTasks; i++)
397        {
398          buf = new jpvmBuffer();
399          buf.pack(seedInt);
400          seedInt--;
401          info.jpvm.pvm_send(buf,info.tids[i],NetMessageTag.sendSeed);
402        }
403        */
404
405        LOGGER.trace ( "All sent" );
406
407        // generate all the nethosts
408        
409        info.endIndex = simulatorParser.layerStructure.nodeEndIndices;
410        
411        netJpvmTaskIds
412          = new jpvmTaskId [ info.numTasks ] [ info.endIndex.length ] ;
413
414        for ( int i = 0 ; i < info.numTasks; i++ )
415        {
416          LOGGER.trace ( "generate child for trialHost " + i );
417          
418          // Net Host is to separate large network into small pieces
419          
420          info.jpvm.pvm_spawn (
421            "cnslab.cnsnetwork.NetHost",
422            info.endIndex.length,
423            netJpvmTaskIds [ i ],
424            heapSize );
425          
426          final jpvmBuffer  jpvmBufferInstance = new jpvmBuffer ( );
427          
428          jpvmBufferInstance.pack ( info.endIndex.length );
429          
430          jpvmBufferInstance.pack (
431            netJpvmTaskIds [ i ],
432            info.endIndex.length,
433            1 );
434          
435          jpvmBufferInstance.pack (
436            info.endIndex,
437            info.endIndex.length,
438            1 );
439          
440          seedInt = seedInt - info.endIndex.length;
441          
442          jpvmBufferInstance.pack ( seedInt );
443          
444          // parent's TID
445          
446          jpvmBufferInstance.pack ( info.tids [ i ] );
447          
448          jpvmBufferInstance.pack ( ba.length );
449          
450          jpvmBufferInstance.pack ( ba, ba.length, 1 );
451          
452          info.jpvm.pvm_mcast (
453            jpvmBufferInstance,
454            netJpvmTaskIds [ i ],
455            info.endIndex.length,
456            NetMessageTag.sendTids );
457        }
458
459        for ( int i = 0; i < info.numTasks; i++ )
460        {
461          final jpvmBuffer  jpvmBufferInstance = new jpvmBuffer ( );
462          
463          jpvmBufferInstance.pack ( info.endIndex.length );
464          
465          jpvmBufferInstance.pack (
466            netJpvmTaskIds [ i ],
467            info.endIndex.length,
468            1 );
469          
470          // send trial Host the child TIDs
471          
472          info.jpvm.pvm_send (
473            jpvmBufferInstance,
474            info.tids [ i ],
475            NetMessageTag.sendTids2 );
476        }
477
478        aliveHost = info.numTasks;
479        
480        totalTrials = 0;
481        
482        for ( int  j = 0; j < experiment.subExp.length; j++ )
483        {
484          totalTrials += experiment.subExp [ j ].repetition;
485        }
486
487        totalTrials = totalTrials * simulatorParser.numOfHosts;
488        
489        intraReceiver = new LinkedList [
490            experiment.recorder.intraEle.size ( ) * experiment.subExp.length ];
491
492        /*
493        HashMap<String, Integer> multiCounter
494          = new HashMap<String, Integer>(); // don't consider trials
495          
496        HashMap<String, Integer> multiCounterAll
497          = new HashMap<String, Integer>(); // considering separate trials
498
499        HashMap<String, Integer> fieldCounter
500          = new HashMap<String, Integer>();
501          // different time section , neuron 
502
503        HashMap<String, Double> vectorCounterX
504          = new HashMap<String, Double>();
505          // different time section , neuron for X axis
506         
507        HashMap<String, Double> vectorCounterY
508          = new HashMap<String, Double>();
509          // different time section , neuron for Y axis
510        */
511
512        boolean  stop = false;
513
514        // Barrier Sync
515        
516        for (
517          int i = 0;
518          i < info.numTasks * info.endIndex.length + info.numTasks;
519          i++ )
520        {
521          // Receive a message...
522          
523          final jpvmMessage
524            message = info.jpvm.pvm_recv ( NetMessageTag.readySig );
525          
526          // Unpack the message...
527          
528          final String  str = message.buffer.upkstr ( );
529          
530          LOGGER.trace ( str );
531        }
532        
533        /*
534        for(int i = 0 ; i < info.numTasks; i++)
535        {
536          info.jpvm.pvm_mcast (
537            buf,
538            netTids[i],
539            info.endIndex.length,
540            NetMessageTag.readySig );
541        }
542        */
543        
544        //info.jpvm.pvm_mcast(
545        //  buf,info.tids,info.numTasks,NetMessageTag.readySig);
546        
547        //Barrier Sync
548        
549        final long
550          estimateTime1 = System.currentTimeMillis ( ) - simulationStartTime;
551        
552        LOGGER.trace ( String.format (
553          "****** Simulation is starting --- %dm:%ds"
554          + " was spent for connection\n",
555          new Long ( estimateTime1 / 60000 ),
556          new Long ( ( estimateTime1 % 60000 ) / 1000 ) ) );
557        
558        // LOGGER.trace(
559        //   "************ simulation is starting *********************");
560        
561        // 5 seconds 
562        
563        toDo = new ToDo ( 5 );
564
565        per = new double [ info.numTasks ];
566        
567        eeId = new int [ info.numTasks ];
568        
569        ttId = new int [ info.numTasks ];
570
571        countDis = 0;
572        
573        countHosts = 0;
574
575        while ( !stop )
576        {
577          // receive info from others
578          
579          final jpvmMessage  m = info.jpvm.pvm_recv ( );
580          
581          switch ( m.messageTag )
582          {
583            case NetMessageTag.checkTime:
584              
585              processCheckTime ( m );              
586              
587              break;
588              
589            case NetMessageTag.trialReady:
590              
591              processTrialReady ( m );              
592              
593              break;
594              
595            case NetMessageTag.getBackData:
596              
597              processBackData ( m );
598              
599              break;
600              
601            case NetMessageTag.trialDone:
602              
603              processTrialDone ( m );
604              
605              break;
606          }
607          
608          //  LOGGER.trace("alive hosts"+aliveHost);
609
610          if ( aliveHost   == 0
611            && totalTrials == 0 ) 
612          {
613            stop = true;
614            
615            break;
616          }
617        }
618
619        LOGGER.trace ( "Recording and exiting" );
620        
621        System.gc ( );
622        
623        for ( int  j = 0; j < experiment.subExp.length; j++ )
624        {
625          for ( int  k = 0; k < experiment.recorder.intraEle.size ( ); k++ )
626          {
627            final LinkedList<IntraInfo>  currList
628              = intraReceiver [ k + j * experiment.recorder.intraEle.size ( ) ];
629            
630            final Iterator<IntraInfo>  intraData = currList.iterator ( );
631            
632            while ( intraData.hasNext ( ) )
633            {
634              intraData.next ( ).divide (
635                experiment.subExp [ j ].repetition
636                  * ( experiment.recorder.intraEle.get ( k ).size ( ) ) );
637            }
638          }
639        }
640
641        final RecWriter  recWriter = new RecWriter (
642          experiment,
643          simulatorParser,
644          intraReceiver,
645          recorderData );
646        
647        //      Thread.sleep(0);
648        
649        //network.ncfile.close();
650        
651        LOGGER.trace ( "\n" );
652
653        if ( !experiment.recorder.outputFile.equals ( "" ) )
654        {
655          LOGGER.trace (
656            "output to file "
657              + RESULTS_DIR_PREFIX
658              + experiment.recorder.outputFile );
659          
660          final RecorderData  outputRecorderData = new RecorderData ( );
661          
662          // TODO:  Is this necessary?
663          
664          RecorderDataLib.insertExperimentRecorderDataIntoRecorderData (
665            outputRecorderData,
666            experiment,
667            recorderData );
668          
669          final File
670            binaryFile = new File (
671              RESULTS_DIR,
672              experiment.recorder.outputFile ); 
673          
674          RecorderDataLib.writeRecorderDataToBinaryFile (
675            outputRecorderData,
676            binaryFile );
677        }
678        else
679        {
680          recWriter.record ( simulatorParser.outFile );
681          
682          PlotResult.init ( RESULTS_DIR_PREFIX + simulatorParser.outFile );
683          
684          if ( experiment.recorder.plot )
685          {
686            // plot is allowed
687            
688            PlotResult.suPlot ( );
689            
690            PlotResult.muPlot ( );
691            
692            PlotResult.fieldPlot ( );
693            
694            PlotResult.vectorPlot ( );
695            
696            PlotResult.intraPlot ( );
697            
698            // PlotResult.exportFile ( );
699          }
700          
701          PlotResult.stop ( );
702        }
703        
704        /*
705      String filename = "results/datainput";
706      FileOutputStream fos = null;
707      ObjectOutputStream out = null;
708      try {
709
710        RecorderData outdata = new RecorderData();
711        for( int eId=0; eId<exp.subExp.length; eId++)
712        {
713          for( int tId=0; tId <exp.subExp[eId].repetition; tId++)
714          {
715            for( int sID= 0; sID < exp.rec.singleUnit.size(); sID++) 
716            {
717              outdata.receiver.put(
718                "Exp"+eId+"Tri"+tId+"/"+exp.rec.suNames.get(sID),
719                rdata.receiver.get(
720                  "E"+eId+"T"+tId+"N"+exp.rec.singleUnit.get(sID)));
721            }
722          }
723        }
724
725        fos = new FileOutputStream(filename);
726        out = new ObjectOutputStream(fos);
727        out.writeObject(outdata);
728        out.close();
729        LOGGER.trace("Object Persisted");
730        } catch (IOException ex) {
731          ex.printStackTrace();
732        }
733        */
734
735        final long
736          estimateTime2 = System.currentTimeMillis ( ) - simulationStartTime;
737        
738        LOGGER.trace ( String.format (
739          "****** Simulation is done --- %dm:%ds was "
740            + "spent for the whole simulation\n",
741          new Long ( estimateTime2 / 60000 ),
742          new Long ( ( estimateTime2 % 60000 ) / 1000 ) ) );
743        
744        info.jpvm.pvm_exit ( );
745      } 
746      catch ( final jpvmException  jpe )
747      {
748        LOGGER.error ( "Error - mainhost jpvm exception" );
749        
750        LOGGER.error ( jpe.toString ( ) );
751      }
752      catch ( final Exception  a )
753      {
754        a.printStackTrace ( );
755      }
756    }
757    
758    ////////////////////////////////////////////////////////////////////////
759    // private methods
760    ////////////////////////////////////////////////////////////////////////
761    
762    private void  processBackData (
763      final jpvmMessage  jpvmMessageInstance )
764      throws jpvmException
765    ////////////////////////////////////////////////////////////////////////
766    {
767      countHosts++;
768
769      if ( countHosts == info.endIndex.length )
770      {
771        aliveHost--;
772
773        countHosts = 0;
774      }
775
776      // LOGGER.trace("Receiving data from ");
777
778      final RecorderData
779        spikes = ( RecorderData ) jpvmMessageInstance.buffer.upkcnsobj ( );
780
781      // LOGGER.trace(m.buffer.upkint()+"\n");
782
783      // combine for single unit
784
785      final Set<Map.Entry<String, LinkedList<Double>>>
786        entries1 = spikes.receiver.entrySet ( );
787
788      final Iterator<Map.Entry<String, LinkedList<Double>>>
789        entryIter1 = entries1.iterator ( );
790
791      while ( entryIter1.hasNext ( ) )
792      {
793        final Map.Entry<String, LinkedList<Double>>
794          entry = entryIter1.next ( );
795
796        // Get the key from the entry.
797
798        final String  key = entry.getKey ( );
799
800        // Get the value.
801
802        final LinkedList<Double>  value = entry.getValue ( );
803
804        LinkedList<Double>
805          tmp1 = recorderData.receiver.get ( key );
806
807        if ( tmp1 == null )
808        {
809          recorderData.receiver.put (
810            key,
811            tmp1 = ( new LinkedList<Double> ( ) ) );
812        }
813
814        //put received info into memory
815        //if( spike.time !=0.0 ) tmp.add(spike.time);
816        
817        // put received info into memory
818        
819        tmp1.addAll(value);
820      }
821
822      ///combine for multi unit
823
824      final Set<Map.Entry<String, Integer>>
825        entries2 = spikes.multiCounter.entrySet ( );
826
827      final Iterator<Map.Entry<String, Integer>>
828        entryIter2 = entries2.iterator();
829
830      while (entryIter2.hasNext())
831      {
832        final Map.Entry<String, Integer>
833          entry = entryIter2.next ( );
834        
835        // Get the key from the entry.
836
837        final String key = entry.getKey();
838        
839        // Get the value.
840
841        final Integer value = entry.getValue();
842
843        Integer  tmp2 = recorderData.multiCounter.get ( key );
844
845        if ( tmp2 == null)
846        {
847          recorderData.multiCounter.put (
848            key,
849            tmp2 = ( new Integer ( 0 ) ) );
850        }
851
852        tmp2 += value;
853
854        recorderData.multiCounter.put (
855          key,
856          tmp2 );
857      }
858
859      final Set<Map.Entry<String, Integer>>
860        entries3 = spikes.multiCounterAll.entrySet();
861
862      final Iterator<Map.Entry<String, Integer>>
863        entryIter3 = entries3.iterator ( );
864
865      while ( entryIter3.hasNext ( ) )
866      {
867        final Map.Entry<String, Integer>
868          entry = entryIter3.next ( );
869        
870        // Get the key from the entry.
871
872        final String  key = entry.getKey ( );
873        
874        // Get the value.
875
876        final Integer  value = entry.getValue ( );
877
878        Integer  tmp3 = recorderData.multiCounterAll.get ( key );
879
880        if ( tmp3 == null )
881        {
882          recorderData.multiCounterAll.put (
883            key,
884            tmp3 = ( new Integer ( 0 ) ) );
885        }
886
887        tmp3 += value;
888
889        recorderData.multiCounterAll.put (
890          key,
891          tmp3 );
892      }
893
894      //combine for field ele
895
896      final Set<Map.Entry<String, Integer>>
897        entries4 = spikes.fieldCounter.entrySet ( );
898
899      final Iterator<Map.Entry<String, Integer>>
900        entryIter4 = entries4.iterator ( );
901
902      while ( entryIter4.hasNext ( ) )
903      {
904        final Map.Entry<String, Integer>
905          entry = entryIter4.next ( );
906
907        // Get the key from the entry.
908
909        final String  key = entry.getKey ( );
910
911        // LOGGER.trace(key);
912
913        // Get the value.
914
915        final Integer  value = entry.getValue ( );
916
917        Integer  tmp4 = recorderData.fieldCounter.get ( key );
918
919        if ( tmp4 == null )
920        {
921          recorderData.fieldCounter.put (
922            key,
923            tmp4 = ( new Integer ( 0 ) ) );
924        }
925
926        tmp4 += value;
927
928        recorderData.fieldCounter.put (
929          key,
930          tmp4 );
931      }
932
933      //combine for vector ele
934
935      final Set<Map.Entry<String, Double>>
936        entries5 = spikes.vectorCounterX.entrySet ( );
937
938      final Iterator<Map.Entry<String, Double>>
939        entryIter5 = entries5.iterator ( );
940
941      while  ( entryIter5.hasNext ( ) )
942      {
943        final Map.Entry<String, Double>
944          entry = entryIter5.next ( );
945        
946        // Get the key from the entry.
947
948        final String  key = entry.getKey ( );
949        
950        // Get the value.
951
952        final Double  value = entry.getValue();
953
954        Double  tmp5 = recorderData.vectorCounterX.get ( key );
955
956        if ( tmp5 == null )
957        {
958          recorderData.vectorCounterX.put (
959            key,
960            tmp5 = ( new Double ( 0.0 ) ) );
961        }
962
963        tmp5 += value;
964
965        recorderData.vectorCounterX.put (
966          key,
967          tmp5 );
968      }
969
970      final Set<Map.Entry<String, Double>>
971        entries6 = spikes.vectorCounterY.entrySet ( );
972
973      final Iterator<Map.Entry<String, Double>>
974        entryIter6 = entries6.iterator ( );
975
976      while ( entryIter6.hasNext ( ) )
977      {
978        final Map.Entry<String, Double>
979          entry = entryIter6.next ( );
980        
981        // Get the key from the entry.
982
983        final String  key = entry.getKey ( );
984        
985        // Get the value.
986
987        final Double value = entry.getValue ( );
988
989        Double  tmp6 = recorderData.vectorCounterY.get ( key );
990
991        if ( tmp6 == null )
992        {
993          recorderData.vectorCounterY.put (
994            key,
995            tmp6 = ( new Double ( 0.0 ) ) );
996        }
997
998        tmp6 += value;
999
1000        recorderData.vectorCounterY.put (
1001          key,
1002          tmp6 );
1003      }
1004    }
1005    
1006    private void  processCheckTime (
1007      final jpvmMessage  jpvmMessageInstance )
1008      throws jpvmException
1009    ////////////////////////////////////////////////////////////////////////
1010    {
1011      countDis++;
1012      
1013      int hostId = jpvmMessageInstance.buffer.upkint();
1014      
1015      int eId = jpvmMessageInstance.buffer.upkint();
1016      
1017      double root_time = jpvmMessageInstance.buffer.upkdouble();
1018      
1019      int tId = jpvmMessageInstance.buffer.upkint();
1020      
1021      per [ hostId ]
1022        = root_time / experiment.subExp [ eId ].trialLength * 100;
1023      
1024      eeId [ hostId ] = eId;
1025      
1026      ttId [ hostId ] = tId;
1027      
1028      if(countDis == info.numTasks)
1029      {
1030        countDis=0;
1031        
1032        for ( int ii=0; ii < info.numTasks; ii++ )
1033        {
1034          LOGGER.trace ( String.format (
1035            "E%dT%d: %.1f%% ",
1036            new Integer ( eeId [ ii ] ),
1037            new Integer ( ttId [ ii ] ),
1038            new Double  ( per  [ ii ] ) ) );
1039        }
1040      }
1041    }
1042    
1043    private void  processTrialDone (
1044      final jpvmMessage  jpvmMessageInstance )
1045      throws jpvmException
1046    ////////////////////////////////////////////////////////////////////////
1047    {
1048      totalTrials--;
1049      
1050      int res_trial = jpvmMessageInstance.buffer.upkint ( );
1051      
1052      int res_exp = jpvmMessageInstance.buffer.upkint ( );
1053      
1054      //  LOGGER.trace("R: "+"E"+res_exp+"T"+res_trial);
1055      //  RecordBuffer spikes = (RecordBuffer)m.buffer.upkcnsobj();
1056      
1057      final IntraRecBuffer
1058        intra = ( IntraRecBuffer ) jpvmMessageInstance.buffer.upkcnsobj ( );
1059      
1060      //      LOGGER.trace(intra);
1061      //  int totalsize = spikes.buff.size();
1062      //  int n =0;
1063
1064      //  Iterator<NetRecordSpike> iter_spike
1065      //    = spikes.buff.iterator();
1066      //          LOGGER.trace("spikes"+spikes.buff.size());
1067      /*
1068      while(iter_spike.hasNext())
1069      {
1070      n++;
1071      if( (n%(totalsize/1000)) == 0)LOGGER.trace(
1072        "recording..."+(double)n/(double)totalsize+"\r");
1073      NetRecordSpike spike = iter_spike.next();
1074
1075      //single unit processing
1076      if(exp.rec.singleUnit.contains(spike.from))
1077      //if neuron is in single unit recorder
1078      {
1079
1080      LinkedList<Double> tmp = receiver.get(
1081        "E"+res_exp+"T"+res_trial+"N"+spike.from);
1082
1083      if(tmp == null)
1084      {
1085        receiver.put(
1086          "E"+res_exp+"T"+res_trial+"N"+spike.from,
1087          tmp=(new LinkedList<Double>()));
1088      }
1089      
1090      //put received info into memory
1091      //if( spike.time !=0.0 ) tmp.add(spike.time);
1092      
1093      tmp.add(spike.time); //put received info into memory
1094      
1095      //LOGGER.trace(
1096        "fire: time:"+spike.time+ " index:"+spike.from);
1097      }
1098      //multiple unit processing
1099      for(int mID = 0 ; mID < exp.rec.multiUnit.size(); mID++)
1100      {
1101        if(exp.rec.multiUnit.get(mID).contains(spike.from))
1102        {
1103          int binIndex = (int)(spike.time/exp.rec.timeBinSize);
1104          
1105          Integer tmpInt
1106            = multiCounter.get("E"+res_exp+"N"+mID+"B"+binIndex);
1107            
1108          if(tmpInt == null)
1109          {
1110            multiCounter.put(
1111              "E"+res_exp+"N"+mID+"B"+binIndex,
1112              tmpInt=(new Integer(0)));
1113          }
1114          
1115          tmpInt = tmpInt + 1;
1116          
1117          multiCounter.put(
1118            "E"+res_exp+"N"+mID+"B"+binIndex,
1119            tmpInt);
1120            
1121          Integer tmpIntAll = multiCounterAll.get(
1122            "E"+res_exp+"T"+res_trial+"N"+mID+"B"+binIndex);
1123            
1124          if(tmpIntAll == null)
1125          {
1126            multiCounterAll.put(
1127              "E"+res_exp+"T"+res_trial+"N"+mID+"B"+binIndex,
1128              tmpIntAll=(new Integer(0)));
1129          }
1130          
1131          tmpIntAll = tmpIntAll + 1;
1132          
1133          multiCounterAll.put(
1134            "E"+res_exp+"T"+res_trial+"N"+mID+"B"+binIndex,
1135            tmpIntAll);
1136        }
1137      }
1138      
1139      //field processing
1140      
1141      for(int fID = 0 ; fID < exp.rec.fieldEle.size(); fID++)
1142      {
1143        if ( pas.ls.celllayer_test (
1144          spike.from,
1145          exp.rec.fieldEle.get(fID).getPrefix(),
1146          exp.rec.fieldEle.get(fID).getSuffix()))
1147        {
1148          int [] xy  = pas.ls.celllayer_cordinate(
1149            spike.from,
1150            exp.rec.fieldEle.get(fID).getPrefix(),
1151            exp.rec.fieldEle.get(fID).getSuffix());
1152            
1153          int binIndex = (int)(spike.time/exp.rec.fieldTimeBinSize);
1154          
1155          Integer tmpInt = fieldCounter.get(
1156            "E"+res_exp+","+exp.rec.fieldEle.get(fID).getPrefix()
1157            + "," + xy[0] +"," +xy[1] +","
1158            + exp.rec.fieldEle.get(fID).getSuffix()
1159            + "," + "B" + binIndex );
1160              
1161          if(tmpInt == null)
1162          {
1163            fieldCounter.put(
1164              "E"+res_exp+","+exp.rec.fieldEle.get(fID)+","+xy[0]
1165              +","+xy[1]+","+exp.rec.fieldEle.get(fID).getSuffix()
1166              +","+"B"+binIndex, tmpInt=(new Integer(0)));
1167          }
1168          
1169          tmpInt = tmpInt + 1;
1170          
1171          fieldCounter.put(
1172            "E"+res_exp+","+exp.rec.fieldEle.get(fID).getPrefix()
1173            +","+xy[0]+","+xy[1]+","
1174            +exp.rec.fieldEle.get(fID).getSuffix()+","+"B"
1175            +binIndex,
1176            tmpInt);
1177        }
1178      }
1179      //vector processing
1180      for(int vID = 0 ; vID < exp.rec.vectorUnit.size(); vID++)
1181      {
1182        for( int cID =0;
1183          cID < exp.rec.vectorUnit.get(vID).coms.size(); cID++)
1184        {
1185          if ( pas.ls.celllayer_test (
1186            spike.from,
1187            exp.rec.vectorUnit.get(vID)
1188              .coms.get(cID).layer.getPrefix(),
1189            exp.rec.vectorUnit.get(vID)
1190              .coms.get(cID).layer.getSuffix()))
1191          {
1192            int [] xy  = pas.ls.celllayer_cordinate(
1193              spike.from,exp.rec.vectorUnit.get(vID)
1194                .coms.get(cID).layer.getPrefix(),
1195              exp.rec.vectorUnit.get(vID)
1196                .coms.get(cID).layer.getSuffix());
1197                
1198            int binIndex
1199              = (int)(spike.time/exp.rec.vectorTimeBinSize);
1200              
1201            Double tmpDX = vectorCounterX.get(
1202              "E"+res_exp+"V"+vID+"B"+binIndex+"C"+xy[0]+","+xy[1]);
1203              
1204            Double tmpDY = vectorCounterY.get(
1205              "E"+res_exp+"V"+vID+"B"+binIndex+"C"+xy[0]+","+xy[1]);
1206
1207            if(tmpDX == null)
1208            {
1209              vectorCounterX.put (
1210                "E"+res_exp+"V"+vID+"B"+binIndex+"C"+xy[0]+","
1211                  +xy[1],
1212                tmpDX=(new Double(0.0)));
1213                
1214              vectorCounterY.put (
1215                "E"+res_exp+"V"+vID+"B"+binIndex+"C"+xy[0]+","
1216                  +xy[1],
1217                tmpDY=(new Double(0.0)));
1218            }
1219
1220            tmpDX = tmpDX + Math.cos(
1221              Math.PI/180.0*(double)exp.rec.vectorUnit.get(vID)
1222                .coms.get(cID).orientation);
1223                
1224            tmpDY = tmpDY + Math.sin(
1225              Math.PI/180.0*(double)exp.rec.vectorUnit.get(vID)
1226                .coms.get(cID).orientation);
1227                
1228            vectorCounterX.put(
1229              "E"+res_exp+"V"+vID+"B"+binIndex+"C"+xy[0]+","+xy[1],
1230              tmpDX);
1231              
1232            vectorCounterY.put (
1233              "E"+res_exp+"V"+vID+"B"+binIndex+"C"+xy[0]+","+xy[1],
1234              tmpDY);
1235            }
1236          }
1237        }
1238      }
1239      */
1240
1241      for ( int  i = 0; i < intra.neurons.length; i++ )
1242      {
1243        final int  neu = intra.neurons [ i ];
1244        
1245        final int  eleId = experiment.recorder.intraIndex ( neu );
1246        
1247        final LinkedList<IntraInfo>  info = intra.buff.get ( i );
1248        
1249        final int
1250          index = eleId + res_exp * experiment.recorder.intraEle.size ( );
1251        
1252        final LinkedList<IntraInfo>  currList = intraReceiver [ index ];
1253        
1254        if ( currList != null )
1255        {
1256          final Iterator<IntraInfo>  intraData = info.iterator ( );
1257          
1258          final Iterator<IntraInfo>  thisData = currList.iterator ( );
1259          
1260          while ( intraData.hasNext ( ) )
1261          {
1262            thisData.next ( ).plus ( intraData.next ( ) );
1263          }
1264        }
1265        else
1266        { 
1267          intraReceiver [ index ] = info;  
1268        }
1269      }
1270    }
1271    
1272    private void  processTrialReady (
1273      final jpvmMessage  jpvmMessageInstance )
1274      throws jpvmException
1275    ////////////////////////////////////////////////////////////////////////
1276    {
1277      // get free host id
1278      
1279      final int  freeId = jpvmMessageInstance.buffer.upkint ( );
1280      
1281      trialId++;
1282      
1283      if ( expId < experiment.subExp.length )
1284      {
1285        if ( trialId == experiment.subExp [ expId ].repetition )
1286        {
1287          trialId = 0;
1288          
1289          expId++;
1290        }
1291      }
1292      
1293      // game is still on
1294      
1295      if ( expId < experiment.subExp.length )
1296      {
1297        LOGGER.trace (
1298          "Subexp "    + expId
1299          + " trial "  + trialId
1300          + " freeId " + freeId );
1301
1302        final jpvmBuffer  jpvmBufferInstance = new jpvmBuffer ( );      
1303        
1304        jpvmBufferInstance.pack ( trialId );
1305        
1306        jpvmBufferInstance.pack ( expId );
1307        
1308        info.jpvm.pvm_send (
1309          jpvmBufferInstance,
1310          info.tids [ freeId ],
1311          NetMessageTag.oneTrial );
1312      }
1313      else if ( aliveHost != 0 )
1314      {
1315        // If all of the work is done and some hosts are not killed
1316        
1317        if ( toDo != null )
1318        {
1319          toDo.stop ( );
1320          
1321          toDo = null;
1322        }
1323
1324        LOGGER.trace ( "host " + freeId + " is killed" );
1325        
1326        final jpvmBuffer  jpvmBufferInstance = new jpvmBuffer ( );
1327        
1328        jpvmBufferInstance.pack ( 0 );
1329        
1330        info.jpvm.pvm_send (
1331          jpvmBufferInstance,
1332          info.tids [ freeId ],
1333          NetMessageTag.stopSig );
1334      }
1335    }
1336    
1337    ////////////////////////////////////////////////////////////////////////
1338    ////////////////////////////////////////////////////////////////////////
1339    }