001    package cnslab.cnsnetwork;
002    
003    import java.io.*;
004    import java.util.*;
005    import javax.xml.parsers.*;
006    import org.w3c.dom.*;
007    import org.xml.sax.*;    
008
009    import jpvm.*;
010    import org.slf4j.Logger;
011    import org.slf4j.LoggerFactory;
012
013    import cnslab.cnsmath.*;
014    import edu.jhu.mb.ernst.engine.DiscreteEvent;
015    import edu.jhu.mb.ernst.engine.DiscreteEventQueue;
016    import edu.jhu.mb.ernst.engine.EngineFactory;
017    import edu.jhu.mb.ernst.engine.factory.DefaultEngineFactoryImp;
018    import edu.jhu.mb.ernst.model.ModelFactory;
019    import edu.jhu.mb.ernst.model.ModulatedSynapse;
020    import edu.jhu.mb.ernst.model.Synapse;
021    import edu.jhu.mb.ernst.model.factory.DefaultModelFactoryImp;
022    import edu.jhu.mb.ernst.util.seq.ListSeq;
023    import edu.jhu.mb.ernst.util.seq.Seq;
024
025    /***********************************************************************
026    * Simulator Parser, to parse XML file  
027    * 
028    * @version
029    *   $Date: 2012-08-04 15:43:19 -0500 (Sat, 04 Aug 2012) $
030    *   $Rev: 117 $
031    *   $Author: jmcohen27 $
032    * @author
033    *   Yi Dong
034    * @author
035    *   David Wallace Croft, M.Sc.
036    * @author
037    *   Jeremy Cohen
038    ***********************************************************************/
039    public final class  SimulatorParser
040    ////////////////////////////////////////////////////////////////////////
041    ////////////////////////////////////////////////////////////////////////
042    {
043      
044    private static final Class<SimulatorParser>
045      CLASS = SimulatorParser.class;
046   
047    private static final Logger
048      LOGGER = LoggerFactory.getLogger ( CLASS );
049    
050    private static final EngineFactory
051      DEFAULT_ENGINE_FACTORY = DefaultEngineFactoryImp.INSTANCE;
052    
053    private static final ModelFactory
054      DEFAULT_MODEL_FACTORY = DefaultModelFactoryImp.INSTANCE;
055    
056    private static final String
057      NUMBER_DOES_NOT_MATCH = "number does not match";
058    
059    //
060   
061    public PrintStream  p;
062
063    //  public boolean connected;
064
065    /** minimum synaptic delay */
066    public double  minDelay;
067
068    public Experiment  experiment;
069
070    /** Layer structure */
071    public LayerStructure
072      layerStructure;
073    
074    /** seed number */
075    public Seed  idum;
076
077    /** length of xEdge */
078    public int  xEdgeLength;
079    
080    /** length of yEdge */
081    public int  yEdgeLength;
082
083    /** number of Hosts; */
084    public int  numOfHosts;
085
086    /** cell map type abmap or linemap */
087    public int  mapType;
088
089    /** number of parallel hosts */
090    public int  parallelHost;
091
092    public int
093      aSec,
094      bSec;
095
096    /** background firing rate */
097    public double  backgroundFrequency;
098    
099    /** background synaptic strength */
100    public double  backgroundStrength;
101    
102    /** background inputs channel */
103    public int  bChannel; 
104
105    /** output file name */
106    public String  outFile = "simExperiment.nc";
107
108    public Document  document;
109
110    public Element  rootElement;
111
112    public DocumentType  documentType;
113
114    /** Names of sub experiment */
115    public ArrayList<String>  subexpNames;
116
117    /** Model parameters */
118    public Map<String, Para>  modelParaMap;
119
120    /** Double Data defined in Data section of XML file */
121    public Map<String, Double>  doubleDataMap;
122    
123    /** Matrix Data defined in Data section of XML file */
124    public Map<String, double [ ] [ ]>  matrixDataMap;
125    
126    // private final instance variables
127    
128    private final List<ModulatedSynapse>
129      modulatedSynapseList = new ArrayList<ModulatedSynapse> ( );
130    
131    private final Seq<ModulatedSynapse>
132      modulatedSynapseSeq
133        = new ListSeq<ModulatedSynapse> ( modulatedSynapseList );
134    
135    // private non-final instance variables
136  
137    // TODO:  parse engineFactory and modelFactory class names from XML file
138    
139    private EngineFactory
140      engineFactory = DEFAULT_ENGINE_FACTORY;
141    
142    private ModelFactory
143      modelFactory = DEFAULT_MODEL_FACTORY;
144    
145    private DiscreteEventQueue
146      discreteEventQueue = engineFactory.createDiscreteEventQueue ( );
147    
148    ////////////////////////////////////////////////////////////////////////
149    // static methods
150    ////////////////////////////////////////////////////////////////////////
151      
152    public static void  main ( final String [ ]  args )
153      throws Exception
154    ////////////////////////////////////////////////////////////////////////
155    {
156      final SimulatorParser
157        simulatorParser = new SimulatorParser (
158          new Seed ( -3 ),
159          new File ( "model/testxml.xml" ) );
160      
161      // pas.parseMapCells();
162      
163      simulatorParser.parseMapCells ( 5 );
164      
165      System.out.println (
166        simulatorParser.layerStructure.base
167        + " "
168        + simulatorParser.layerStructure.neuron_end );
169      
170      simulatorParser.parsePopNeurons ( 5 );
171      
172      simulatorParser.parseConnection ( 5 );
173      
174      simulatorParser.parseExperiment ( );
175      
176      simulatorParser.findMinDelay ( );
177      
178      System.out.println ( simulatorParser.minDelay );
179
180      //System.out.println(pas.ls.neurons.length);
181      
182      /*
183      for(int i=0; i< pas.ls.neurons.length-1; i++)
184      {
185        System.out.println(pas.ls.neurons[i]);
186      }
187      */
188      
189      //for(int i=0; i< pas.ls.numberOfNeurons; i++)
190      //{
191      //  System.out.println(pas.ls.neurons[i]);
192      //}
193    }
194
195    ////////////////////////////////////////////////////////////////////////
196    // constructor methods
197    ////////////////////////////////////////////////////////////////////////
198    
199    public  SimulatorParser (
200      final Seed  idum,
201      final File  modelFile )
202    ////////////////////////////////////////////////////////////////////////
203    {
204      try 
205      {
206        System.setProperty (
207          "javax.xml.parsers.DocumentBuilderFactory",
208          "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl" );
209        
210        final DocumentBuilderFactory
211          documentBuilderFactory = DocumentBuilderFactory.newInstance ( );
212
213        documentBuilderFactory.setExpandEntityReferences ( true );
214        
215        documentBuilderFactory.setNamespaceAware ( true );
216        
217        documentBuilderFactory.setValidating ( true );
218        
219        documentBuilderFactory.setAttribute (
220          "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
221          "http://www.w3.org/2001/XMLSchema" );
222        
223        /*
224        try
225        {
226          dbf.setFeature (
227            "http://apache.org/xml/features/validation/schema",
228            true );
229            
230          dbf.setFeature (
231            "http://apache.org/xml/features/validation/"
232              + "schema-full-checking",
233            true );
234            
235          dbf.setFeature (
236            "http://xml.org/sax/features/validation",
237            true );
238        }
239        catch ( final Exception  e )
240        {
241          e.printStackTrace ( );
242        }
243        */
244
245        final DocumentBuilder
246          documentBuilder = documentBuilderFactory.newDocumentBuilder ( );
247
248        documentBuilder.setErrorHandler ( new SimpleErrorHandler ( ) );
249
250        document = documentBuilder.parse ( modelFile );
251        
252        rootElement = document.getDocumentElement ( );
253
254        rootElement.removeAttribute ( "xmlns:xsi" );
255        
256        rootElement.removeAttribute ( "xsi:schemaLocation" );
257
258        final DOMConfiguration
259          domConfiguration = document.getDomConfig ( );
260        
261        domConfiguration.setParameter (
262          "entities",
263          Boolean.FALSE );
264        
265        // config2.setParameter (
266        //   "schema-type",
267        //   "http://www.w3.org/2001/XMLSchema" );
268        //
269        // config2.setParameter (
270        //   "validate",
271        //   Boolean.TRUE );
272
273        documentType = document.getDoctype ( );
274
275        //doc = db.newDocument();
276        //DOMConfiguration config = doc.getDomConfig();
277        //config.setParameter("entities", Boolean.FALSE);
278        //Node dup = doc.importNode(root , true);
279        //doc.appendChild(dup);
280
281        // if(root==null) throw new RuntimeException("reading fails");
282        
283        modelParaMap = new HashMap<String, Para> ( );
284        
285        doubleDataMap = new HashMap<String, Double> ( );
286        
287        matrixDataMap = new HashMap<String, double [ ] [ ]> ( );
288
289        //ReferenceCheck();
290      }
291      catch ( final SAXParseException  err ) 
292      {
293        System.out.println (
294          "Error parsing line: " + err.getLineNumber ( ) );
295        
296        throw new RuntimeException ( err );
297      }
298      catch ( final SAXException  e )
299      {
300        System.out.println ( "Error parsing, SAXException thrown!" );
301        
302        throw new RuntimeException ( e );
303      }
304      catch ( final Throwable  t )
305      {
306// TODO:  Should probably not catch Throwable
307       
308        LOGGER.error (
309          t.getMessage ( ),
310          t );
311        
312        System.out.println ( "Error parsing, has to throw!" );
313        
314        t.printStackTrace ( );
315        
316        throw new RuntimeException ( t );
317      }
318
319      //  this.connected = false;
320      
321      this.idum = idum ;
322    }
323
324//    public  SimulatorParser (
325//      final Seed    idum,
326//      final String  modelFilename ) 
327//    //////////////////////////////////////////////////////////////////////
328//    {
329//      this ( idum, new File ( "model/" + modelFilename ) );
330//    }
331      
332    public SimulatorParser (
333      final Seed      idum,
334      final Document  doc ) 
335    ////////////////////////////////////////////////////////////////////////
336    {
337      modelParaMap = new HashMap<String, Para> ( );
338      
339      doubleDataMap = new HashMap<String, Double> ( );
340      
341      matrixDataMap = new HashMap<String, double [ ] [ ]> ( );
342      
343      this.document = doc;
344      
345      rootElement = doc.getDocumentElement ( );
346      
347      this.idum = idum ;
348      
349      // this.connected = false;
350    }
351
352    public  SimulatorParser ( )
353    ////////////////////////////////////////////////////////////////////////
354    {
355      //
356    }
357
358    ////////////////////////////////////////////////////////////////////////
359    ////////////////////////////////////////////////////////////////////////
360    
361    public DiscreteEventQueue  getDiscreteEventQueue ( )
362    ////////////////////////////////////////////////////////////////////////
363    {
364      return discreteEventQueue;
365    }
366    
367    public EngineFactory  getEngineFactory ( )
368    ////////////////////////////////////////////////////////////////////////
369    {
370      return engineFactory;
371    }
372    
373    public ModelFactory  getModelFactory ( )
374    ////////////////////////////////////////////////////////////////////////
375    {
376      return modelFactory;
377    }
378    
379    public Seq<ModulatedSynapse>  getModulatedSynapseSeq ( )
380    ////////////////////////////////////////////////////////////////////////
381    {
382      if ( modulatedSynapseSeq.size ( ) == 0 )
383      {
384        // TODO:  move this to init instead of lazy initialization
385        
386        populateModulatedSynapseSeq ( );
387      }
388      
389      return modulatedSynapseSeq;
390    }
391    
392    /***********************************************************************
393    * Check whether the XML file is valid or not 
394    ***********************************************************************/
395    public String  validate ( final String  modelFilename )
396    ////////////////////////////////////////////////////////////////////////
397    {
398      return validate ( new File ( "model/" + modelFilename ) );
399    }
400    
401    /***********************************************************************
402    * Check whether the XML file is valid or not 
403    ***********************************************************************/
404    public String  validate ( final File  modelFile )
405    ////////////////////////////////////////////////////////////////////////
406    {
407      String  tmp = "";
408      
409      try 
410      {
411        System.setProperty (
412          "javax.xml.parsers.DocumentBuilderFactory",
413          "org.apache.xerces.jaxp.DocumentBuilderFactoryImpl" );
414        
415        final DocumentBuilderFactory
416          dbf = DocumentBuilderFactory.newInstance ( );
417
418        dbf.setExpandEntityReferences ( true );
419        
420        dbf.setNamespaceAware ( true );
421        
422        dbf.setValidating ( true );
423       
424        dbf.setAttribute (
425          "http://java.sun.com/xml/jaxp/properties/schemaLanguage",
426          "http://www.w3.org/2001/XMLSchema" );
427        
428        /*
429        try
430        {
431          dbf.setFeature (
432            "http://apache.org/xml/features/validation/schema",
433            true );
434            
435          dbf.setFeature (
436            "http://apache.org/xml/features/validation/"
437              + "schema-full-checking",
438            true );
439            
440          dbf.setFeature (
441            "http://xml.org/sax/features/validation",
442            true );
443        }
444        catch ( final Exception  e )
445        {
446          e.printStackTrace ( );
447        }
448        */
449
450        final DocumentBuilder  db = dbf.newDocumentBuilder ( );
451
452        db.setErrorHandler ( new SimpleErrorHandler ( ) );
453
454        // System.out.println("1");
455        
456        document = db.parse ( modelFile );
457        
458        // System.out.println("2");
459
460        rootElement = document.getDocumentElement ( );
461
462        rootElement.removeAttribute ( "xmlns:xsi");
463        
464        rootElement.removeAttribute ( "xsi:schemaLocation" );
465
466        final DOMConfiguration  config2 = document.getDomConfig ( );
467        
468        config2.setParameter (
469          "entities",
470          Boolean.FALSE );
471        
472        // config2.setParameter (
473        //   "schema-type",
474        //   "http://www.w3.org/2001/XMLSchema" );
475        // config2.setParameter ("validate",Boolean.TRUE );
476
477        documentType = document.getDoctype ( );
478
479        modelParaMap = new HashMap<String,Para> ( );
480        
481        doubleDataMap = new HashMap<String,Double> ( );
482        
483        matrixDataMap = new HashMap<String,double [ ] [ ]> ( );
484
485        //  ReferenceCheck();
486      }
487      catch ( final SAXParseException  err )
488      {
489        LOGGER.error (
490          err.getMessage ( ),
491          err );
492        
493        tmp = tmp + "Error parsing line: " + err.getLineNumber ( ) + "\n";
494        
495        // System.exit(-1);
496      }
497      catch ( final SAXException  e )
498      {
499        LOGGER.error (
500          e.getMessage ( ),
501          e );
502        
503        tmp = tmp + "Error parsing, SAXException thrown!\n";
504        
505        //System.exit(-1);
506      }
507      catch ( final Throwable  t ) 
508      {
509// TODO:  Should probably not catch Throwable
510        
511        LOGGER.error (
512          t.getMessage ( ),
513          t );
514       
515        // System.out.println("Error parsing, has to throw!");
516        
517        // t.printStackTrace ( );
518        
519        // System.exit(-1);
520        
521        tmp = tmp + t.getMessage ( ) + "\n";
522      }
523      
524      return tmp;
525    }
526
527    /***********************************************************************
528    * Check XML reference is good or not
529    ***********************************************************************/
530    public void  referenceCheck ( )
531    ////////////////////////////////////////////////////////////////////////
532    {
533      // source in data section
534      
535      final Element
536        dataSec = getFirstElement ( rootElement, "ConstantDefinition" ),
537        neuDef  = getFirstElement ( rootElement, "NeuronDefinition" ),
538        laySec  = getFirstElement ( rootElement, "Layers" );
539
540      // first double
541      
542      final Set<String>
543        doubleIdDataSet = createDataSetFromAttributeValues (
544          dataSec,
545          "Double",
546          "id" );
547      
548      // check double
549      
550      checkDataSetContainsFirstGrandchildValues (
551        doubleIdDataSet,
552        rootElement,
553        "Strength",
554        "Ref",
555        " as strength is not defined in the data section" );      
556
557      checkDataSetContainsFirstGrandchildValues (
558        doubleIdDataSet,
559        rootElement,
560        "Delay",
561        "Ref",
562        " as delay is not defined in the data section" );      
563
564      final Set<String>
565        matrixIdDataSet = createDataSetFromAttributeValues (
566          dataSec,
567          "Matrix",
568          "id" );
569      
570      checkDataSetContainsFirstGrandchildValues (
571        matrixIdDataSet,
572        rootElement,
573        "Matrix",
574        "Ref",
575        " as matrix is not defined in the data section" );
576
577      // neuron type definition check
578      
579      final Set<String>
580        neuronTypeNameDataSet = createDataSetFromFirstChildValues (
581          neuDef,
582          "Name" );
583      
584      checkDataSetContainsFirstChildValues (
585        neuronTypeNameDataSet,
586        rootElement,
587        "NeuronType",
588        " as a neuron model is not defined in the NeuronDefinition"
589          + " section" );
590
591      // layer prefix check
592      
593      final Set<String>
594        layerPrefixDataSet = createDataSetFromFirstChildValues (
595          laySec,
596          "Prefix" );
597      
598      checkDataSetContainsAttributeValues (
599        layerPrefixDataSet,
600        rootElement,
601        "FromLayer",
602        "prefix",
603        " as layer prefix in FromLayer is not defined in the Layers "
604          + "section" );
605      
606      checkDataSetContainsAttributeValues (
607        layerPrefixDataSet,
608        rootElement,
609        "ToLayer",
610        "prefix",
611        " as layer prefix in ToLayer is not defined in the Layers "
612          + "section" );
613      
614      checkDataSetContainsAttributeValues (
615        layerPrefixDataSet,
616        rootElement,
617        "LayerOrientation",
618        "pre",
619        " as layer prefix in VectorMap is not defined in the Layers"
620          + " section" );
621      
622      checkDataSetContainsAttributeValues (
623        layerPrefixDataSet,
624        rootElement,
625        "Line",
626        "pre",
627        " as layer prefix in Recorder section is not defined in the "
628          + "Layers section" );
629
630      checkDataSetContainsAttributeValues (
631        layerPrefixDataSet,
632        rootElement,
633        "Square",
634        "pre",
635        " as layer prefix in Recorder section is not defined in the "
636          + "Layers section" );
637
638      checkDataSetContainsFirstChildValues (
639        layerPrefixDataSet,
640        rootElement,
641        "Prefix",
642        " as layer prefix name in Experiment or Recorder sections is"
643          + " not defined in the Layers section" );
644
645      // layer suffix check
646      
647      final Set<String>
648        layerSuffixDataSet = createDataSetFromFirstChildValues (
649          laySec,
650          "Suffix" );
651      
652      checkDataSetContainsAttributeValues (
653        layerSuffixDataSet,
654        rootElement,
655        "FromLayer",
656        "suffix",
657        " as layer suffix in FromLayer is not defined in the "
658          + "Layers section" );
659
660      checkDataSetContainsAttributeValues (
661        layerSuffixDataSet,
662        rootElement,
663        "ToLayer",
664        "suffix",
665        " as layer suffix in ToLayer is not defined in the "
666          + "Layers section" );
667
668      checkDataSetContainsAttributeValues (
669        layerSuffixDataSet,
670        rootElement,
671        "LayerOrientation",
672        "suf",
673        " as layer suffix in VectorMap is not defined in the "
674          + " Layers section" );
675
676      checkDataSetContainsAttributeValues (
677        layerSuffixDataSet,
678        rootElement,
679        "Line",
680        "suf",
681        " as layer suffix in Recorder section is not defined in the "
682          + "Layers section" );
683
684      checkDataSetContainsAttributeValues (
685        layerSuffixDataSet,
686        rootElement,
687        "Square",
688        "suf",
689        " as layer suffix in Recorder section is not defined in the "
690          + "Layers section" );
691      
692      checkDataSetContainsFirstChildValues (
693        layerSuffixDataSet,
694        rootElement,
695        "Suffix",
696        " as layer suffix name in Experiment or Recorder sections is "
697          + "not defined in the Layers section" );
698
699      // System.out.println ( "Reference check...........OK!" );
700    }
701
702    /***********************************************************************
703    * Parse the connection section, connect the neurons and build up the
704    * network structure
705    ***********************************************************************/
706// TODO:  Is this method used?  If so, finish cleanup and create unit tests.    
707    public double  parseConnection ( )
708      throws Exception
709    ////////////////////////////////////////////////////////////////////////
710    {
711      double  maxOutput = -1.0;
712      
713      final NodeList
714        connectionsNodeList
715          = rootElement.getElementsByTagName ( "Connections" );
716      
717      final Element
718        connectionsElement = ( Element ) connectionsNodeList.item ( 0 );
719
720      // read layers
721      
722      // loop connections
723      
724      final NodeList  lConnectionNodeList
725        = connectionsElement.getElementsByTagName ( "LConnection" );
726      
727      final int
728        lConnectionNodeListLength = lConnectionNodeList.getLength ( );
729      
730      // add all the layers
731      
732      for ( int  it = 0; it < lConnectionNodeListLength; it++ )
733      {
734        final Element
735          lConnectionElement = ( Element ) lConnectionNodeList.item ( it );
736        
737        int  max = 1;
738        
739        final NodeList  fromLayerNodeList
740          = lConnectionElement.getElementsByTagName ( "FromLayer" );
741        
742        if ( fromLayerNodeList.getLength ( ) != 1 )
743        {
744          max = fromLayerNodeList.getLength ( );
745        }
746        
747        final NodeList  toLayerNodeList
748          = lConnectionElement.getElementsByTagName ( "ToLayer" );
749        
750        final int  toLayerNodeListLength = toLayerNodeList.getLength ( );
751        
752        if ( toLayerNodeListLength !=1
753          && max != 1
754          && toLayerNodeListLength != max )
755        {
756          throw new RuntimeException ( NUMBER_DOES_NOT_MATCH );
757        }
758        
759        if ( toLayerNodeListLength != 1 )
760        {
761          max = toLayerNodeListLength;
762        }
763        
764        final NodeList  matrixNodeList
765          = lConnectionElement.getElementsByTagName ( "Matrix" );
766        
767        final int  matrixNodeListLength = matrixNodeList.getLength ( );
768        
769        if ( matrixNodeListLength != 1
770          && max != 1
771          && matrixNodeListLength != max )
772        {
773          throw new RuntimeException ( "matrix " + matrixNodeListLength
774            + " max " + max + " " + NUMBER_DOES_NOT_MATCH );
775        }
776        
777        if ( matrixNodeListLength !=1 )
778        {
779          max = matrixNodeListLength;
780        }
781        
782        final NodeList
783          orientationNodeList
784            = lConnectionElement.getElementsByTagName ( "Rotation" );
785        
786        final int
787          orientationNodeListLength = orientationNodeList.getLength ( ); 
788        
789        if ( orientationNodeListLength !=1
790          && max != 1
791          && orientationNodeListLength != max )
792        {
793          throw new RuntimeException ( NUMBER_DOES_NOT_MATCH );
794        }
795        
796        if ( orientationNodeListLength != 1 )
797        {
798          max = orientationNodeListLength;
799        }
800        
801        final NodeList
802          styleNodeList
803            = lConnectionElement.getElementsByTagName ( "Style" );
804        
805        final int  styleNodeListLength = styleNodeList.getLength ( );
806        
807        if ( styleNodeListLength != 1
808          && max != 1
809          && styleNodeListLength != max )
810        {
811          throw new RuntimeException ( NUMBER_DOES_NOT_MATCH );
812        }
813        
814        if ( styleNodeListLength != 1 )
815        {
816          max = styleNodeListLength;
817        }
818        
819        final NodeList
820          typeNodeList
821            = lConnectionElement.getElementsByTagName ( "Type" );
822        
823        final int  typeNodeListLength = typeNodeList.getLength ( );
824        
825        if ( typeNodeListLength != 1
826          && max != 1
827          && typeNodeListLength != max )
828        {
829          throw new RuntimeException ( NUMBER_DOES_NOT_MATCH );
830        }
831        
832        if ( typeNodeListLength != 1 )
833        {
834          max = typeNodeListLength;
835        }
836        
837        NodeList str =  lConnectionElement.getElementsByTagName("Strength");
838        
839        if(str.getLength() !=1 && max !=1 && str.getLength() != max)
840          throw new RuntimeException(NUMBER_DOES_NOT_MATCH);
841        
842        if(str.getLength() !=1 ) max = str.getLength();
843        
844        NodeList multi =  lConnectionElement.getElementsByTagName(
845          "Multiplier");
846        
847        if(multi.getLength() !=1 && max !=1 && multi.getLength() != max)
848          throw new RuntimeException(NUMBER_DOES_NOT_MATCH);
849        
850        if(multi.getLength() !=1 ) max = multi.getLength();
851        
852        NodeList offset =  lConnectionElement.getElementsByTagName(
853          "Offset");
854        
855        if(offset.getLength() !=1 && max !=1 && offset.getLength() != max)
856          throw new RuntimeException(NUMBER_DOES_NOT_MATCH);
857        
858        if(offset.getLength() !=1 ) max = offset.getLength();
859        
860        NodeList delay =  lConnectionElement.getElementsByTagName("Delay");
861        
862        if(delay.getLength() !=1 && max !=1 && delay.getLength() != max)
863          throw new RuntimeException(NUMBER_DOES_NOT_MATCH);
864        
865        if(delay.getLength() !=1 ) max = delay.getLength();
866        
867        //      System.out.println("max"+max);
868
869        for(int i=0; i < max; i++)
870        {
871          Element lmatrix;
872          if(matrixNodeList.getLength()==max)
873          {
874            lmatrix = (Element)(matrixNodeList.item(i));
875          }
876          else
877          {
878            lmatrix = (Element)(matrixNodeList.item(0));
879          }
880          double [][] conMatrix;
881          if(lmatrix.getElementsByTagName("Ref").getLength()>0)
882          {
883            conMatrix = matrixDataMap.get(
884              lmatrix.getElementsByTagName("Ref")
885              .item(0).getFirstChild().getNodeValue());
886            
887            if(conMatrix == null)
888              throw new RuntimeException(
889                lmatrix.getElementsByTagName("Ref").item(0)
890                .getFirstChild().getNodeValue()
891                +" as a reference is not defined in Data Section");
892          }
893          else
894          {
895            NodeList rows = lmatrix.getElementsByTagName("Row");
896            String firstRow = rows.item(0).getFirstChild().getNodeValue();
897            String sep [] = firstRow.split("[a-z,\t ]");
898            //      System.out.println(sep.length);
899            conMatrix = new double [rows.getLength()][sep.length];
900            for(int colId=0; colId < sep.length; colId++)
901            {
902              conMatrix[0][colId]=Double.parseDouble(sep[colId]);
903            }
904
905            for( int rowId=1; rowId<rows.getLength(); rowId++)
906            {
907              firstRow = rows.item(rowId).getFirstChild().getNodeValue();
908              sep = firstRow.split("[a-z,\t ]");
909              for(int colId=0; colId < sep.length; colId++)
910              {
911                conMatrix[rowId][colId]=Double.parseDouble(sep[colId]);
912              }
913            }
914          }
915          /*
916      for(int ii=0; ii < conMatrix.length; ii++)
917      {
918        for(int jj=0 ; jj < conMatrix[0].length; jj++)
919        {
920          System.out.print(conMatrix[ii][jj]+" ");
921        }
922        System.out.println();
923      }
924           */
925
926
927          Element lrotation;
928          if(orientationNodeList.getLength()==max)
929          {
930            lrotation = (Element)(orientationNodeList.item(i));
931          }
932          else
933          {
934            lrotation = (Element)(orientationNodeList.item(0));
935          }
936
937          int rot = Integer.parseInt(
938            lrotation.getFirstChild().getNodeValue())/90;
939
940          if(rot>0)
941          {
942            for(int ii=0 ; ii< rot; ii++)
943            {
944              conMatrix = FunUtil.rRotate90(conMatrix);
945            }
946          }
947          else if(rot <0)
948          {
949            for(int ii=0 ; ii< -rot; ii++)
950            {
951              conMatrix = FunUtil.lRotate90(conMatrix);
952            }
953          }
954          //remeber to change the rows matrix. use rows
955          Element lfrom;
956          if(fromLayerNodeList.getLength()==max)
957          {
958            lfrom = (Element)(fromLayerNodeList.item(i));
959          }
960          else
961          {
962            lfrom = (Element)(fromLayerNodeList.item(0));
963          }
964          Element lto;
965          if(toLayerNodeList.getLength()==max)
966          {
967            lto = (Element)(toLayerNodeList.item(i));
968          }
969          else
970          {
971            lto = (Element)(toLayerNodeList.item(0));
972          }
973          Element lstyle;
974          if(styleNodeList.getLength()==max)
975          {
976            lstyle = (Element)(styleNodeList.item(i));
977          }
978          else
979          {
980            lstyle = (Element)(styleNodeList.item(0));
981          }
982
983          String sStyle =lstyle.getFirstChild().getNodeValue();
984          
985          final boolean  sty = parseVergenceStyle ( lstyle );
986          
987          Element ltype;
988          if(typeNodeList.getLength()==max)
989          {
990            ltype = (Element)(typeNodeList.item(i));
991          }
992          else
993          {
994            ltype = (Element)(typeNodeList.item(0));
995          }
996          
997          final int  iType = parseSynapseType ( ltype ); 
998
999          Element lstr;
1000          if(str.getLength()==max)
1001          {
1002            lstr = (Element)(str.item(i));
1003          }
1004          else
1005          {
1006            lstr = (Element)(str.item(0));
1007          }
1008
1009          Element lmulti;
1010          if(multi.getLength()==max)
1011          {
1012            lmulti = (Element)(multi.item(i));
1013          }
1014          else
1015          {
1016            lmulti = (Element)(multi.item(0));
1017          }
1018          Element loffset;
1019          if(offset.getLength()==max)
1020          {
1021            loffset = (Element)(offset.item(i));
1022          }
1023          else
1024          {
1025            loffset = (Element)(offset.item(0));
1026          }
1027          Element ldelay;
1028          if(delay.getLength()==max)
1029          {
1030            ldelay = (Element)(delay.item(i));
1031          }
1032          else
1033          {
1034            ldelay = (Element)(delay.item(0));
1035          }
1036          /*
1037      System.out.print(
1038        lfrom.getAttributeNode("prefix").getNodeValue()
1039        +" "+lfrom.getAttributeNode("suffix").getNodeValue()
1040        +" "+lto.getAttributeNode("prefix").getNodeValue()
1041        +" "+lto.getAttributeNode("suffix").getNodeValue());
1042      System.out.print(" "+sty);
1043      System.out.print(" "+lstr.getFirstChild().getNodeValue());
1044      System.out.print(" "+lmulti.getFirstChild().getNodeValue());
1045      System.out.print(" "+loffset.getFirstChild().getNodeValue());
1046      System.out.print(" "+ldelay.getFirstChild().getNodeValue());
1047      System.out.println();
1048           */
1049          /*
1050      for(int ii=0; ii < conMatrix.length; ii++)
1051      {
1052        for(int jj=0 ; jj < conMatrix[0].length; jj++)
1053        {
1054          System.out.print(conMatrix[ii][jj]+" ");
1055        }
1056        System.out.println();
1057      }
1058           */
1059
1060          // System.out.println(Double.parseDouble(
1061          //   ((Element)(nList.item(it)))
1062          //   .getElementsByTagName("Multiplier").item(0)
1063          //   .getFirstChild().getNodeValue()));
1064          // System.out.println(Double.parseDouble(
1065          //   ((Element)(nList.item(it)))
1066          //   .getElementsByTagName("Offset").item(0)
1067          //   .getFirstChild().getNodeValue()));
1068          // System.out.println(Double.parseDouble(
1069          //   ((Element)(nList.item(it)))
1070          //   .getElementsByTagName("Strength").item(0)
1071          //   .getFirstChild().getNodeValue())
1072          //   *Double.parseDouble(((Element)(nList.item(it)))
1073          //   .getElementsByTagName("Multiplier").item(0)
1074          //   .getFirstChild().getNodeValue())
1075          //   + Double.parseDouble(((Element)(nList.item(it)))
1076          //   .getElementsByTagName("Offset").item(0)
1077          //   .getFirstChild().getNodeValue()));
1078          //
1079          
1080          Double theStr;
1081          
1082          if(lstr.getElementsByTagName("Ref").getLength()>0)
1083          {
1084            theStr = doubleDataMap.get(lstr.getElementsByTagName("Ref")
1085              .item(0).getFirstChild().getNodeValue());
1086            
1087            if(theStr == null)
1088              throw new RuntimeException(
1089                lstr.getElementsByTagName("Ref").item(0).getFirstChild()
1090                .getNodeValue()
1091                +" as a reference is not defined in Data Section");
1092          }
1093          else
1094          {
1095            theStr = Double.parseDouble(
1096              lstr.getFirstChild().getNodeValue());
1097          }
1098          
1099          Double theDelay;
1100          
1101          if(ldelay.getElementsByTagName("Ref").getLength()>0)
1102          {
1103            theDelay = doubleDataMap.get(
1104              ldelay.getElementsByTagName("Ref").item(0)
1105              .getFirstChild().getNodeValue());
1106            
1107            if(theDelay == null)
1108              throw new RuntimeException(
1109                ldelay.getElementsByTagName("Ref").item(0)
1110                .getFirstChild().getNodeValue()
1111                +" as a reference is not defined in Data Section");
1112          }
1113          else
1114          {
1115            theDelay = Double.parseDouble(
1116              ldelay.getFirstChild().getNodeValue());
1117          }
1118
1119          double outVal;
1120          
1121          outVal = layerStructure.connect (
1122            lfrom.getAttributeNode("prefix").getNodeValue(),
1123            lfrom.getAttributeNode("suffix").getNodeValue(),
1124            lto.getAttributeNode("prefix").getNodeValue(),
1125            lto.getAttributeNode("suffix").getNodeValue(),
1126            sty,
1127            theStr*Double.parseDouble(
1128              lmulti.getFirstChild().getNodeValue())
1129              + Double.parseDouble(loffset.getFirstChild().getNodeValue()),
1130            iType,
1131            theDelay,
1132            conMatrix);
1133          if(outVal > maxOutput) maxOutput = outVal;
1134        }
1135      }
1136
1137      final NodeList  nList
1138        = connectionsElement.getElementsByTagName("Connection");
1139      
1140      for(int it= 0 ; it< nList.getLength(); it++) // add all the layers;
1141      {
1142        Element matrix = (Element)(((Element)(nList.item(it)))
1143          .getElementsByTagName("Matrix").item(0));
1144
1145        NodeList rows = matrix.getElementsByTagName("Row");
1146        
1147        String firstRow = rows.item(0).getFirstChild().getNodeValue();
1148        
1149        String sep [] = firstRow.split("[a-z,\t ]");
1150        
1151        //      System.out.println(sep.length);
1152        
1153        double [][] conMatrix = new double [rows.getLength()][sep.length];
1154        
1155        for(int colId=0; colId < sep.length; colId++)
1156        {
1157          conMatrix[0][colId]=Double.parseDouble(sep[colId]);
1158        }
1159
1160        for( int rowId=1; rowId<rows.getLength(); rowId++)
1161        {
1162          firstRow = rows.item(rowId).getFirstChild().getNodeValue();
1163          
1164          sep = firstRow.split("[a-z,\t ]");
1165          
1166          for(int colId=0; colId < sep.length; colId++)
1167          {
1168            conMatrix[rowId][colId]=Double.parseDouble(sep[colId]);
1169          }
1170        }
1171        /*
1172
1173      for(int ii=0; ii < conMatrix.length; ii++)
1174      {
1175        for(int jj=0 ; jj < conMatrix[0].length; jj++)
1176        {
1177          System.out.print(conMatrix[ii][jj]+" ");
1178        }
1179        System.out.println();
1180      }
1181         */
1182
1183        int rotation = Integer.parseInt (
1184          ((Element)(nList.item(it)))
1185          .getElementsByTagName("Rotation").item(0)
1186          .getFirstChild().getNodeValue())/90;
1187
1188        if(rotation>0)
1189        {
1190          for(int ii=0 ; ii< rotation; ii++)
1191          {
1192            conMatrix = FunUtil.rRotate90(conMatrix);
1193          }
1194        }
1195        else if(rotation <0)
1196        {
1197          for(int ii=0 ; ii< -rotation; ii++)
1198          {
1199            conMatrix = FunUtil.lRotate90(conMatrix);
1200          }
1201        }
1202        /*
1203
1204      for(int ii=0; ii < conMatrix.length; ii++)
1205      {
1206        for(int jj=0 ; jj < conMatrix[0].length; jj++)
1207        {
1208          System.out.print(conMatrix[ii][jj]+" ");
1209        }
1210        System.out.println();
1211      }
1212         */
1213
1214
1215        Element from = (Element)(((Element)(nList.item(it)))
1216          .getElementsByTagName("FromLayer").item(0));
1217        
1218        Element to  = (Element)(((Element)(nList.item(it)))
1219          .getElementsByTagName("ToLayer").item(0));
1220        
1221        final Element  styleElement = getFirstElement (
1222          ( Element ) nList.item ( it ),
1223          "Style " );
1224        
1225        final boolean  sty = parseVergenceStyle ( styleElement );
1226        
1227        //synaptic type  
1228        
1229        final Element  typeElement = getFirstElement (
1230          ( Element ) nList.item ( it ),
1231          "Type" );
1232
1233        final int  type = parseSynapseType ( typeElement );
1234        
1235        System.out.println(
1236          ((Element)(from.getElementsByTagName("Prefix").item(0)))
1237          .getFirstChild().getNodeValue()
1238          +" "
1239          + ((Element)(from.getElementsByTagName("Suffix").item(0)))
1240          .getFirstChild().getNodeValue()+" "
1241          + ((Element)(to.getElementsByTagName("Prefix").item(0)))
1242          .getFirstChild().getNodeValue()
1243          +" "
1244          + ((Element)(to.getElementsByTagName("Suffix").item(0)))
1245          .getFirstChild().getNodeValue());
1246        
1247        // System.out.println(sty);
1248        // System.out.println(Double.parseDouble(
1249        //   ((Element)(nList.item(it))).getElementsByTagName("Strength")
1250        //   .item(0).getFirstChild().getNodeValue()));
1251        // System.out.println(Double.parseDouble(
1252        //   ((Element)(nList.item(it))).getElementsByTagName("Multiplier")
1253        //   .item(0).getFirstChild().getNodeValue()));
1254        // System.out.println(Double.parseDouble(
1255        //   ((Element)(nList.item(it))).getElementsByTagName("Offset")
1256        //   .item(0).getFirstChild().getNodeValue()));
1257        // System.out.println(Double.parseDouble(
1258        //   ((Element)(nList.item(it))).getElementsByTagName("Strength")
1259        //   .item(0).getFirstChild().getNodeValue())
1260        //   *Double.parseDouble(((Element)(nList.item(it)))
1261        //   .getElementsByTagName("Multiplier").item(0)
1262        //   .getFirstChild().getNodeValue())
1263        //   + Double.parseDouble(((Element)(nList.item(it)))
1264        //   .getElementsByTagName("Offset").item(0)
1265        //   .getFirstChild().getNodeValue()));
1266        
1267        double outVal;
1268        
1269        outVal =  layerStructure.connect (
1270          ((Element)(from.getElementsByTagName("Prefix").item(0)))
1271            .getFirstChild().getNodeValue(),
1272          ((Element)(from.getElementsByTagName("Suffix").item(0)))
1273            .getFirstChild().getNodeValue(),
1274          ((Element)(to.getElementsByTagName("Prefix").item(0)))
1275            .getFirstChild().getNodeValue(),
1276          ((Element)(to.getElementsByTagName("Suffix").item(0)))
1277            .getFirstChild().getNodeValue(),
1278          sty,
1279          Double.parseDouble(((Element)(nList.item(it)))
1280            .getElementsByTagName("Strength").item(0).getFirstChild()
1281            .getNodeValue())
1282            *Double.parseDouble(((Element)(nList.item(it)))
1283            .getElementsByTagName("Multiplier").item(0)
1284            .getFirstChild().getNodeValue())
1285            + Double.parseDouble(((Element)(nList.item(it)))
1286            .getElementsByTagName("Offset").item(0)
1287            .getFirstChild().getNodeValue()),
1288          type,
1289          Double.parseDouble(((Element)(nList.item(it)))
1290            .getElementsByTagName("Delay").item(0).getFirstChild()
1291            .getNodeValue()),
1292          conMatrix);
1293        
1294        if(outVal > maxOutput) maxOutput = outVal;
1295      }
1296      
1297      return maxOutput;
1298    }
1299
1300    /***********************************************************************
1301    * Build the scaffold.
1302    * 
1303    * This method is called by NetHost.createSimulatorParser().
1304    ***********************************************************************/
1305    public void  parseScaffold ( final int  hostId )
1306      throws Exception
1307    ////////////////////////////////////////////////////////////////////////
1308    {
1309      // double  maxOutput = -1.0;
1310      
1311      final NodeList
1312        connectionsNodeList
1313          = rootElement.getElementsByTagName ( "Connections" );
1314      
1315      final Element
1316        connectionsElement = ( Element ) connectionsNodeList.item ( 0 );
1317
1318      // read layers loop connections
1319      
1320      // loop connections
1321      
1322      final NodeList  lConnectionNodeList
1323        = connectionsElement.getElementsByTagName ( "LConnection" );
1324      
1325      final int
1326        lConnectionNodeListLength = lConnectionNodeList.getLength ( );
1327      
1328      // add all the layers
1329      
1330      for ( int  it = 0; it < lConnectionNodeListLength; it++ )
1331      {
1332        final Element  lConnectionElement
1333          = ( Element ) lConnectionNodeList.item ( it );
1334        
1335        parseScaffoldWithPeriodic ( hostId, lConnectionElement );
1336      }
1337
1338      // read layers general loop connections
1339      
1340      // loop connections
1341      
1342      final NodeList  gConnectionNodeList
1343        = connectionsElement.getElementsByTagName ( "GConnection" );
1344      
1345      final int
1346        gConnectionNodeListLength = gConnectionNodeList.getLength ( );
1347      
1348      // add all the layers
1349      
1350      for ( int  it = 0; it < gConnectionNodeListLength; it++ )
1351      {
1352        final Element  gConnectionElement
1353          = ( Element ) gConnectionNodeList.item ( it );
1354        
1355        parseScaffold ( hostId, gConnectionElement );
1356      }
1357
1358      // read layers probability connections
1359      
1360      // loop connections
1361      
1362      final NodeList  pConnectionNodeList
1363        = connectionsElement.getElementsByTagName ( "PConnection" );
1364      
1365      final int
1366        pConnectionNodeListLength = pConnectionNodeList.getLength ( );
1367      
1368      // add all the layers
1369      
1370      for ( int  it = 0; it < pConnectionNodeListLength; it++ )
1371      {
1372        final Element  pConnectionElement
1373          = ( Element ) pConnectionNodeList.item ( it );
1374        
1375        parseScaffoldWithPeriodicAndStrengthMatrix (
1376          hostId,
1377          pConnectionElement );
1378      }
1379
1380      // read layers probability general connections
1381      
1382      // loop connections
1383      
1384      final NodeList  gpConnectionNodeList
1385        = connectionsElement.getElementsByTagName ( "GPConnection" );
1386      
1387      final int
1388        gpConnectionNodeListLength = gpConnectionNodeList.getLength ( );
1389      
1390      // add all the layers;
1391      
1392      for ( int  it = 0; it < gpConnectionNodeListLength; it++ )
1393      {
1394        final Element  connectionElement
1395          = ( Element ) gpConnectionNodeList.item ( it );
1396        
1397        parseScaffoldWithStrengthMatrix ( hostId, connectionElement );
1398      }
1399
1400      // read layers
1401
1402      final NodeList  connectionNodeList
1403        = connectionsElement.getElementsByTagName ( "Connection" );
1404      
1405      final int
1406        connectionNodeListLength = connectionNodeList.getLength ( );
1407      
1408      // add all the layers
1409      
1410      for ( int  it = 0; it < connectionNodeListLength; it++ )
1411      {
1412        final Element
1413          connectionElement = ( Element ) connectionNodeList.item ( it );
1414        
1415        parseScaffoldWithPeriodicAndSingleElement (
1416          hostId,
1417          connectionElement );
1418      }
1419    }
1420
1421    @Deprecated
1422    public double parseChangeConnection(int hostId) throws Exception
1423    ////////////////////////////////////////////////////////////////////////
1424    {
1425      layerStructure.reSetSeed();
1426      double maxOutput = -1.0;
1427      NodeList nList = rootElement.getElementsByTagName("Connections");
1428      Element conns = (Element) nList.item(0);
1429
1430      //read layers;
1431      nList = conns.getElementsByTagName("LConnection"); //loop connections
1432      for(int it= 0 ; it< nList.getLength(); it++) // add all the layers;
1433      {
1434        String perio = ((Element)(nList.item(it)))
1435          .getAttributeNode("periodic").getValue();
1436        boolean periodic;
1437        if(perio.equals("true") || perio.equals("TRUE"))
1438        {
1439          periodic = true;
1440        }
1441        else
1442        {
1443          periodic = false;
1444        }
1445
1446        int max=1;
1447        NodeList from =  ((Element)(nList.item(it)))
1448          .getElementsByTagName("FromLayer");
1449        if(from.getLength() !=1) max = from.getLength();
1450        NodeList to =  ((Element)(nList.item(it)))
1451          .getElementsByTagName("ToLayer");
1452        if(to.getLength() !=1 && max !=1 && to.getLength() != max)
1453          throw new RuntimeException("number does not match");
1454        if(to.getLength() !=1 ) max = to.getLength();
1455        NodeList matrix =  ((Element)(nList.item(it)))
1456          .getElementsByTagName("Matrix");
1457        if(matrix.getLength() !=1 && max !=1 && matrix.getLength() != max) 
1458          throw new RuntimeException("number does not match");
1459        if(matrix.getLength() !=1 ) max = matrix.getLength();
1460        NodeList orientation =  ((Element)(nList.item(it)))
1461          .getElementsByTagName("Rotation");
1462        if(orientation.getLength() !=1 && max !=1 
1463          && orientation.getLength() != max) 
1464          throw new RuntimeException("number does not match");
1465        if(orientation.getLength() !=1 ) max = orientation.getLength();
1466        NodeList style =  ((Element)(nList.item(it)))
1467          .getElementsByTagName("Style");
1468        if(style.getLength() !=1 && max !=1 && style.getLength() != max) 
1469          throw new RuntimeException("number does not match");
1470        if(style.getLength() !=1 ) max = style.getLength();
1471        NodeList type =  ((Element)(nList.item(it)))
1472          .getElementsByTagName("Type");
1473        if(type.getLength() !=1 && max !=1 && type.getLength() != max) 
1474          throw new RuntimeException("number does not match");
1475        if(type.getLength() !=1 ) max = type.getLength();
1476        NodeList str =  ((Element)(nList.item(it)))
1477          .getElementsByTagName("Strength");
1478        if(str.getLength() !=1 && max !=1 && str.getLength() != max) 
1479          throw new RuntimeException("number does not match");
1480        if(str.getLength() !=1 ) max = str.getLength();
1481        NodeList multi =  ((Element)(nList.item(it)))
1482          .getElementsByTagName("Multiplier");
1483        if(multi.getLength() !=1 && max !=1 && multi.getLength() != max) 
1484          throw new RuntimeException("number does not match");
1485        if(multi.getLength() !=1 ) max = multi.getLength();
1486        NodeList offset =  ((Element)(nList.item(it)))
1487          .getElementsByTagName("Offset");
1488        if(offset.getLength() !=1 && max !=1 && offset.getLength() != max) 
1489          throw new RuntimeException("number does not match");
1490        if(offset.getLength() !=1 ) max = offset.getLength();
1491        NodeList delay =  ((Element)(nList.item(it)))
1492          .getElementsByTagName("Delay");
1493        if(delay.getLength() !=1 && max !=1 && delay.getLength() != max) 
1494          throw new RuntimeException("number does not match");
1495        if(delay.getLength() !=1 ) max = delay.getLength();
1496        //      System.out.println("max"+max);
1497
1498        for(int i=0; i < max; i++)
1499        {
1500          Element lmatrix;
1501          if(matrix.getLength()==max)
1502          {
1503            lmatrix = (Element)(matrix.item(i));
1504          }
1505          else
1506          {
1507            lmatrix = (Element)(matrix.item(0));
1508          }
1509
1510
1511          double [][] conMatrix;
1512          if(lmatrix.getElementsByTagName("Ref").getLength()>0)
1513          {
1514            conMatrix = matrixDataMap.get(
1515              lmatrix.getElementsByTagName("Ref")
1516              .item(0).getFirstChild().getNodeValue());
1517            if(conMatrix == null) 
1518              throw new RuntimeException(
1519                lmatrix.getElementsByTagName("Ref").item(0)
1520                .getFirstChild().getNodeValue()
1521                +" as a reference is not defined in Data Section");
1522          }
1523          else
1524          {
1525            NodeList rows = lmatrix.getElementsByTagName("Row");
1526            String firstRow = rows.item(0).getFirstChild().getNodeValue();
1527            String sep [] = firstRow.split("[a-z,\t ]");
1528            //      System.out.println(sep.length);
1529            conMatrix = new double [rows.getLength()][sep.length];
1530            for(int colId=0; colId < sep.length; colId++)
1531            {
1532              conMatrix[0][colId]=Double.parseDouble(sep[colId]);
1533            }
1534
1535            for( int rowId=1; rowId<rows.getLength(); rowId++)
1536            {
1537              firstRow = rows.item(rowId).getFirstChild().getNodeValue();
1538              sep = firstRow.split("[a-z,\t ]");
1539              for(int colId=0; colId < sep.length; colId++)
1540              {
1541                conMatrix[rowId][colId]=Double.parseDouble(sep[colId]);
1542              }
1543            }
1544          }
1545
1546          Element lrotation;
1547          if(orientation.getLength()==max)
1548          {
1549            lrotation = (Element)(orientation.item(i));
1550          }
1551          else
1552          {
1553            lrotation = (Element)(orientation.item(0));
1554          }
1555
1556          int rot =Integer.parseInt(
1557            lrotation.getFirstChild().getNodeValue())/90;
1558
1559          if(rot>0)
1560          {
1561            for(int ii=0 ; ii< rot; ii++)
1562            {
1563              conMatrix = FunUtil.rRotate90(conMatrix);
1564            }
1565          }
1566          else if(rot <0)
1567          {
1568            for(int ii=0 ; ii< -rot; ii++)
1569            {
1570              conMatrix = FunUtil.lRotate90(conMatrix);
1571            }
1572          }
1573          //remeber to change the rows matrix. use rows
1574          Element lfrom;
1575          if(from.getLength()==max)
1576          {
1577            lfrom = (Element)(from.item(i));
1578          }
1579          else
1580          {
1581            lfrom = (Element)(from.item(0));
1582          }
1583          Element lto;
1584          if(to.getLength()==max)
1585          {
1586            lto = (Element)(to.item(i));
1587          }
1588          else
1589          {
1590            lto = (Element)(to.item(0));
1591          }
1592          Element lstyle;
1593          if(style.getLength()==max)
1594          {
1595            lstyle = (Element)(style.item(i));
1596          }
1597          else
1598          {
1599            lstyle = (Element)(style.item(0));
1600          }
1601          
1602          final boolean  sty = parseVergenceStyle ( lstyle );
1603
1604          Element ltype;
1605          if(type.getLength()==max)
1606          {
1607            ltype = (Element)(type.item(i));
1608          }
1609          else
1610          {
1611            ltype = (Element)(type.item(0));
1612          }
1613
1614          final int  iType = parseSynapseType ( ltype );
1615          
1616          Element lstr;
1617          
1618          if(str.getLength()==max)
1619          {
1620            lstr = (Element)(str.item(i));
1621          }
1622          else
1623          {
1624            lstr = (Element)(str.item(0));
1625          }
1626          Element lmulti;
1627          if(multi.getLength()==max)
1628          {
1629            lmulti = (Element)(multi.item(i));
1630          }
1631          else
1632          {
1633            lmulti = (Element)(multi.item(0));
1634          }
1635          Element loffset;
1636          if(offset.getLength()==max)
1637          {
1638            loffset = (Element)(offset.item(i));
1639          }
1640          else
1641          {
1642            loffset = (Element)(offset.item(0));
1643          }
1644          Element ldelay;
1645          if(delay.getLength()==max)
1646          {
1647            ldelay = (Element)(delay.item(i));
1648          }
1649          else
1650          {
1651            ldelay = (Element)(delay.item(0));
1652          }
1653          
1654          Double theStr;
1655          if(lstr.getElementsByTagName("Ref").getLength()>0)
1656          {
1657            theStr = doubleDataMap.get(lstr.getElementsByTagName("Ref")
1658              .item(0).getFirstChild().getNodeValue());
1659            if(theStr == null) 
1660              throw new RuntimeException(
1661                lstr.getElementsByTagName("Ref").item(0)
1662                .getFirstChild().getNodeValue()
1663                +" as a reference is not defined in Data Section");
1664          }
1665          else
1666          {
1667            theStr = Double.parseDouble(
1668              lstr.getFirstChild().getNodeValue());
1669          }
1670          
1671          Double theDelay;
1672          if(ldelay.getElementsByTagName("Ref").getLength()>0)
1673          {
1674            theDelay = doubleDataMap.get(
1675              ldelay.getElementsByTagName("Ref")
1676              .item(0).getFirstChild().getNodeValue());
1677            
1678            if(theDelay == null) 
1679              throw new RuntimeException(
1680                ldelay.getElementsByTagName("Ref").item(0)
1681                .getFirstChild().getNodeValue()
1682                +" as a reference is not defined in Data Section");
1683          }
1684          else
1685          {
1686            theDelay = Double.parseDouble(
1687              ldelay.getFirstChild().getNodeValue());
1688          }
1689
1690          double outVal;
1691          outVal=  layerStructure.changeConnection(
1692            lfrom.getAttributeNode("prefix").getNodeValue(),
1693            lfrom.getAttributeNode("suffix").getNodeValue(),
1694            lto.getAttributeNode("prefix").getNodeValue(),
1695            lto.getAttributeNode("suffix").getNodeValue(),
1696            sty,
1697            theStr*Double.parseDouble(
1698              lmulti.getFirstChild().getNodeValue())
1699              + Double.parseDouble(loffset.getFirstChild().getNodeValue()),
1700            iType,
1701            theDelay,
1702            conMatrix,
1703            hostId,
1704            periodic);
1705          if(outVal > maxOutput) maxOutput = outVal;
1706        }
1707      }
1708
1709      //read layers general loop connections;
1710      nList = conns.getElementsByTagName("GConnection"); //loop connections
1711      for(int it= 0 ; it< nList.getLength(); it++) // add all the layers;
1712      {
1713        int max=1;
1714        NodeList from =  ((Element)(nList.item(it)))
1715          .getElementsByTagName("FromLayer");
1716        if(from.getLength() !=1) max = from.getLength();
1717        NodeList to =  ((Element)(nList.item(it)))
1718          .getElementsByTagName("ToLayer");
1719        if(to.getLength() !=1 && max !=1 && to.getLength() != max) 
1720          throw new RuntimeException("number does not match");
1721        if(to.getLength() !=1 ) max = to.getLength();
1722        NodeList matrix =  ((Element)(nList.item(it)))
1723          .getElementsByTagName("Matrix");
1724        if(matrix.getLength() !=1 && max !=1 && matrix.getLength() != max) 
1725          throw new RuntimeException("number does not match");
1726        if(matrix.getLength() !=1 ) max = matrix.getLength();
1727        NodeList orientation =  ((Element)(nList.item(it)))
1728          .getElementsByTagName("Rotation");
1729        if(orientation.getLength() !=1 && max !=1 
1730          && orientation.getLength() != max) 
1731          throw new RuntimeException("number does not match");
1732        if(orientation.getLength() !=1 ) max = orientation.getLength();
1733
1734        NodeList type =  ((Element)(nList.item(it)))
1735          .getElementsByTagName("Type");
1736        if(type.getLength() !=1 && max !=1 && type.getLength() != max) 
1737          throw new RuntimeException("number does not match");
1738        if(type.getLength() !=1 ) max = type.getLength();
1739        NodeList str =  ((Element)(nList.item(it)))
1740          .getElementsByTagName("Strength");
1741        if(str.getLength() !=1 && max !=1 && str.getLength() != max) 
1742          throw new RuntimeException("number does not match");
1743        if(str.getLength() !=1 ) max = str.getLength();
1744        NodeList multi =  ((Element)(nList.item(it)))
1745          .getElementsByTagName("Multiplier");
1746        if(multi.getLength() !=1 && max !=1 && multi.getLength() != max) 
1747          throw new RuntimeException("number does not match");
1748        if(multi.getLength() !=1 ) max = multi.getLength();
1749        NodeList offset =  ((Element)(nList.item(it)))
1750          .getElementsByTagName("Offset");
1751        if(offset.getLength() !=1 && max !=1 && offset.getLength() != max) 
1752          throw new RuntimeException("number does not match");
1753        if(offset.getLength() !=1 ) max = offset.getLength();
1754        NodeList delay =  ((Element)(nList.item(it)))
1755          .getElementsByTagName("Delay");
1756        if(delay.getLength() !=1 && max !=1 && delay.getLength() != max) 
1757          throw new RuntimeException("number does not match");
1758        if(delay.getLength() !=1 ) max = delay.getLength();
1759        //      System.out.println("max"+max);
1760
1761        for(int i=0; i < max; i++)
1762        {
1763          Element lmatrix;
1764          if(matrix.getLength()==max)
1765          {
1766            lmatrix = (Element)(matrix.item(i));
1767          }
1768          else
1769          {
1770            lmatrix = (Element)(matrix.item(0));
1771          }
1772
1773          double [][] conMatrix;
1774          if(lmatrix.getElementsByTagName("Ref").getLength()>0)
1775          {
1776            conMatrix = matrixDataMap.get(
1777              lmatrix.getElementsByTagName("Ref").item(0)
1778              .getFirstChild().getNodeValue());
1779            if(conMatrix == null) 
1780              throw new RuntimeException(
1781                lmatrix.getElementsByTagName("Ref").item(0)
1782                .getFirstChild().getNodeValue()
1783                +" as a reference is not defined in Data Section");
1784          }
1785          else
1786          {
1787            NodeList rows = lmatrix.getElementsByTagName("Row");
1788            String firstRow = rows.item(0).getFirstChild().getNodeValue();
1789            String sep [] = firstRow.split("[a-z,\t ]");
1790            //      System.out.println(sep.length);
1791            conMatrix = new double [rows.getLength()][sep.length];
1792            for(int colId=0; colId < sep.length; colId++)
1793            {
1794              conMatrix[0][colId]=Double.parseDouble(sep[colId]);
1795            }
1796
1797            for( int rowId=1; rowId<rows.getLength(); rowId++)
1798            {
1799              firstRow = rows.item(rowId).getFirstChild().getNodeValue();
1800              sep = firstRow.split("[a-z,\t ]");
1801              for(int colId=0; colId < sep.length; colId++)
1802              {
1803                conMatrix[rowId][colId]=Double.parseDouble(sep[colId]);
1804              }
1805            }
1806          }
1807
1808          Element lrotation;
1809          if(orientation.getLength()==max)
1810          {
1811            lrotation = (Element)(orientation.item(i));
1812          }
1813          else
1814          {
1815            lrotation = (Element)(orientation.item(0));
1816          }
1817
1818          int rot =Integer.parseInt(
1819            lrotation.getFirstChild().getNodeValue())/90;
1820
1821          if(rot>0)
1822          {
1823            for(int ii=0 ; ii< rot; ii++)
1824            {
1825              conMatrix = FunUtil.rRotate90(conMatrix);
1826            }
1827          }
1828          else if(rot <0)
1829          {
1830            for(int ii=0 ; ii< -rot; ii++)
1831            {
1832              conMatrix = FunUtil.lRotate90(conMatrix);
1833            }
1834          }
1835          //remeber to change the rows matrix. use rows
1836          Element lfrom;
1837          if(from.getLength()==max)
1838          {
1839            lfrom = (Element)(from.item(i));
1840          }
1841          else
1842          {
1843            lfrom = (Element)(from.item(0));
1844          }
1845          Element lto;
1846          if(to.getLength()==max)
1847          {
1848            lto = (Element)(to.item(i));
1849          }
1850          else
1851          {
1852            lto = (Element)(to.item(0));
1853          }
1854
1855          Element ltype;
1856          if(type.getLength()==max)
1857          {
1858            ltype = (Element)(type.item(i));
1859          }
1860          else
1861          {
1862            ltype = (Element)(type.item(0));
1863          }
1864
1865          final int  iType = parseSynapseType ( ltype );
1866          
1867          Element lstr;
1868          if(str.getLength()==max)
1869          {
1870            lstr = (Element)(str.item(i));
1871          }
1872          else
1873          {
1874            lstr = (Element)(str.item(0));
1875          }
1876          Element lmulti;
1877          if(multi.getLength()==max)
1878          {
1879            lmulti = (Element)(multi.item(i));
1880          }
1881          else
1882          {
1883            lmulti = (Element)(multi.item(0));
1884          }
1885          Element loffset;
1886          if(offset.getLength()==max)
1887          {
1888            loffset = (Element)(offset.item(i));
1889          }
1890          else
1891          {
1892            loffset = (Element)(offset.item(0));
1893          }
1894          Element ldelay;
1895          if(delay.getLength()==max)
1896          {
1897            ldelay = (Element)(delay.item(i));
1898          }
1899          else
1900          {
1901            ldelay = (Element)(delay.item(0));
1902          }
1903
1904          Double theStr;
1905          if(lstr.getElementsByTagName("Ref").getLength()>0)
1906          {
1907            theStr = doubleDataMap.get(
1908              lstr.getElementsByTagName("Ref").item(0).getFirstChild()
1909              .getNodeValue());
1910            if(theStr == null) 
1911              throw new RuntimeException(
1912                lstr.getElementsByTagName("Ref").item(0)
1913                .getFirstChild().getNodeValue()
1914                +" as a reference is not defined in Data Section");
1915          }
1916          else
1917          {
1918            theStr = Double.parseDouble(
1919              lstr.getFirstChild().getNodeValue());
1920          }
1921          Double theDelay;
1922          if(ldelay.getElementsByTagName("Ref").getLength()>0)
1923          {
1924            theDelay = doubleDataMap.get(
1925              ldelay.getElementsByTagName("Ref").item(0).getFirstChild()
1926                .getNodeValue());
1927            
1928            if(theDelay == null) throw new RuntimeException(
1929              ldelay.getElementsByTagName("Ref").item(0).getFirstChild()
1930                .getNodeValue()
1931                  +" as a reference is not defined in Data Section");
1932          }
1933          else
1934          {
1935            theDelay = Double.parseDouble(
1936              ldelay.getFirstChild().getNodeValue());
1937          }
1938
1939          double outVal;
1940          
1941          outVal = layerStructure.changeConnection(
1942            lfrom.getAttributeNode("prefix").getNodeValue(),
1943            lfrom.getAttributeNode("suffix").getNodeValue(),
1944            lto.getAttributeNode("prefix").getNodeValue(),
1945            lto.getAttributeNode("suffix").getNodeValue(),
1946            theStr*Double.parseDouble(
1947              lmulti.getFirstChild().getNodeValue())
1948                + Double.parseDouble(
1949                  loffset.getFirstChild().getNodeValue()),
1950            iType,
1951            theDelay,
1952            conMatrix,
1953            hostId);
1954          if(outVal > maxOutput) maxOutput = outVal;
1955        }
1956      }
1957
1958      //read layers;
1959      nList = conns.getElementsByTagName("Connection");
1960      for(int it= 0 ; it< nList.getLength(); it++) // add all the layers;
1961      {
1962        String perio = ((Element)(nList.item(it))).getAttributeNode(
1963          "periodic").getValue();
1964        
1965        boolean periodic;
1966        
1967        if(perio.equals("true") || perio.equals("TRUE"))
1968        {
1969          periodic = true;
1970        }
1971        else
1972        {
1973          periodic = false;
1974        }
1975
1976        Element matrix = (Element)(((Element)(nList.item(it)))
1977          .getElementsByTagName("Matrix").item(0));
1978
1979        NodeList rows = matrix.getElementsByTagName("Row");
1980        String firstRow = rows.item(0).getFirstChild().getNodeValue();
1981        String sep [] = firstRow.split("[a-z,\t ]");
1982        //      p.println(sep.length);
1983        //      p.flush();
1984        double [][] conMatrix = new double [rows.getLength()][sep.length];
1985        for(int colId=0; colId < sep.length; colId++)
1986        {
1987          conMatrix[0][colId]=Double.parseDouble(sep[colId]);
1988        }
1989
1990        for( int rowId=1; rowId<rows.getLength(); rowId++)
1991        {
1992          firstRow = rows.item(rowId).getFirstChild().getNodeValue();
1993          sep = firstRow.split("[a-z,\t ]");
1994          for(int colId=0; colId < sep.length; colId++)
1995          {
1996            conMatrix[rowId][colId]=Double.parseDouble(sep[colId]);
1997          }
1998        }
1999        /*
2000      for(int ii=0; ii < conMatrix.length; ii++)
2001      {
2002        for(int jj=0 ; jj < conMatrix[0].length; jj++)
2003        {
2004          p.print(conMatrix[ii][jj]+" ");
2005        }
2006        p.println();
2007      }
2008         */
2009
2010        int rotation =Integer.parseInt(
2011          ((Element)(nList.item(it))).getElementsByTagName("Rotation")
2012            .item(0).getFirstChild().getNodeValue())/90;
2013
2014        if(rotation>0)
2015        {
2016          for(int ii=0 ; ii< rotation; ii++)
2017          {
2018            conMatrix = FunUtil.rRotate90(conMatrix);
2019          }
2020        }
2021        else if(rotation <0)
2022        {
2023          for(int ii=0 ; ii< -rotation; ii++)
2024          {
2025            conMatrix = FunUtil.lRotate90(conMatrix);
2026          }
2027        }
2028        /*
2029      for(int ii=0; ii < conMatrix.length; ii++)
2030      {
2031        for(int jj=0 ; jj < conMatrix[0].length; jj++)
2032        {
2033          p.print(conMatrix[ii][jj]+" ");
2034        }
2035        p.println();
2036      }
2037         */
2038
2039
2040        Element from = (Element)(((Element)(nList.item(it)))
2041          .getElementsByTagName("FromLayer").item(0));
2042        
2043        Element to  = (Element)(((Element)(nList.item(it)))
2044          .getElementsByTagName("ToLayer").item(0));
2045        
2046        final Element  styleElement = getFirstElement (
2047          ( Element ) ( nList.item ( it ) ),
2048          "Style" );
2049        
2050        final  boolean  sty = parseVergenceStyle ( styleElement );
2051        
2052        //synaptic type
2053        
2054        final Element  typeElement = ( Element )
2055          ( ( Element ) nList.item ( it ) )
2056          .getElementsByTagName ( "Type" ).item ( 0 );
2057
2058        final int  type = parseSynapseType ( typeElement );
2059        
2060/*
2061        System.out.println(((Element)
2062          (from.getElementsByTagName("Prefix").item(0)))
2063          .getFirstChild().getNodeValue()
2064          +" "
2065          + ((Element)(from.getElementsByTagName("Suffix").item(0)))
2066          .getFirstChild().getNodeValue()+" "
2067          + ((Element)(to.getElementsByTagName("Prefix").item(0)))
2068          .getFirstChild().getNodeValue()+" "
2069          + ((Element)(to.getElementsByTagName("Suffix").item(0)))
2070          .getFirstChild().getNodeValue());
2071*/
2072/*
2073        if(connected)
2074        {
2075          p.println(
2076            "str"+Double.parseDouble(((Element)(nList.item(it)))
2077            .getElementsByTagName("Strength").item(0).getFirstChild()
2078            .getNodeValue())*Double.parseDouble(((Element)(nList.item(it)))
2079            .getElementsByTagName("Multiplier").item(0).getFirstChild()
2080            .getNodeValue())+ Double.parseDouble(((Element)(nList.item(it)))
2081            .getElementsByTagName("Offset").item(0).getFirstChild()
2082            .getNodeValue()));
2083          p.println(((Element)(from.getElementsByTagName("Prefix")
2084            .item(0))).getFirstChild().getNodeValue()+ " "
2085            +((Element)(from.getElementsByTagName("Suffix").item(0)))
2086            .getFirstChild().getNodeValue()+" "
2087            +((Element)(to.getElementsByTagName("Prefix").item(0)))
2088            .getFirstChild().getNodeValue()+" "
2089            +((Element)(to.getElementsByTagName("Suffix").item(0)))
2090            .getFirstChild().getNodeValue());
2091        }
2092*/
2093        double outVal;
2094        
2095        outVal = layerStructure.changeConnection(((Element)(
2096          from.getElementsByTagName("Prefix").item(0))).getFirstChild()
2097            .getNodeValue(),
2098          ((Element)(from.getElementsByTagName("Suffix").item(0)))
2099            .getFirstChild().getNodeValue(),
2100          ((Element)(to.getElementsByTagName("Prefix").item(0)))
2101            .getFirstChild().getNodeValue(),
2102          ((Element)(to.getElementsByTagName("Suffix").item(0)))
2103            .getFirstChild().getNodeValue(),
2104          sty,
2105          Double.parseDouble(
2106            ((Element)(nList.item(it))).getElementsByTagName("Strength")
2107              .item(0).getFirstChild().getNodeValue())
2108              * Double.parseDouble(((Element)(nList.item(it)))
2109                  .getElementsByTagName("Multiplier").item(0)
2110                  .getFirstChild().getNodeValue())
2111              + Double.parseDouble(((Element)(nList.item(it)))
2112                .getElementsByTagName("Offset").item(0).getFirstChild()
2113                .getNodeValue()),
2114          type,
2115          Double.parseDouble(
2116            ((Element)(nList.item(it))).getElementsByTagName("Delay")
2117              .item(0).getFirstChild().getNodeValue()),
2118          conMatrix,
2119          hostId,
2120          periodic);
2121        
2122        if(outVal > maxOutput) maxOutput = outVal;
2123      }
2124      
2125      return maxOutput;
2126    }
2127
2128    /***********************************************************************
2129    * Parse the connection section, connect the neurons and build up the
2130    * network structure
2131    ***********************************************************************/
2132    public double parseConnection(int hostId) throws Exception
2133    ////////////////////////////////////////////////////////////////////////
2134    {
2135      layerStructure.reSetSeed(); //reset the seed number
2136      
2137      double maxOutput = -1.0;
2138      
2139      NodeList nList = rootElement.getElementsByTagName("Connections");
2140      
2141      Element conns = (Element) nList.item(0);
2142
2143      //read layers;
2144      nList = conns.getElementsByTagName("LConnection"); //loop connections
2145      
2146      for(int it= 0 ; it< nList.getLength(); it++) // add all the layers;
2147      {
2148        String perio = ((Element)(nList.item(it)))
2149          .getAttributeNode("periodic").getValue();
2150        
2151        boolean periodic;
2152        
2153        if(perio.equals("true") || perio.equals("TRUE"))
2154        {
2155          periodic = true;
2156        }
2157        else
2158        {
2159          periodic = false;
2160        }
2161
2162        int max=1;
2163        
2164        NodeList from = ((Element)(nList.item(it)))
2165          .getElementsByTagName("FromLayer");
2166        
2167        if(from.getLength() !=1) max = from.getLength();
2168        
2169        NodeList to = ((Element)(nList.item(it)))
2170          .getElementsByTagName("ToLayer");
2171        
2172        if(to.getLength() !=1 && max !=1 && to.getLength() != max)
2173          throw new RuntimeException("number does not match");
2174        
2175        if(to.getLength() !=1 ) max = to.getLength();
2176        
2177        NodeList
2178          matrix = ((Element)(nList.item(it)))
2179            .getElementsByTagName("Matrix");
2180        
2181        if(matrix.getLength() !=1 && max !=1 && matrix.getLength() != max)
2182          throw new RuntimeException("number does not match");
2183        
2184        if(matrix.getLength() !=1 ) max = matrix.getLength();
2185        
2186        NodeList orientation = ((Element)(nList.item(it)))
2187          .getElementsByTagName("Rotation");
2188        
2189        if(orientation.getLength() !=1 && max !=1
2190          && orientation.getLength() != max)
2191          throw new RuntimeException("number does not match");
2192        
2193        if(orientation.getLength() !=1 ) max = orientation.getLength();
2194        
2195        NodeList
2196          style = ((Element)(nList.item(it))).getElementsByTagName("Style");
2197        
2198        if (style.getLength() !=1 && max !=1 && style.getLength() != max)
2199          throw new RuntimeException("number does not match");
2200        
2201        if(style.getLength() !=1 ) max = style.getLength();
2202        
2203        NodeList
2204          type = ((Element)(nList.item(it))).getElementsByTagName("Type");
2205        
2206        if(type.getLength() !=1 && max !=1 && type.getLength() != max)
2207          throw new RuntimeException("number does not match");
2208        
2209        if(type.getLength() !=1 ) max = type.getLength();
2210        
2211        NodeList  str
2212          = ((Element)(nList.item(it))).getElementsByTagName("Strength");
2213        
2214        if(str.getLength() !=1 && max !=1 && str.getLength() != max)
2215          throw new RuntimeException("number does not match");
2216        
2217        if(str.getLength() !=1 ) max = str.getLength();
2218        
2219        NodeList multi =  ((Element)(nList.item(it))).getElementsByTagName(
2220          "Multiplier");
2221        
2222        if(multi.getLength() !=1 && max !=1 && multi.getLength() != max)
2223          throw new RuntimeException("number does not match");
2224        
2225        if(multi.getLength() !=1 ) max = multi.getLength();
2226        
2227        NodeList offset =  ((Element)(nList.item(it))).getElementsByTagName(
2228          "Offset");
2229        
2230        if(offset.getLength() !=1 && max !=1 && offset.getLength() != max)
2231          throw new RuntimeException("number does not match");
2232        
2233        if(offset.getLength() !=1 ) max = offset.getLength();
2234        
2235        NodeList delay = ((Element)(nList.item(it))).getElementsByTagName(
2236          "Delay");
2237        
2238        if(delay.getLength() !=1 && max !=1 && delay.getLength() != max)
2239          throw new RuntimeException("number does not match");
2240        
2241        if(delay.getLength() !=1 ) max = delay.getLength();
2242        
2243        //      System.out.println("max"+max);
2244
2245        for(int i=0; i < max; i++)
2246        {
2247          Element lmatrix;
2248          if(matrix.getLength()==max)
2249          {
2250            lmatrix = (Element)(matrix.item(i));
2251          }
2252          else
2253          {
2254            lmatrix = (Element)(matrix.item(0));
2255          }
2256
2257          double [][] conMatrix;
2258          
2259          if(lmatrix.getElementsByTagName("Ref").getLength()>0)
2260          {
2261            conMatrix = matrixDataMap.get(
2262              lmatrix.getElementsByTagName("Ref").item(0).getFirstChild()
2263              .getNodeValue());
2264            
2265            if(conMatrix == null)
2266              throw new RuntimeException(
2267                lmatrix.getElementsByTagName("Ref").item(0).getFirstChild()
2268                  .getNodeValue()
2269                    +" as a reference is not defined in Data Section");
2270          }
2271          else
2272          {
2273            NodeList rows = lmatrix.getElementsByTagName("Row");
2274            
2275            String firstRow = rows.item(0).getFirstChild().getNodeValue();
2276            
2277            String sep [] = firstRow.split("[a-z,\t ]");
2278            
2279            //      System.out.println(sep.length);
2280            
2281            conMatrix = new double [rows.getLength()][sep.length];
2282            
2283            for(int colId=0; colId < sep.length; colId++)
2284            {
2285              conMatrix[0][colId]=Double.parseDouble(sep[colId]);
2286            }
2287
2288            for( int rowId=1; rowId<rows.getLength(); rowId++)
2289            {
2290              firstRow = rows.item(rowId).getFirstChild().getNodeValue();
2291              
2292              sep = firstRow.split("[a-z,\t ]");
2293              
2294              for(int colId=0; colId < sep.length; colId++)
2295              {
2296                conMatrix[rowId][colId]=Double.parseDouble(sep[colId]);
2297              }
2298            }
2299          }
2300
2301          Element lrotation;
2302          
2303          if(orientation.getLength()==max)
2304          {
2305            lrotation = (Element)(orientation.item(i));
2306          }
2307          else
2308          {
2309            lrotation = (Element)(orientation.item(0));
2310          }
2311
2312          int rot =Integer.parseInt(
2313            lrotation.getFirstChild().getNodeValue())/90;
2314
2315          if(rot>0)
2316          {
2317            for(int ii=0 ; ii< rot; ii++)
2318            {
2319              conMatrix = FunUtil.rRotate90(conMatrix);
2320            }
2321          }
2322          else if(rot <0)
2323          {
2324            for(int ii=0 ; ii< -rot; ii++)
2325            {
2326              conMatrix = FunUtil.lRotate90(conMatrix);
2327            }
2328          }
2329          //remeber to change the rows matrix. use rows
2330          Element lfrom;
2331          if(from.getLength()==max)
2332          {
2333            lfrom = (Element)(from.item(i));
2334          }
2335          else
2336          {
2337            lfrom = (Element)(from.item(0));
2338          }
2339          Element lto;
2340          if(to.getLength()==max)
2341          {
2342            lto = (Element)(to.item(i));
2343          }
2344          else
2345          {
2346            lto = (Element)(to.item(0));
2347          }
2348          Element lstyle;
2349          if(style.getLength()==max)
2350          {
2351            lstyle = (Element)(style.item(i));
2352          }
2353          else
2354          {
2355            lstyle = (Element)(style.item(0));
2356          }
2357          
2358          final boolean  sty = parseVergenceStyle ( lstyle );
2359
2360          Element ltype;
2361          if(type.getLength()==max)
2362          {
2363            ltype = (Element)(type.item(i));
2364          }
2365          else
2366          {
2367            ltype = (Element)(type.item(0));
2368          }
2369
2370          final int  iType = parseSynapseType ( ltype );
2371          
2372          Element lstr;
2373          if(str.getLength()==max)
2374          {
2375            lstr = (Element)(str.item(i));
2376          }
2377          else
2378          {
2379            lstr = (Element)(str.item(0));
2380          }
2381          Element lmulti;
2382          if(multi.getLength()==max)
2383          {
2384            lmulti = (Element)(multi.item(i));
2385          }
2386          else
2387          {
2388            lmulti = (Element)(multi.item(0));
2389          }
2390          Element loffset;
2391          if(offset.getLength()==max)
2392          {
2393            loffset = (Element)(offset.item(i));
2394          }
2395          else
2396          {
2397            loffset = (Element)(offset.item(0));
2398          }
2399          Element ldelay;
2400          if(delay.getLength()==max)
2401          {
2402            ldelay = (Element)(delay.item(i));
2403          }
2404          else
2405          {
2406            ldelay = (Element)(delay.item(0));
2407          }
2408/*
2409          System.out.print(lfrom.getAttributeNode("prefix").getNodeValue()
2410            +" "+lfrom.getAttributeNode("suffix").getNodeValue()+" "
2411            +lto.getAttributeNode("prefix").getNodeValue()+" "
2412            +lto.getAttributeNode("suffix").getNodeValue());
2413            
2414          System.out.print(" "+sty);
2415          
2416          System.out.print(" "+lstr.getFirstChild().getNodeValue());
2417          
2418          System.out.print(" "+lmulti.getFirstChild().getNodeValue());
2419          
2420          System.out.print(" "+loffset.getFirstChild().getNodeValue());
2421          
2422          System.out.print(" "+ldelay.getFirstChild().getNodeValue());
2423          
2424          System.out.println();
2425*/
2426/*
2427          if(connected)
2428          {
2429          p.print(lfrom.getAttributeNode("prefix").getNodeValue()+" "
2430            +lfrom.getAttributeNode("suffix").getNodeValue()+" "
2431            +lto.getAttributeNode("prefix").getNodeValue()+" "
2432            +lto.getAttributeNode("suffix").getNodeValue());
2433            
2434          p.print(" "+sty);
2435          
2436          p.print(" "+lstr.getFirstChild().getNodeValue());
2437          
2438          p.print(" "+lmulti.getFirstChild().getNodeValue());
2439          
2440          p.print(" "+loffset.getFirstChild().getNodeValue());
2441          
2442          p.print(" "+ldelay.getFirstChild().getNodeValue());
2443          
2444          p.println();
2445          }
2446*/
2447/*
2448          for(int ii=0; ii < conMatrix.length; ii++)
2449          {
2450            for(int jj=0 ; jj < conMatrix[0].length; jj++)
2451            {
2452              System.out.print(conMatrix[ii][jj]+" ");
2453            }
2454            System.out.println();
2455          }
2456*/
2457          Double theStr;
2458          
2459          if(lstr.getElementsByTagName("Ref").getLength()>0)
2460          {
2461            theStr = doubleDataMap.get(lstr.getElementsByTagName("Ref")
2462              .item(0).getFirstChild().getNodeValue());
2463            
2464            if(theStr == null)
2465              throw new RuntimeException(
2466                lstr.getElementsByTagName("Ref").item(0).getFirstChild()
2467                  .getNodeValue()
2468                    +" as a reference is not defined in Data Section");
2469          }
2470          else
2471          {
2472            theStr = Double.parseDouble(
2473              lstr.getFirstChild().getNodeValue());
2474          }
2475          
2476          Double theDelay;
2477          
2478          if(ldelay.getElementsByTagName("Ref").getLength()>0)
2479          {
2480            theDelay = doubleDataMap.get(
2481              ldelay.getElementsByTagName("Ref").item(0)
2482                .getFirstChild().getNodeValue());
2483            
2484            if(theDelay == null)
2485              throw new RuntimeException(
2486                ldelay.getElementsByTagName("Ref").item(0).getFirstChild()
2487                  .getNodeValue()
2488                    +" as a reference is not defined in Data Section");
2489          }
2490          else
2491          {
2492            theDelay = Double.parseDouble(
2493              ldelay.getFirstChild().getNodeValue());
2494          }
2495
2496          double outVal;
2497          
2498          outVal = layerStructure.connect(
2499            lfrom.getAttributeNode("prefix").getNodeValue(),
2500            lfrom.getAttributeNode("suffix").getNodeValue(),
2501            lto.getAttributeNode("prefix").getNodeValue(),
2502            lto.getAttributeNode("suffix").getNodeValue(),
2503            sty,
2504            theStr * Double.parseDouble (
2505              lmulti.getFirstChild().getNodeValue() )
2506              + Double.parseDouble(loffset.getFirstChild().getNodeValue()),
2507            iType,
2508            theDelay,
2509            conMatrix,
2510            hostId,
2511            periodic);
2512          
2513          if(outVal > maxOutput) maxOutput = outVal;
2514        }
2515      }
2516
2517      //read layers general loop connections;
2518      
2519      nList = conns.getElementsByTagName("GConnection"); //loop connections
2520      
2521      for(int it= 0 ; it< nList.getLength(); it++) // add all the layers;
2522      {
2523        int max=1;
2524        
2525        NodeList from = ((Element)(nList.item(it))).getElementsByTagName(
2526          "FromLayer");
2527        
2528        if(from.getLength() !=1) max = from.getLength();
2529        
2530        NodeList to =  ((Element)(nList.item(it))).getElementsByTagName(
2531          "ToLayer");
2532        
2533        if(to.getLength() !=1 && max !=1 && to.getLength() != max)
2534          throw new RuntimeException("number does not match");
2535        
2536        if(to.getLength() !=1 ) max = to.getLength();
2537        
2538        NodeList matrix =  ((Element)(nList.item(it))).getElementsByTagName(
2539          "Matrix");
2540        
2541        if(matrix.getLength() !=1 && max !=1 && matrix.getLength() != max)
2542          throw new RuntimeException("number does not match");
2543        
2544        if(matrix.getLength() !=1 ) max = matrix.getLength();
2545        
2546        NodeList orientation = ((Element)(nList.item(it)))
2547          .getElementsByTagName("Rotation");
2548        
2549        if(orientation.getLength() !=1 && max !=1
2550          && orientation.getLength() != max)
2551          throw new RuntimeException("number does not match");
2552        
2553        if(orientation.getLength() !=1 ) max = orientation.getLength();
2554
2555        NodeList type = ((Element)(nList.item(it)))
2556          .getElementsByTagName("Type");
2557        
2558        if(type.getLength() !=1 && max !=1 && type.getLength() != max)
2559          throw new RuntimeException("number does not match");
2560        
2561        if(type.getLength() !=1 ) max = type.getLength();
2562        
2563        NodeList str = ((Element)(nList.item(it)))
2564          .getElementsByTagName("Strength");
2565        
2566        if(str.getLength() !=1 && max !=1 && str.getLength() != max)
2567          throw new RuntimeException("number does not match");
2568        
2569        if(str.getLength() !=1 ) max = str.getLength();
2570        
2571        NodeList multi =  ((Element)(nList.item(it))).getElementsByTagName(
2572          "Multiplier");
2573        
2574        if(multi.getLength() !=1 && max !=1 && multi.getLength() != max)
2575          throw new RuntimeException("number does not match");
2576        
2577        if(multi.getLength() !=1 ) max = multi.getLength();
2578        
2579        NodeList offset =  ((Element)(nList.item(it))).getElementsByTagName(
2580          "Offset");
2581        
2582        if(offset.getLength() !=1 && max !=1 && offset.getLength() != max)
2583          throw new RuntimeException("number does not match");
2584        
2585        if(offset.getLength() !=1 ) max = offset.getLength();
2586        
2587        NodeList delay =  ((Element)(nList.item(it))).getElementsByTagName(
2588          "Delay");
2589        
2590        if(delay.getLength() !=1 && max !=1 && delay.getLength() != max)
2591          throw new RuntimeException("number does not match");
2592        
2593        if(delay.getLength() !=1 ) max = delay.getLength();
2594        
2595        //      System.out.println("max"+max);
2596
2597        for(int i=0; i < max; i++)
2598        {
2599          Element lmatrix;
2600          if(matrix.getLength()==max)
2601          {
2602            lmatrix = (Element)(matrix.item(i));
2603          }
2604          else
2605          {
2606            lmatrix = (Element)(matrix.item(0));
2607          }
2608          double [][] conMatrix;
2609          if(lmatrix.getElementsByTagName("Ref").getLength()>0)
2610          {
2611            conMatrix = matrixDataMap.get(
2612              lmatrix.getElementsByTagName("Ref").item(0).getFirstChild()
2613              .getNodeValue());
2614            
2615            if(conMatrix == null)
2616              throw new RuntimeException(
2617                lmatrix.getElementsByTagName("Ref").item(0)
2618                  .getFirstChild().getNodeValue()
2619                    +" as a reference is not defined in Data Section");
2620          }
2621          else
2622          {
2623            NodeList rows = lmatrix.getElementsByTagName("Row");
2624            
2625            String firstRow = rows.item(0).getFirstChild().getNodeValue();
2626            
2627            String sep [] = firstRow.split("[a-z,\t ]");
2628            
2629            //      System.out.println(sep.length);
2630            
2631            conMatrix = new double [rows.getLength()][sep.length];
2632            
2633            for(int colId=0; colId < sep.length; colId++)
2634            {
2635              conMatrix[0][colId]=Double.parseDouble(sep[colId]);
2636            }
2637
2638            for( int rowId=1; rowId<rows.getLength(); rowId++)
2639            {
2640              firstRow = rows.item(rowId).getFirstChild().getNodeValue();
2641              
2642              sep = firstRow.split("[a-z,\t ]");
2643              
2644              for(int colId=0; colId < sep.length; colId++)
2645              {
2646                conMatrix[rowId][colId]=Double.parseDouble(sep[colId]);
2647              }
2648            }
2649          }
2650
2651          Element lrotation;
2652          
2653          if(orientation.getLength()==max)
2654          {
2655            lrotation = (Element)(orientation.item(i));
2656          }
2657          else
2658          {
2659            lrotation = (Element)(orientation.item(0));
2660          }
2661
2662          int rot =Integer.parseInt(
2663            lrotation.getFirstChild().getNodeValue())/90;
2664
2665          if(rot>0)
2666          {
2667            for(int ii=0 ; ii< rot; ii++)
2668            {
2669              conMatrix = FunUtil.rRotate90(conMatrix);
2670            }
2671          }
2672          else if(rot <0)
2673          {
2674            for(int ii=0 ; ii< -rot; ii++)
2675            {
2676              conMatrix = FunUtil.lRotate90(conMatrix);
2677            }
2678          }
2679          //remeber to change the rows matrix. use rows
2680          Element lfrom;
2681          if(from.getLength()==max)
2682          {
2683            lfrom = (Element)(from.item(i));
2684          }
2685          else
2686          {
2687            lfrom = (Element)(from.item(0));
2688          }
2689          Element lto;
2690          if(to.getLength()==max)
2691          {
2692            lto = (Element)(to.item(i));
2693          }
2694          else
2695          {
2696            lto = (Element)(to.item(0));
2697          }
2698
2699          Element ltype;
2700          if(type.getLength()==max)
2701          {
2702            ltype = (Element)(type.item(i));
2703          }
2704          else
2705          {
2706            ltype = (Element)(type.item(0));
2707          }
2708
2709          final int  iType = parseSynapseType ( ltype );
2710          
2711          Element lstr;
2712          if(str.getLength()==max)
2713          {
2714            lstr = (Element)(str.item(i));
2715          }
2716          else
2717          {
2718            lstr = (Element)(str.item(0));
2719          }
2720          Element lmulti;
2721          if(multi.getLength()==max)
2722          {
2723            lmulti = (Element)(multi.item(i));
2724          }
2725          else
2726          {
2727            lmulti = (Element)(multi.item(0));
2728          }
2729          Element loffset;
2730          if(offset.getLength()==max)
2731          {
2732            loffset = (Element)(offset.item(i));
2733          }
2734          else
2735          {
2736            loffset = (Element)(offset.item(0));
2737          }
2738          Element ldelay;
2739          if(delay.getLength()==max)
2740          {
2741            ldelay = (Element)(delay.item(i));
2742          }
2743          else
2744          {
2745            ldelay = (Element)(delay.item(0));
2746          }
2747          Double theStr;
2748          if(lstr.getElementsByTagName("Ref").getLength()>0)
2749          {
2750            theStr = doubleDataMap.get(
2751              lstr.getElementsByTagName("Ref").item(0).getFirstChild()
2752                .getNodeValue());
2753            
2754            if(theStr == null)
2755              throw new RuntimeException(
2756                  lstr.getElementsByTagName("Ref").item(0)
2757                    .getFirstChild().getNodeValue()
2758                      +" as a reference is not defined in Data Section");
2759          }
2760          else
2761          {
2762            theStr = Double.parseDouble(
2763              lstr.getFirstChild().getNodeValue());
2764          }
2765          
2766          Double theDelay;
2767          
2768          if(ldelay.getElementsByTagName("Ref").getLength()>0)
2769          {
2770            theDelay = doubleDataMap.get(
2771              ldelay.getElementsByTagName("Ref").item(0).getFirstChild()
2772                .getNodeValue());
2773            
2774            if(theDelay == null)
2775              throw new RuntimeException(
2776                ldelay.getElementsByTagName("Ref").item(0).getFirstChild()
2777                  .getNodeValue()
2778                    +" as a reference is not defined in Data Section");
2779          }
2780          else
2781          {
2782            theDelay = Double.parseDouble(
2783              ldelay.getFirstChild().getNodeValue());
2784          }
2785
2786          double outVal;
2787          
2788          outVal = layerStructure.connect(
2789            lfrom.getAttributeNode("prefix").getNodeValue(),
2790            lfrom.getAttributeNode("suffix").getNodeValue(),
2791            lto.getAttributeNode("prefix").getNodeValue(),
2792            lto.getAttributeNode("suffix").getNodeValue(),
2793            theStr*Double.parseDouble(
2794              lmulti.getFirstChild().getNodeValue())
2795              + Double.parseDouble(loffset.getFirstChild().getNodeValue()),
2796            iType,
2797            theDelay,
2798            conMatrix,
2799            hostId);
2800          if(outVal > maxOutput) maxOutput = outVal;
2801        }
2802      }
2803
2804      //read layers probability connections;
2805      
2806      nList = conns.getElementsByTagName("PConnection"); //loop connections
2807      
2808      for(int it= 0 ; it< nList.getLength(); it++) // add all the layers;
2809      {
2810        String perio = ((Element)(nList.item(it)))
2811          .getAttributeNode("periodic").getValue();
2812        
2813        boolean periodic;
2814        
2815        if(perio.equals("true") || perio.equals("TRUE"))
2816        {
2817          periodic = true;
2818        }
2819        else
2820        {
2821          periodic = false;
2822        }
2823
2824        int max=1;
2825        
2826        boolean str_matrix; // strength matrix exist or not
2827        
2828        NodeList from = ((Element)(nList.item(it))).getElementsByTagName(
2829          "FromLayer");
2830        
2831        if(from.getLength() !=1) max = from.getLength();
2832        
2833        NodeList to =  ((Element)(nList.item(it))).getElementsByTagName(
2834          "ToLayer");
2835        
2836        if(to.getLength() !=1 && max !=1 && to.getLength() != max)
2837          throw new RuntimeException("number does not match");
2838        
2839        if(to.getLength() !=1 ) max = to.getLength();
2840
2841        NodeList pmatrix = ((Element)(nList.item(it))).getElementsByTagName(
2842          "PMatrix");
2843        
2844        if(pmatrix.getLength() !=1 && max !=1 && pmatrix.getLength() != max)
2845          throw new RuntimeException("number does not match");
2846        
2847        if(pmatrix.getLength() !=1 ) max = pmatrix.getLength();
2848
2849        NodeList smatrix = ((Element)(nList.item(it))).getElementsByTagName(
2850          "SMatrix");
2851        
2852        if(smatrix.getLength() ==0)
2853        {
2854          str_matrix = false;
2855        }
2856        else
2857        {
2858          if(smatrix.getLength() !=1 && max !=1
2859            && smatrix.getLength() != max)
2860            throw new RuntimeException("number does not match");
2861          
2862          if(smatrix.getLength() !=1 ) max = smatrix.getLength();
2863          
2864          str_matrix = true;
2865        }
2866
2867        NodeList orientation = ((Element)(nList.item(it)))
2868          .getElementsByTagName("Rotation");
2869        
2870        if(orientation.getLength() !=1 && max !=1
2871          && orientation.getLength() != max)
2872          throw new RuntimeException("number does not match");
2873        
2874        if(orientation.getLength() !=1 ) max = orientation.getLength();
2875        
2876        NodeList style =  ((Element)(nList.item(it))).getElementsByTagName(
2877          "Style");
2878
2879        if(style.getLength() !=1 && max !=1 && style.getLength() != max)
2880          throw new RuntimeException("number does not match");
2881
2882        if(style.getLength() !=1 ) max = style.getLength();
2883
2884        NodeList type =  ((Element)(nList.item(it))).getElementsByTagName(
2885          "Type");
2886
2887        if(type.getLength() !=1 && max !=1 && type.getLength() != max)
2888          throw new RuntimeException("number does not match");
2889
2890        if(type.getLength() !=1 ) max = type.getLength();
2891
2892        NodeList str = ((Element)(nList.item(it))).getElementsByTagName(
2893          "Strength");
2894
2895        if(str.getLength() !=1 && max !=1 && str.getLength() != max)
2896          throw new RuntimeException("number does not match");
2897
2898        if(str.getLength() !=1 ) max = str.getLength();
2899
2900        NodeList multi = ((Element)(nList.item(it))).getElementsByTagName(
2901          "Multiplier");
2902        
2903        if(multi.getLength() !=1 && max !=1 && multi.getLength() != max)
2904          throw new RuntimeException("number does not match");
2905        
2906        if(multi.getLength() !=1 ) max = multi.getLength();
2907        
2908        NodeList offset = ((Element)(nList.item(it))).getElementsByTagName(
2909          "Offset");
2910        
2911        if(offset.getLength() !=1 && max !=1 && offset.getLength() != max)
2912          throw new RuntimeException("number does not match");
2913        
2914        if(offset.getLength() !=1 ) max = offset.getLength();
2915        
2916        NodeList delay = ((Element)(nList.item(it))).getElementsByTagName(
2917          "Delay");
2918        
2919        if(delay.getLength() !=1 && max !=1 && delay.getLength() != max)
2920          throw new RuntimeException("number does not match");
2921        
2922        if(delay.getLength() !=1 ) max = delay.getLength();
2923        
2924        // System.out.println("max"+max);
2925
2926        for(int i=0; i < max; i++)
2927        {
2928          Element lmatrix,eSmatrix;
2929          
2930          if(pmatrix.getLength()==max)
2931          {
2932            lmatrix = (Element)(pmatrix.item(i));
2933          }
2934          else
2935          {
2936            lmatrix = (Element)(pmatrix.item(0));
2937          }
2938
2939          double [][] conMatrix;
2940          
2941          if(lmatrix.getElementsByTagName("Ref").getLength()>0)
2942          {
2943            conMatrix = matrixDataMap.get(
2944              lmatrix.getElementsByTagName("Ref").item(0).getFirstChild()
2945                .getNodeValue());
2946            
2947            if(conMatrix == null)
2948              throw new RuntimeException(
2949                lmatrix.getElementsByTagName("Ref").item(0).getFirstChild()
2950                  .getNodeValue()
2951                  +" as a reference is not defined in Data Section");
2952          }
2953          else 
2954          {
2955            NodeList rows = lmatrix.getElementsByTagName("Row");
2956            
2957            String firstRow = rows.item(0).getFirstChild().getNodeValue();
2958            
2959            String sep [] = firstRow.split("[a-z,\t ]");
2960
2961            conMatrix = new double [rows.getLength()][sep.length];
2962
2963            for(int colId=0; colId < sep.length; colId++)
2964            {
2965              conMatrix[0][colId]=Double.parseDouble(sep[colId]);
2966            }
2967
2968            for( int rowId=1; rowId<rows.getLength(); rowId++)
2969            {
2970              firstRow = rows.item(rowId).getFirstChild().getNodeValue();
2971              
2972              sep = firstRow.split("[a-z,\t ]");
2973              
2974              for(int colId=0; colId < sep.length; colId++)
2975              {
2976                conMatrix[rowId][colId]=Double.parseDouble(sep[colId]);
2977              }
2978            }
2979          }
2980
2981          // System.out.println(sep.length);
2982          
2983          double [][] sconMatrix = null;
2984
2985          if(str_matrix) // if strength matrix exists
2986          {
2987            if(smatrix.getLength()==max)
2988            {
2989              eSmatrix = (Element)(smatrix.item(i));
2990            }
2991            else
2992            {
2993              eSmatrix = (Element)(smatrix.item(0));
2994            }
2995
2996            if(eSmatrix.getElementsByTagName("Ref").getLength()>0)
2997            {
2998              sconMatrix = matrixDataMap.get(eSmatrix.getElementsByTagName(
2999                "Ref").item(0).getFirstChild().getNodeValue());
3000              
3001              if(sconMatrix == null)
3002                throw new RuntimeException(
3003                  eSmatrix.getElementsByTagName("Ref").item(0)
3004                    .getFirstChild().getNodeValue()
3005                    +" as a reference is not defined in Data Section");
3006            }
3007            else
3008            {
3009              NodeList rows = eSmatrix.getElementsByTagName("Row");
3010              
3011              String firstRow = rows.item(0).getFirstChild().getNodeValue();
3012              
3013              String [] sep = firstRow.split("[a-z,\t ]");
3014              
3015              // System.out.println(sep.length);
3016
3017              sconMatrix = new double [rows.getLength()][sep.length];
3018              
3019              for(int colId=0; colId < sep.length; colId++)
3020              {
3021                sconMatrix[0][colId]=Double.parseDouble(sep[colId]);
3022              }
3023
3024              for( int rowId=1; rowId<rows.getLength(); rowId++)
3025              {
3026                firstRow = rows.item(rowId).getFirstChild().getNodeValue();
3027                
3028                sep = firstRow.split("[a-z,\t ]");
3029                
3030                for(int colId=0; colId < sep.length; colId++)
3031                {
3032                  sconMatrix[rowId][colId]=Double.parseDouble(sep[colId]);
3033                }
3034              }
3035            }
3036          }
3037
3038          Element lrotation;
3039          
3040          if(orientation.getLength()==max)
3041          {
3042            lrotation = (Element)(orientation.item(i));
3043          }
3044          else
3045          {
3046            lrotation = (Element)(orientation.item(0));
3047          }
3048
3049          int rot =Integer.parseInt(
3050            lrotation.getFirstChild().getNodeValue())/90;
3051
3052          if(rot>0)
3053          {
3054            for(int ii=0 ; ii< rot; ii++)
3055            {
3056              conMatrix = FunUtil.rRotate90(conMatrix);
3057              
3058              if(str_matrix)sconMatrix = FunUtil.rRotate90(sconMatrix);
3059            }
3060          }
3061          else if(rot <0)
3062          {
3063            for(int ii=0 ; ii< -rot; ii++)
3064            {
3065              conMatrix = FunUtil.lRotate90(conMatrix);
3066              if(str_matrix)sconMatrix = FunUtil.lRotate90(sconMatrix);
3067            }
3068          }
3069          //remeber to change the rows matrix. use rows
3070          Element lfrom;
3071          if(from.getLength()==max)
3072          {
3073            lfrom = (Element)(from.item(i));
3074          }
3075          else
3076          {
3077            lfrom = (Element)(from.item(0));
3078          }
3079          Element lto;
3080          if(to.getLength()==max)
3081          {
3082            lto = (Element)(to.item(i));
3083          }
3084          else
3085          {
3086            lto = (Element)(to.item(0));
3087          }
3088          Element lstyle;
3089          if(style.getLength()==max)
3090          {
3091            lstyle = (Element)(style.item(i));
3092          }
3093          else
3094          {
3095            lstyle = (Element)(style.item(0));
3096          }
3097          
3098          final boolean  sty = parseVergenceStyle ( lstyle );
3099
3100          Element ltype;
3101          if(type.getLength()==max)
3102          {
3103            ltype = (Element)(type.item(i));
3104          }
3105          else
3106          {
3107            ltype = (Element)(type.item(0));
3108          }
3109          
3110          final int  iType = parseSynapseType ( ltype );
3111
3112          Element lstr;
3113          
3114          if(str.getLength()==max)
3115          {
3116            lstr = (Element)(str.item(i));
3117          }
3118          else
3119          {
3120            lstr = (Element)(str.item(0));
3121          }
3122          Element lmulti;
3123          if(multi.getLength()==max)
3124          {
3125            lmulti = (Element)(multi.item(i));
3126          }
3127          else
3128          {
3129            lmulti = (Element)(multi.item(0));
3130          }
3131          Element loffset;
3132          if(offset.getLength()==max)
3133          {
3134            loffset = (Element)(offset.item(i));
3135          }
3136          else
3137          {
3138            loffset = (Element)(offset.item(0));
3139          }
3140          Element ldelay;
3141          if(delay.getLength()==max)
3142          {
3143            ldelay = (Element)(delay.item(i));
3144          }
3145          else
3146          {
3147            ldelay = (Element)(delay.item(0));
3148          }
3149/*
3150          System.out.print(
3151            lfrom.getAttributeNode("prefix").getNodeValue()
3152            +" "
3153            +lfrom.getAttributeNode("suffix").getNodeValue()
3154            +" "
3155            +lto.getAttributeNode("prefix").getNodeValue()
3156            +" "
3157            +lto.getAttributeNode("suffix").getNodeValue());
3158            
3159          System.out.print(" "+sty);
3160          
3161          System.out.print(" "+lstr.getFirstChild().getNodeValue());
3162          
3163          System.out.print(" "+lmulti.getFirstChild().getNodeValue());
3164          
3165          System.out.print(" "+loffset.getFirstChild().getNodeValue());
3166          
3167          System.out.print(" "+ldelay.getFirstChild().getNodeValue());
3168          
3169          System.out.println();
3170*/
3171/*
3172          if(connected)
3173          {
3174            p.print(lfrom.getAttributeNode("prefix").getNodeValue()
3175              +" "
3176              +lfrom.getAttributeNode("suffix").getNodeValue()
3177              +" "
3178              +lto.getAttributeNode("prefix").getNodeValue()
3179              +" "
3180              +lto.getAttributeNode("suffix").getNodeValue());
3181              
3182            p.print(" "+sty);
3183            
3184            p.print(" "+lstr.getFirstChild().getNodeValue());
3185            
3186            p.print(" "+lmulti.getFirstChild().getNodeValue());
3187            
3188            p.print(" "+loffset.getFirstChild().getNodeValue());
3189            
3190            p.print(" "+ldelay.getFirstChild().getNodeValue());
3191            
3192            p.println();
3193          }
3194*/
3195/*
3196          for(int ii=0; ii < conMatrix.length; ii++)
3197          {
3198            for(int jj=0 ; jj < conMatrix[0].length; jj++)
3199            {
3200              System.out.print(conMatrix[ii][jj]+" ");
3201            }
3202            System.out.println();
3203          }
3204*/
3205          Double theStr;
3206          
3207          if(lstr.getElementsByTagName("Ref").getLength()>0)
3208          {
3209            theStr = doubleDataMap.get(
3210              lstr.getElementsByTagName("Ref").item(0).getFirstChild()
3211                .getNodeValue());
3212            
3213            if(theStr == null)
3214              throw new RuntimeException(
3215                lstr.getElementsByTagName("Ref").item(0).getFirstChild()
3216                  .getNodeValue()
3217                    +" as a reference is not defined in Data Section");
3218          }
3219          else
3220          {
3221            theStr = Double.parseDouble(
3222              lstr.getFirstChild().getNodeValue());
3223          }
3224          
3225          Double theDelay;
3226          
3227          if(ldelay.getElementsByTagName("Ref").getLength()>0)
3228          {
3229            theDelay = doubleDataMap.get(
3230              ldelay.getElementsByTagName("Ref").item(0).getFirstChild()
3231                .getNodeValue());
3232            
3233            if(theDelay == null)
3234              throw new RuntimeException(
3235                ldelay.getElementsByTagName("Ref").item(0).getFirstChild()
3236                  .getNodeValue()
3237                    +" as a reference is not defined in Data Section");
3238          }
3239          else
3240          {
3241            theDelay = Double.parseDouble(
3242              ldelay.getFirstChild().getNodeValue());
3243          }
3244
3245          double outVal;
3246          
3247          outVal = layerStructure.connect(
3248            lfrom.getAttributeNode("prefix").getNodeValue(),
3249            lfrom.getAttributeNode("suffix").getNodeValue(),
3250            lto.getAttributeNode("prefix").getNodeValue(),
3251            lto.getAttributeNode("suffix").getNodeValue(),
3252            sty,
3253            theStr*Double.parseDouble(
3254              lmulti.getFirstChild().getNodeValue())
3255              + Double.parseDouble(loffset.getFirstChild().getNodeValue()),
3256            iType,
3257            theDelay,
3258            conMatrix,
3259            sconMatrix,
3260            hostId,
3261            periodic);
3262          if(outVal > maxOutput) maxOutput = outVal;
3263        }
3264      }
3265
3266      //read layers probability general connections;
3267      
3268      nList = conns.getElementsByTagName("GPConnection"); //loop connections
3269      
3270      for(int it= 0 ; it< nList.getLength(); it++) // add all the layers;
3271      {
3272        int max=1;
3273        
3274        boolean str_matrix; // strength matrix exist or not
3275        
3276        NodeList from = ((Element)(nList.item(it))).getElementsByTagName(
3277          "FromLayer");
3278        
3279        if(from.getLength() !=1) max = from.getLength();
3280        
3281        NodeList to =  ((Element)(nList.item(it))).getElementsByTagName(
3282          "ToLayer");
3283        
3284        if(to.getLength() !=1 && max !=1 && to.getLength() != max)
3285          throw new RuntimeException("number does not match");
3286        
3287        if(to.getLength() !=1 ) max = to.getLength();
3288
3289        NodeList pmatrix = ((Element)(nList.item(it))).getElementsByTagName(
3290          "PMatrix");
3291        
3292        if(pmatrix.getLength() !=1 && max !=1 && pmatrix.getLength() != max)
3293            throw new RuntimeException("number does not match");
3294        
3295        if(pmatrix.getLength() !=1 ) max = pmatrix.getLength();
3296
3297        NodeList smatrix = ((Element)(nList.item(it))).getElementsByTagName(
3298          "SMatrix");
3299        
3300        if(smatrix.getLength() ==0)
3301        {
3302          str_matrix = false;
3303        }
3304        else
3305        {
3306          if(smatrix.getLength() !=1 && max !=1
3307            && smatrix.getLength() != max)
3308            throw new RuntimeException("number does not match");
3309          
3310          if(smatrix.getLength() !=1 ) max = smatrix.getLength();
3311          
3312          str_matrix = true;
3313        }
3314
3315        NodeList orientation = ((Element)(nList.item(it)))
3316          .getElementsByTagName("Rotation");
3317        
3318        if(orientation.getLength() !=1
3319          && max != 1
3320          && orientation.getLength() != max)
3321          throw new RuntimeException("number does not match");
3322        
3323        if(orientation.getLength() !=1 ) max = orientation.getLength();
3324
3325        NodeList type = ((Element)(nList.item(it))).getElementsByTagName(
3326          "Type");
3327        
3328        if(type.getLength() !=1
3329          && max != 1
3330          && type.getLength() != max)
3331          throw new RuntimeException("number does not match");
3332        
3333        if(type.getLength() !=1 ) max = type.getLength();
3334        
3335        NodeList str = ((Element)(nList.item(it)))
3336          .getElementsByTagName("Strength");
3337        
3338        if ( str.getLength() != 1
3339          && max !=1
3340          && str.getLength() != max)
3341          throw new RuntimeException("number does not match");
3342        
3343        if(str.getLength() !=1 ) max = str.getLength();
3344        
3345        NodeList multi = ((Element)(nList.item(it))).getElementsByTagName(
3346          "Multiplier");
3347        
3348        if(multi.getLength() !=1 && max !=1 && multi.getLength() != max)
3349          throw new RuntimeException("number does not match");
3350        
3351        if(multi.getLength() !=1 ) max = multi.getLength();
3352        
3353        NodeList offset = ((Element)(nList.item(it)))
3354          .getElementsByTagName("Offset");
3355        
3356        if(offset.getLength() !=1
3357          && max != 1
3358          && offset.getLength() != max)
3359          throw new RuntimeException("number does not match");
3360        
3361        if(offset.getLength() !=1 ) max = offset.getLength();
3362        
3363        NodeList delay = ((Element)(nList.item(it)))
3364          .getElementsByTagName("Delay");
3365        
3366        if ( delay.getLength() != 1
3367          && max != 1
3368          && delay.getLength() != max )
3369          throw new RuntimeException("number does not match");
3370        
3371        if(delay.getLength() !=1 ) max = delay.getLength();
3372        
3373        // System.out.println("max"+max);
3374
3375        for(int i=0; i < max; i++)
3376        {
3377          Element
3378            lmatrix,
3379            eSmatrix;
3380          
3381          if(pmatrix.getLength()==max)
3382          {
3383            lmatrix = (Element)(pmatrix.item(i));
3384          }
3385          else
3386          {
3387            lmatrix = (Element)(pmatrix.item(0));
3388          }
3389
3390          double [][] conMatrix;
3391          
3392          if(lmatrix.getElementsByTagName("Ref").getLength()>0)
3393          {
3394            conMatrix = matrixDataMap.get(
3395              lmatrix.getElementsByTagName("Ref").item(0).getFirstChild()
3396                .getNodeValue());
3397            
3398            if(conMatrix == null)
3399              throw new RuntimeException(
3400                lmatrix.getElementsByTagName("Ref").item(0).getFirstChild()
3401                  .getNodeValue()
3402                    +" as a reference is not defined in Data Section");
3403          }
3404          else 
3405          {
3406            NodeList rows = lmatrix.getElementsByTagName("Row");
3407            
3408            String firstRow = rows.item(0).getFirstChild().getNodeValue();
3409            
3410            String sep [] = firstRow.split("[a-z,\t ]");
3411
3412            conMatrix = new double [rows.getLength()][sep.length];
3413
3414            for(int colId=0; colId < sep.length; colId++)
3415            {
3416              conMatrix[0][colId]=Double.parseDouble(sep[colId]);
3417            }
3418
3419            for( int rowId=1; rowId<rows.getLength(); rowId++)
3420            {
3421              firstRow = rows.item(rowId).getFirstChild().getNodeValue();
3422              
3423              sep = firstRow.split("[a-z,\t ]");
3424              
3425              for(int colId=0; colId < sep.length; colId++)
3426              {
3427                conMatrix[rowId][colId]=Double.parseDouble(sep[colId]);
3428              }
3429            }
3430          }
3431
3432          // System.out.println(sep.length);
3433          
3434          double [][] sconMatrix = null;
3435
3436          if(str_matrix) // if strength matrix exists
3437          {
3438            if(smatrix.getLength()==max)
3439            {
3440              eSmatrix = (Element)(smatrix.item(i));
3441            }
3442            else
3443            {
3444              eSmatrix = (Element)(smatrix.item(0));
3445            }
3446
3447            if(eSmatrix.getElementsByTagName("Ref").getLength()>0)
3448            {
3449              sconMatrix = matrixDataMap.get(
3450                eSmatrix.getElementsByTagName("Ref").item(0).getFirstChild()
3451                  .getNodeValue());
3452              
3453              if(sconMatrix == null)
3454                throw new RuntimeException(
3455                  eSmatrix.getElementsByTagName("Ref").item(0)
3456                    .getFirstChild().getNodeValue()
3457                    +" as a reference is not defined in Data Section");
3458            }
3459            else
3460            {
3461              NodeList rows = eSmatrix.getElementsByTagName("Row");
3462              
3463              String firstRow = rows.item(0).getFirstChild().getNodeValue();
3464              
3465              String [] sep = firstRow.split("[a-z,\t ]");
3466              
3467              // System.out.println(sep.length);
3468
3469              sconMatrix = new double [rows.getLength()][sep.length];
3470              
3471              for(int colId=0; colId < sep.length; colId++)
3472              {
3473                sconMatrix[0][colId]=Double.parseDouble(sep[colId]);
3474              }
3475
3476              for( int rowId=1; rowId<rows.getLength(); rowId++)
3477              {
3478                firstRow = rows.item(rowId).getFirstChild().getNodeValue();
3479                
3480                sep = firstRow.split("[a-z,\t ]");
3481                
3482                for(int colId=0; colId < sep.length; colId++)
3483                {
3484                  sconMatrix[rowId][colId]=Double.parseDouble(sep[colId]);
3485                }
3486              }
3487            }
3488          }
3489
3490          Element lrotation;
3491          
3492          if(orientation.getLength()==max)
3493          {
3494            lrotation = (Element)(orientation.item(i));
3495          }
3496          else
3497          {
3498            lrotation = (Element)(orientation.item(0));
3499          }
3500
3501          int rot = Integer.parseInt(
3502            lrotation.getFirstChild().getNodeValue())/90;
3503
3504          if(rot>0)
3505          {
3506            for(int ii=0 ; ii< rot; ii++)
3507            {
3508              conMatrix = FunUtil.rRotate90(conMatrix);
3509              
3510              if(str_matrix)sconMatrix = FunUtil.rRotate90(sconMatrix);
3511            }
3512          }
3513          else if(rot <0)
3514          {
3515            for(int ii=0 ; ii< -rot; ii++)
3516            {
3517              conMatrix = FunUtil.lRotate90(conMatrix);
3518              
3519              if(str_matrix)sconMatrix = FunUtil.lRotate90(sconMatrix);
3520            }
3521          }
3522          
3523          //remember to change the rows matrix. use rows
3524          
3525          Element lfrom;
3526          
3527          if(from.getLength()==max)
3528          {
3529            lfrom = (Element)(from.item(i));
3530          }
3531          else
3532          {
3533            lfrom = (Element)(from.item(0));
3534          }
3535          
3536          Element lto;
3537          
3538          if(to.getLength()==max)
3539          {
3540            lto = (Element)(to.item(i));
3541          }
3542          else
3543          {
3544            lto = (Element)(to.item(0));
3545          }
3546
3547          Element ltype;
3548          
3549          if(type.getLength()==max)
3550          {
3551            ltype = (Element)(type.item(i));
3552          }
3553          else
3554          {
3555            ltype = (Element)(type.item(0));
3556          }
3557
3558          final int  iType = parseSynapseType ( ltype );
3559          
3560          Element lstr;
3561          
3562          if(str.getLength()==max)
3563          {
3564            lstr = (Element)(str.item(i));
3565          }
3566          else
3567          {
3568            lstr = (Element)(str.item(0));
3569          }
3570          
3571          Element lmulti;
3572          
3573          if(multi.getLength()==max)
3574          {
3575            lmulti = (Element)(multi.item(i));
3576          }
3577          else
3578          {
3579            lmulti = (Element)(multi.item(0));
3580          }
3581          
3582          Element loffset;
3583          
3584          if(offset.getLength()==max)
3585          {
3586            loffset = (Element)(offset.item(i));
3587          }
3588          else
3589          {
3590            loffset = (Element)(offset.item(0));
3591          }
3592          
3593          Element ldelay;
3594          
3595          if(delay.getLength()==max)
3596          {
3597            ldelay = (Element)(delay.item(i));
3598          }
3599          else
3600          {
3601            ldelay = (Element)(delay.item(0));
3602          }
3603          
3604/*
3605          System.out.print(lfrom.getAttributeNode("prefix").getNodeValue()
3606            +" "+lfrom.getAttributeNode("suffix").getNodeValue()+" "
3607            +lto.getAttributeNode("prefix").getNodeValue()+" "
3608            +lto.getAttributeNode("suffix").getNodeValue());
3609          System.out.print(" "+sty);
3610          System.out.print(" "+lstr.getFirstChild().getNodeValue());
3611          System.out.print(" "+lmulti.getFirstChild().getNodeValue());
3612          System.out.print(" "+loffset.getFirstChild().getNodeValue());
3613          System.out.print(" "+ldelay.getFirstChild().getNodeValue());
3614          System.out.println();
3615*/
3616/*
3617          if(connected)
3618          {
3619          p.print(lfrom.getAttributeNode("prefix").getNodeValue()+" "
3620            +lfrom.getAttributeNode("suffix").getNodeValue()+" "
3621            +lto.getAttributeNode("prefix").getNodeValue()+" "
3622            +lto.getAttributeNode("suffix").getNodeValue());
3623          p.print(" "+sty);
3624          p.print(" "+lstr.getFirstChild().getNodeValue());
3625          p.print(" "+lmulti.getFirstChild().getNodeValue());
3626          p.print(" "+loffset.getFirstChild().getNodeValue());
3627          p.print(" "+ldelay.getFirstChild().getNodeValue());
3628          p.println();
3629          }
3630*/
3631/*
3632          for(int ii=0; ii < conMatrix.length; ii++)
3633          {
3634          for(int jj=0 ; jj < conMatrix[0].length; jj++)
3635          {
3636          System.out.print(conMatrix[ii][jj]+" ");
3637          }
3638          System.out.println();
3639          }
3640*/
3641          Double theStr;
3642          
3643          if(lstr.getElementsByTagName("Ref").getLength()>0)
3644          {
3645            theStr = doubleDataMap.get(
3646              lstr.getElementsByTagName("Ref").item(0).getFirstChild()
3647                .getNodeValue());
3648            
3649            if(theStr == null)
3650              throw new RuntimeException(
3651                lstr.getElementsByTagName("Ref").item(0).getFirstChild()
3652                  .getNodeValue()
3653                    +" as a reference is not defined in Data Section");
3654          }
3655          else
3656          {
3657            theStr = Double.parseDouble(
3658              lstr.getFirstChild().getNodeValue());
3659          }
3660          
3661          Double theDelay;
3662          
3663          if(ldelay.getElementsByTagName("Ref").getLength()>0)
3664          {
3665            theDelay = doubleDataMap.get(
3666              ldelay.getElementsByTagName("Ref").item(0).getFirstChild()
3667                .getNodeValue());
3668            
3669            if(theDelay == null)
3670              throw new RuntimeException(
3671                ldelay.getElementsByTagName("Ref").item(0).getFirstChild()
3672                  .getNodeValue()
3673                    +" as a reference is not defined in Data Section");
3674          }
3675          else
3676          {
3677            theDelay = Double.parseDouble(
3678              ldelay.getFirstChild().getNodeValue());
3679          }
3680
3681          double outVal;
3682
3683          outVal = layerStructure.connectgp(
3684            lfrom.getAttributeNode("prefix").getNodeValue(),
3685            lfrom.getAttributeNode("suffix").getNodeValue(),
3686            lto.getAttributeNode("prefix").getNodeValue(),
3687            lto.getAttributeNode("suffix").getNodeValue(),
3688            theStr * Double.parseDouble(
3689              lmulti.getFirstChild().getNodeValue())
3690              + Double.parseDouble(
3691                loffset.getFirstChild().getNodeValue()),
3692            iType,
3693            theDelay,
3694            conMatrix,
3695            sconMatrix,
3696            hostId);
3697          
3698          if(outVal > maxOutput) maxOutput = outVal;
3699        }
3700      }
3701
3702      //read layers;
3703      
3704      nList = conns.getElementsByTagName("Connection");
3705      
3706      for(int it= 0 ; it< nList.getLength(); it++) // add all the layers;
3707      {
3708        String perio = ((Element)(nList.item(it)))
3709          .getAttributeNode("periodic").getValue();
3710        
3711        boolean periodic;
3712        
3713        if(perio.equals("true") || perio.equals("TRUE"))
3714        {
3715          periodic = true;
3716        }
3717        else
3718        {
3719          periodic = false;
3720        }
3721
3722        Element matrix = (Element)(((Element)(nList.item(it)))
3723          .getElementsByTagName("Matrix").item(0));
3724
3725        NodeList rows = matrix.getElementsByTagName("Row");
3726        
3727        String firstRow = rows.item(0).getFirstChild().getNodeValue();
3728        
3729        String sep [] = firstRow.split("[a-z,\t ]");
3730        
3731        // p.println(sep.length);
3732        // p.flush();
3733        
3734        double [][]
3735          conMatrix = new double [rows.getLength()][sep.length];
3736        
3737        for(int colId=0; colId < sep.length; colId++)
3738        {
3739          conMatrix[0][colId]=Double.parseDouble(sep[colId]);
3740        }
3741
3742        for( int rowId=1; rowId<rows.getLength(); rowId++)
3743        {
3744          firstRow = rows.item(rowId).getFirstChild().getNodeValue();
3745          
3746          sep = firstRow.split("[a-z,\t ]");
3747          
3748          for(int colId=0; colId < sep.length; colId++)
3749          {
3750            conMatrix[rowId][colId]=Double.parseDouble(sep[colId]);
3751          }
3752        }
3753/*
3754      for(int ii=0; ii < conMatrix.length; ii++)
3755      {
3756        for(int jj=0 ; jj < conMatrix[0].length; jj++)
3757        {
3758          p.print(conMatrix[ii][jj]+" ");
3759        }
3760        p.println();
3761      }
3762*/
3763
3764        int rotation = Integer.parseInt(
3765          ((Element)(nList.item(it))).getElementsByTagName("Rotation")
3766          .item(0).getFirstChild().getNodeValue())/90;
3767
3768        if(rotation>0)
3769        {
3770          for(int ii=0 ; ii< rotation; ii++)
3771          {
3772            conMatrix = FunUtil.rRotate90(conMatrix);
3773          }
3774        }
3775        else if(rotation <0)
3776        {
3777          for(int ii=0 ; ii< -rotation; ii++)
3778          {
3779            conMatrix = FunUtil.lRotate90(conMatrix);
3780          }
3781        }
3782/*
3783        for(int ii=0; ii < conMatrix.length; ii++)
3784        {
3785          for(int jj=0 ; jj < conMatrix[0].length; jj++)
3786          {
3787            p.print(conMatrix[ii][jj]+" ");
3788          }
3789          p.println();
3790        }
3791*/
3792
3793        Element from = (Element)(((Element)(nList.item(it)))
3794          .getElementsByTagName("FromLayer").item(0));
3795        
3796        Element to = (Element)(((Element)(nList.item(it)))
3797          .getElementsByTagName("ToLayer").item(0));
3798        
3799        final Element  styleElement = getFirstElement (
3800          ( Element ) nList.item ( it ),
3801          "Style" );
3802        
3803        final boolean  sty = parseVergenceStyle ( styleElement );
3804        
3805        final Element  typeElement = getFirstElement (
3806          ( Element ) nList.item ( it ),
3807          "Type" );
3808
3809        final int  type = parseSynapseType ( typeElement );
3810/*
3811        System.out.println(
3812          ((Element)(from.getElementsByTagName("Prefix").item(0)))
3813          .getFirstChild().getNodeValue()+" "
3814          + ((Element)(from.getElementsByTagName("Suffix").item(0)))
3815          .getFirstChild().getNodeValue()+" "
3816          + ((Element)(to.getElementsByTagName("Prefix").item(0)))
3817          .getFirstChild().getNodeValue()+" "
3818          + ((Element)(to.getElementsByTagName("Suffix").item(0)))
3819          .getFirstChild().getNodeValue());
3820*/
3821/*
3822        if(connected)
3823        {
3824          p.println("str"+Double.parseDouble(
3825            ((Element)(nList.item(it))).getElementsByTagName("Strength")
3826            .item(0).getFirstChild().getNodeValue())
3827            * Double.parseDouble(((Element)(nList.item(it)))
3828            .getElementsByTagName("Multiplier").item(0).getFirstChild()
3829            .getNodeValue())+ Double.parseDouble(((Element)(nList.item(it)))
3830            .getElementsByTagName("Offset").item(0).getFirstChild()
3831            .getNodeValue()));
3832            
3833          p.println(((Element)(from.getElementsByTagName("Prefix").item(0)))
3834            .getFirstChild().getNodeValue()+ " "
3835            +((Element)(from.getElementsByTagName("Suffix").item(0)))
3836              .getFirstChild().getNodeValue()+" "
3837            +((Element)(to.getElementsByTagName("Prefix").item(0)))
3838              .getFirstChild().getNodeValue()+" "
3839            +((Element)(to.getElementsByTagName("Suffix").item(0)))
3840              .getFirstChild().getNodeValue());
3841        }
3842*/
3843        double outVal;
3844        
3845        outVal = layerStructure.connect(
3846          ((Element)(from.getElementsByTagName("Prefix").item(0)))
3847            .getFirstChild().getNodeValue(),
3848          ((Element)(from.getElementsByTagName("Suffix").item(0)))
3849            .getFirstChild().getNodeValue(),
3850          ((Element)(to.getElementsByTagName("Prefix").item(0)))
3851            .getFirstChild().getNodeValue(),
3852          ((Element)(to.getElementsByTagName("Suffix").item(0)))
3853            .getFirstChild().getNodeValue(),
3854          sty,
3855          Double.parseDouble(
3856            ((Element)(nList.item(it))).getElementsByTagName("Strength")
3857            .item(0).getFirstChild().getNodeValue())
3858            * Double.parseDouble(
3859              ((Element)(nList.item(it))).getElementsByTagName("Multiplier")
3860              .item(0).getFirstChild().getNodeValue())
3861              + Double.parseDouble(((Element)(nList.item(it)))
3862                .getElementsByTagName("Offset").item(0).getFirstChild()
3863                .getNodeValue()),
3864          type,
3865          Double.parseDouble(
3866            ((Element)(nList.item(it))).getElementsByTagName("Delay")
3867            .item(0).getFirstChild().getNodeValue()),
3868          conMatrix,
3869          hostId,
3870          periodic);
3871        
3872        if(outVal > maxOutput) maxOutput = outVal;
3873      }
3874      
3875      return maxOutput;
3876    }
3877
3878    /***********************************************************************
3879    * map the neurons, build up the index
3880    ***********************************************************************/
3881    public void parseMapCells(int hostId)
3882    ////////////////////////////////////////////////////////////////////////
3883    {
3884      NodeList nList = rootElement.getElementsByTagName("OverallConfiguration");
3885      
3886      Element gloable = (Element) nList.item(0);
3887
3888      // layer size
3889      
3890      xEdgeLength = Integer.parseInt((gloable.getElementsByTagName("xEdgeLength").item(0)).getFirstChild().getNodeValue());
3891      
3892      yEdgeLength = Integer.parseInt((gloable.getElementsByTagName("yEdgeLength").item(0)).getFirstChild().getNodeValue());
3893      
3894      if(gloable.getElementsByTagName("DataFileName").getLength()>0)
3895      {
3896        outFile = (gloable.getElementsByTagName("DataFileName").item(0)).getFirstChild().getNodeValue();
3897      }
3898      
3899      // System.out.println(xEdgeLength);
3900      
3901      // System.out.println(yEdgeLength);
3902      
3903      parallelHost = Integer.parseInt(
3904        (gloable.getElementsByTagName("TrialHost").item(0))
3905        .getFirstChild().getNodeValue());
3906
3907      // Host info
3908      
3909      Element ele = (Element)
3910        gloable.getElementsByTagName("NetHost").item(0);
3911
3912      numOfHosts = Integer.parseInt(
3913        ele.getElementsByTagName("Number")
3914        .item(0).getFirstChild().getNodeValue());
3915      
3916      //  System.out.println(numOfHosts);
3917      
3918      Element method = (Element)
3919        ele.getElementsByTagName("MapMethod").item(0);
3920      
3921      aSec = Integer.parseInt(method.getAttributeNode("A").getValue());
3922      
3923      bSec = Integer.parseInt(method.getAttributeNode("B").getValue());
3924      
3925      mapType=LayerStructure.ABMAP;
3926
3927      layerStructure = new LayerStructure (
3928        modelFactory,
3929        numOfHosts,
3930        xEdgeLength,
3931        yEdgeLength );
3932
3933      if(aSec*bSec!=numOfHosts)
3934        throw new RuntimeException(aSec+"x"+bSec+"/="+numOfHosts);
3935
3936      backgroundFrequency = Double.parseDouble(
3937        (gloable.getElementsByTagName("BackgroundFrequency").item(0))
3938        .getFirstChild().getNodeValue());
3939      
3940      backgroundStrength = Double.parseDouble(
3941        (gloable.getElementsByTagName("BackgroundStrength").item(0))
3942        .getFirstChild().getNodeValue());
3943      
3944      final Element  backgroundTypeElement
3945        = getFirstElement ( gloable, "BackgroundType" );
3946      
3947      final int  bChannel = parseSynapseType ( backgroundTypeElement );
3948
3949      //read layers;
3950      
3951      nList = rootElement.getElementsByTagName("Layers");
3952      
3953      ele = (Element)nList.item(0);
3954      
3955      NodeList lay = ele.getElementsByTagName("Layer");
3956      
3957      for(int it= 0 ; it< lay.getLength(); it++) // add all the layers;
3958      {
3959        layerStructure.addLayer(
3960          ((Element)(lay.item(it))).getElementsByTagName("Prefix")
3961            .item(0).getFirstChild().getNodeValue(),
3962          ((Element)(lay.item(it))).getElementsByTagName("Suffix")
3963            .item(0).getFirstChild().getNodeValue(),
3964          Integer.parseInt(((Element)(lay.item(it)))
3965            .getElementsByTagName("MultiX")
3966            .item(0).getFirstChild().getNodeValue()),
3967          Integer.parseInt(((Element)(lay.item(it)))
3968            .getElementsByTagName("MultiY").item(0)
3969            .getFirstChild().getNodeValue()),
3970          ((Element)(lay.item(it))).getElementsByTagName("NeuronType")
3971            .item(0).getFirstChild().getNodeValue());
3972      }
3973      
3974      // System.out.println("total Neurons"+ls.totalNumNeurons());
3975      
3976      switch(mapType)
3977      {
3978        case LayerStructure.ABMAP:
3979          
3980          layerStructure.abmapcells(aSec,bSec,hostId);
3981          
3982          break;
3983          
3984        case LayerStructure.LINEMAP:
3985          
3986          layerStructure.mapcells();
3987          
3988          break;
3989          
3990        default:
3991          
3992          break;
3993      }
3994      
3995      layerStructure.neuronIndex(hostId);
3996    }
3997
3998/*
3999    public String[] plotLine(int x1,int y1,int x2,int y2)
4000    ////////////////////////////////////////////////////////////////////////
4001    {
4002      ArrayList<String> corr =  new ArrayList<String>();
4003      
4004      if ( x1> xEdgeLength || x2>xEdgeLength || y1>yEdgeLength
4005        || y2> yEdgeLength )
4006        throw new RuntimeException("out of range error");
4007
4008      return  corr.toArray(new String[0]);
4009    }
4010*/
4011
4012    /***********************************************************************
4013    * Parse the experiment section, build stimuli accordingly
4014    ***********************************************************************/
4015    public void  parseExp ( int  hostId)
4016    ////////////////////////////////////////////////////////////////////////
4017    {
4018      LOGGER.trace ( "parseExp(hostId) entering" );
4019      
4020      NodeList nList = ((Element)
4021        ((rootElement.getElementsByTagName("Experiment")).item(0)))
4022        .getElementsByTagName("SubExperiment");
4023      
4024      // Element gloable = (Element) nList.item(0);
4025      
4026      SubExp[] subs= new SubExp[nList.getLength()];
4027      
4028      for(int it= 0 ; it< nList.getLength(); it++) // add all the layers;
4029      {
4030        final Element  subExperimentElement = (Element)nList.item(it);
4031
4032        NodeList inputs
4033          = subExperimentElement.getElementsByTagName("Input");
4034        
4035        Stimulus[] stis = new Stimulus[inputs.getLength()];
4036
4037        for(int iter=0; iter< inputs.getLength(); iter++)
4038        {
4039          NodeList mat = ((Element)(inputs.item(iter)))
4040            .getElementsByTagName("Matrix");
4041          
4042          double [][] conMatrix;
4043          
4044          if(mat.getLength()!=0) //filter for the retina
4045          {
4046            Element matrix = (Element)(mat.item(0));
4047
4048            if(matrix.getElementsByTagName("Ref").getLength()>0)
4049            {
4050              conMatrix = matrixDataMap.get(
4051                matrix.getElementsByTagName("Ref").item(0).getFirstChild()
4052                  .getNodeValue());
4053              
4054              if(conMatrix == null)
4055                throw new RuntimeException(
4056                  matrix.getElementsByTagName("Ref").item(0)
4057                    .getFirstChild().getNodeValue()
4058                      +" as a reference is not defined in Data Section");
4059            }
4060            else
4061            {
4062              NodeList rows = matrix.getElementsByTagName("Row");
4063              
4064              String firstRow = rows.item(0).getFirstChild().getNodeValue();
4065              
4066              String sep [] = firstRow.split("[a-z,\t ]");
4067              
4068              // System.out.println(sep.length);
4069              
4070              conMatrix = new double [rows.getLength()][sep.length];
4071              
4072              for(int colId=0; colId < sep.length; colId++)
4073              {
4074                conMatrix[0][colId]=Double.parseDouble(sep[colId]);
4075              }
4076
4077              for( int rowId=1; rowId<rows.getLength(); rowId++)
4078              {
4079                firstRow = rows.item(rowId).getFirstChild().getNodeValue();
4080                
4081                sep = firstRow.split("[a-z,\t ]");
4082                
4083                for(int colId=0; colId < sep.length; colId++)
4084                {
4085                  conMatrix[rowId][colId]=Double.parseDouble(sep[colId]);
4086                }
4087              }
4088            }
4089          }
4090          else
4091          {
4092            conMatrix = new double [1][1];
4093            
4094            conMatrix[0][0]=1.0;
4095          }
4096
4097          final Element  typeElement = ( Element )
4098            ((Element)inputs.item(iter))
4099            .getElementsByTagName("Type").item(0);
4100          
4101          final int  type = parseSynapseType ( typeElement );
4102          
4103          // System.out.println(Double.parseDouble(
4104          //   ((Element)inputs.item(iter)).getElementsByTagName(
4105          //   "Strength").item(0).getFirstChild().getNodeValue()));
4106          
4107          stis[iter] = new Stimulus (
4108            modelFactory,
4109            this,
4110            Double.parseDouble(
4111              ((Element)inputs.item(iter)).getElementsByTagName("Strength")
4112                .item(0).getFirstChild().getNodeValue()),
4113            type,
4114            Double.parseDouble(((Element)inputs.item(iter))
4115              .getAttributeNode("on").getValue()),
4116            Double.parseDouble(((Element)inputs.item(iter))
4117              .getAttributeNode("off").getValue()),
4118            Double.parseDouble(((Element)inputs.item(iter))
4119              .getElementsByTagName("Frequency").item(0).getFirstChild()
4120              .getNodeValue()),
4121            Double.parseDouble(((Element)inputs.item(iter))
4122              .getElementsByTagName("Decay").item(0).getFirstChild()
4123              .getNodeValue()),
4124            idum,
4125            Integer.parseInt(((Element)inputs.item(iter))
4126              .getElementsByTagName("Channel").item(0).getFirstChild()
4127              .getNodeValue()));
4128
4129          NodeList plots = ((Element)inputs.item(iter))
4130            .getElementsByTagName("Stimulus");
4131          
4132          for(int pl=0; pl<plots.getLength(); pl++)
4133          {
4134            NodeList lines = ((Element)plots.item(pl))
4135              .getElementsByTagName("Line");
4136            
4137            for(int li = 0 ; li < lines.getLength(); li++)
4138            {
4139              String sep [] = ((Element)lines.item(li))
4140                .getFirstChild().getNodeValue().split("[a-z,\t ]");
4141              
4142              if(sep.length!=4)
4143                throw new RuntimeException("need 4 arguments");
4144              
4145              stis[iter].plotLine(
4146                Integer.parseInt(sep[0]),
4147                Integer.parseInt(sep[1]),
4148                Integer.parseInt(sep[2]),
4149                Integer.parseInt(sep[3]),
4150                ((Element)inputs.item(iter))
4151                  .getElementsByTagName("Prefix").item(0)
4152                  .getFirstChild().getNodeValue(),
4153                ((Element)inputs.item(iter))
4154                  .getElementsByTagName("Suffix").item(0)
4155                  .getFirstChild().getNodeValue(),hostId);
4156            }
4157            
4158            NodeList squares = ((Element)plots.item(pl))
4159              .getElementsByTagName("Square");
4160            
4161            for(int li = 0 ; li < squares.getLength(); li++)
4162            {
4163              String sep [] = ((Element)squares.item(li))
4164                .getFirstChild().getNodeValue().split("[a-z,\t ]");
4165              
4166              if(sep.length!=4)
4167                throw new RuntimeException("need 4 arguments");
4168              
4169              stis[iter].plotSquare(
4170                Integer.parseInt(sep[0]),
4171                Integer.parseInt(sep[1]),
4172                Integer.parseInt(sep[2]),
4173                Integer.parseInt(sep[3]),
4174                ((Element)inputs.item(iter))
4175                  .getElementsByTagName("Prefix").item(0)
4176                    .getFirstChild().getNodeValue(),
4177                ((Element)inputs.item(iter))
4178                  .getElementsByTagName("Suffix").item(0)
4179                    .getFirstChild().getNodeValue(),hostId);
4180            }
4181            
4182            NodeList image
4183              = ((Element)plots.item(pl)).getElementsByTagName("Image");
4184            
4185            for(int li = 0 ; li < image.getLength(); li++)
4186            {
4187              String reverse = ((Element)
4188                image.item(li)).getAttributeNode("reverse").getValue();
4189              
4190              double gamma
4191                = Double.parseDouble(
4192                  ((Element)image.item(li))
4193                    .getAttributeNode("gamma").getValue());
4194              
4195              double k
4196                = Double.parseDouble(((Element)image.item(li))
4197                  .getAttributeNode("threshold").getValue());
4198              
4199              if(reverse.equals("true") || reverse.equals("TRUE"))
4200              {
4201                stis[iter].plotRImg(
4202                  ((Element)inputs.item(iter))
4203                    .getElementsByTagName("Prefix").item(0).getFirstChild()
4204                    .getNodeValue(),
4205                  ((Element)inputs.item(iter))
4206                    .getElementsByTagName("Suffix").item(0).getFirstChild()
4207                    .getNodeValue(),
4208                  ((Element)image.item(li)).getFirstChild().getNodeValue(),
4209                  conMatrix,
4210                  gamma,
4211                  k,
4212                  hostId);
4213              }
4214              else
4215              {
4216                stis[iter].plotImg(
4217                  ((Element)inputs.item(iter))
4218                    .getElementsByTagName("Prefix").item(0).getFirstChild()
4219                      .getNodeValue(),
4220                  ((Element)inputs.item(iter))
4221                    .getElementsByTagName("Suffix").item(0).getFirstChild()
4222                      .getNodeValue(),
4223                  ((Element)image.item(li)).getFirstChild().getNodeValue(),
4224                  conMatrix,
4225                  gamma,
4226                  k,
4227                  hostId);
4228              }
4229            }
4230
4231            NodeList matrixplot = ((Element)plots.item(pl))
4232              .getElementsByTagName("PlotMatrix");
4233            
4234            for(int li = 0 ; li < matrixplot.getLength(); li++)
4235            {
4236              int cenX = Integer.parseInt(
4237                ((Element)matrixplot.item(li)).getAttributeNode("centerX")
4238                  .getValue());
4239              
4240              int cenY = Integer.parseInt(((Element)matrixplot.item(li))
4241                .getAttributeNode("centerY").getValue());
4242
4243              double [][] plotMatrix;
4244              
4245              plotMatrix = matrixDataMap.get(
4246                ((Element)matrixplot.item(li)).getElementsByTagName("Ref")
4247                  .item(0).getFirstChild().getNodeValue());
4248              
4249              if(plotMatrix == null)
4250                throw new RuntimeException(
4251                  ((Element)matrixplot.item(li)).getElementsByTagName("Ref")
4252                    .item(0).getFirstChild().getNodeValue()
4253                      +" as a reference is not defined in Data Section");
4254
4255              stis[iter].plotMatrix(
4256                ((Element)inputs.item(iter)).getElementsByTagName("Prefix")
4257                  .item(0).getFirstChild().getNodeValue(),
4258                ((Element)inputs.item(iter)).getElementsByTagName("Suffix")
4259                  .item(0).getFirstChild().getNodeValue(),
4260                cenX,
4261                cenY,
4262                plotMatrix,
4263                hostId);
4264            }
4265
4266            NodeList back = ((Element)plots.item(pl)).getElementsByTagName(
4267              "Background");
4268            
4269            for(int li = 0 ; li < back.getLength(); li++)
4270            {
4271              stis[iter].background(
4272                ((Element)inputs.item(iter)).getElementsByTagName("Prefix")
4273                  .item(0).getFirstChild().getNodeValue(),
4274                ((Element)inputs.item(iter)).getElementsByTagName("Suffix")
4275                  .item(0).getFirstChild().getNodeValue(),
4276                hostId);    
4277            }
4278
4279            squares = ((Element)plots.item(pl))
4280              .getElementsByTagName("FilledSquare");
4281            
4282            for(int li = 0 ; li < squares.getLength(); li++)
4283            {
4284              String sep [] = ((Element)squares.item(li))
4285                .getFirstChild().getNodeValue().split("[a-z,\t ]");
4286              
4287              if(sep.length!=4)
4288                throw new RuntimeException("need 4 arguments");
4289              
4290              stis[iter].plotFilledSquare(
4291                Integer.parseInt(sep[0]),
4292                Integer.parseInt(sep[1]),
4293                Integer.parseInt(sep[2]),
4294                Integer.parseInt(sep[3]),
4295                ((Element)inputs.item(iter))
4296                  .getElementsByTagName("Prefix").item(0).getFirstChild()
4297                    .getNodeValue(),
4298                ((Element)inputs.item(iter)).getElementsByTagName("Suffix")
4299                  .item(0).getFirstChild().getNodeValue(),hostId);
4300            }
4301          }
4302          // System.out.println(stis[iter].init(iter));
4303        } // END: for inputs
4304        
4305        // stis[it].pas=null; //release the memory
4306        
4307        for ( int iter=0; iter< inputs.getLength(); iter++ )
4308          stis[iter].simulatorParser=null; //release the memory
4309        
4310        final Collection<DiscreteEvent>
4311          modulatorDiscreteEventCollection
4312            = parseModulator ( subExperimentElement );        
4313
4314        subs[it] = new SubExp (
4315          Integer.parseInt (
4316            subExperimentElement.getAttributeNode("repetition").getValue()),
4317          Double.parseDouble (
4318            subExperimentElement.getAttributeNode("length").getValue()),
4319          stis,
4320          modulatorDiscreteEventCollection );
4321        
4322        subs[it].name
4323          = subExperimentElement.getAttributeNode("name").getValue();
4324        
4325        // System.out.println(subExp.getAttributeNode("length").getValue()
4326        //   + " " + subExp.getAttributeNode("repetition").getValue());
4327        //
4328      } // END: for subexp
4329
4330      // recorder part
4331      
4332      Element recorder = ((Element)
4333        ((rootElement.getElementsByTagName("Recorder")).item(0)));
4334
4335      String plotStr = recorder.getAttributeNode("plot").getValue();
4336      
4337      boolean plot;
4338      
4339      if(plotStr.equals("true") || plotStr.equals("TRUE"))
4340      {
4341        plot = true;
4342      }
4343      else
4344      {
4345        plot = false;
4346      }
4347
4348      Recorder rec = new Recorder(this, plot);
4349      
4350      // single unit electrode
4351      
4352      NodeList outputFile = recorder.getElementsByTagName("OutputFile");
4353      
4354      if ( outputFile.getLength()>0 )
4355        rec.outputFile=((Element)outputFile.item(0))
4356          .getFirstChild().getNodeValue();
4357      
4358      NodeList single = recorder.getElementsByTagName("SingleUnit");
4359      
4360      for(int su=0; su<single.getLength(); su++)
4361      {
4362        //line
4363        //      ArrayList<Integer> sUnit = new ArrayList<Integer>();
4364        
4365        NodeList
4366          line = ((Element)(single.item(su))).getElementsByTagName("Line");
4367        
4368        for(int li = 0 ; li < line.getLength(); li++)
4369        {
4370          String
4371            sep[] = ((Element)(line.item(li))).getFirstChild()
4372              .getNodeValue().split("[a-z,\t ]");
4373          
4374          rec.singleUnit.addAll (
4375            rec.addLine (
4376              Integer.parseInt(sep[0]),
4377              Integer.parseInt(sep[1]),
4378              Integer.parseInt(sep[2]),
4379              Integer.parseInt(sep[3]),
4380              ((Element)(line.item(li))).getAttributeNode("pre").getValue(),
4381              ((Element)(line.item(li))).getAttributeNode("suf").getValue(),
4382              hostId,
4383              rec.suNames));
4384        }
4385
4386        //square
4387        
4388        NodeList
4389          square = ((Element)(single.item(su))).getElementsByTagName(
4390            "Square");
4391        
4392        for(int li = 0 ; li < square.getLength(); li++)
4393        {
4394          String sep[] = ((Element)(square.item(li))).getFirstChild()
4395            .getNodeValue().split("[a-z,\t ]");
4396          
4397          rec.singleUnit.addAll(
4398            rec.addSquare(
4399              Integer.parseInt(sep[0]),
4400              Integer.parseInt(sep[1]),
4401              Integer.parseInt(sep[2]),
4402              Integer.parseInt(sep[3]),
4403              ((Element)(square.item(li))).getAttributeNode("pre")
4404                .getValue(),
4405              ((Element)(square.item(li))).getAttributeNode("suf")
4406                .getValue(),
4407              hostId,
4408              rec.suNames));
4409        }
4410        
4411        // System.out.println(rec.suNames);
4412        // System.out.println(rec.singleUnit);
4413      }
4414
4415      //multi unit electrode
4416      
4417      single = recorder.getElementsByTagName("MultiUnit");
4418      
4419      for(int su=0; su<single.getLength(); su++)
4420      {
4421        rec.timeBinSize = Double.parseDouble(
4422          ((Element)(single.item(su))).getAttributeNode("binSize")
4423            .getValue());
4424        
4425        rec.multiNames.add(
4426          ((Element)(single.item(su))).getElementsByTagName("Name")
4427            .item(0).getFirstChild().getNodeValue());
4428        
4429        //line
4430        
4431        ArrayList<Integer> mUnit = new ArrayList<Integer>();
4432        
4433        ArrayList<String> mName = new ArrayList<String>();
4434
4435        NodeList
4436          line = ((Element)(single.item(su))).getElementsByTagName("Line");
4437        
4438        for(int li = 0 ; li < line.getLength(); li++)
4439        {
4440          String sep[] = ((Element)(line.item(li))).getFirstChild()
4441            .getNodeValue().split("[a-z,\t ]");
4442          
4443          mUnit.addAll(
4444            rec.addLine(
4445              Integer.parseInt(sep[0]),
4446              Integer.parseInt(sep[1]),
4447              Integer.parseInt(sep[2]),
4448              Integer.parseInt(sep[3]),
4449              ((Element)(line.item(li))).getAttributeNode("pre").getValue(),
4450              ((Element)(line.item(li))).getAttributeNode("suf").getValue(),
4451              hostId,
4452              mName));
4453        }
4454
4455        //square
4456        
4457        NodeList square = ((Element)(single.item(su)))
4458          .getElementsByTagName("Square");
4459        
4460        for(int li = 0 ; li < square.getLength(); li++)
4461        {
4462          String sep[] = ((Element)(square.item(li)))
4463            .getFirstChild().getNodeValue().split("[a-z,\t ]");
4464          
4465          mUnit.addAll(
4466            rec.addSquare(
4467              Integer.parseInt(sep[0]),
4468              Integer.parseInt(sep[1]),
4469              Integer.parseInt(sep[2]),
4470              Integer.parseInt(sep[3]),
4471              ((Element)(square.item(li))).getAttributeNode("pre")
4472                .getValue(),
4473              ((Element)(square.item(li))).getAttributeNode("suf")
4474                .getValue(),
4475              hostId,
4476              mName));
4477        }
4478
4479        rec.multiUnit.add(mUnit);
4480        
4481        rec.neuronNames.add(mName);
4482        
4483        //System.out.println(mUnit);
4484        
4485        //System.out.println(mName);
4486      }
4487
4488      // field electrode
4489      
4490      //multi unit electrode
4491      
4492      single = recorder.getElementsByTagName("Field");
4493      
4494      for(int su=0; su<single.getLength(); su++)
4495      {
4496        rec.fieldNames.add(
4497          ((Element)(single.item(su))).getElementsByTagName("Name")
4498            .item(0).getFirstChild().getNodeValue());
4499        
4500        Layer tmpLayer = layerStructure.getLayer(
4501          ((Element)(single.item(su))).getElementsByTagName("Prefix")
4502            .item(0).getFirstChild().getNodeValue(),
4503          ((Element)(single.item(su))).getElementsByTagName("Suffix")
4504            .item(0).getFirstChild().getNodeValue());
4505        
4506        rec.fieldEle.add(tmpLayer);
4507        
4508        rec.fieldTimeBinSize = Double.parseDouble(
4509          ((Element)(single.item(su))).getAttributeNode("binSize")
4510            .getValue());
4511        
4512        rec.setLayerNeurons (
4513          tmpLayer,
4514          hostId); // for slave hosts, they need to set neurons recordable
4515      }
4516
4517      // vector plots
4518      
4519      single = recorder.getElementsByTagName("VectorMap");
4520      
4521      for(int su=0; su<single.getLength(); su++)
4522      {
4523        rec.vectorNames.add(
4524          ((Element)(single.item(su))).getElementsByTagName("Name").item(0)
4525            .getFirstChild().getNodeValue());
4526        
4527        VComponents coms = rec.addComs();
4528        
4529        NodeList comlay = ((Element)(single.item(su)))
4530          .getElementsByTagName("LayerOrientation");
4531        
4532        for( int iCom =0 ; iCom < comlay.getLength(); iCom++)
4533        {
4534          Layer tmpLayer =layerStructure.getLayer(
4535            ((Element)(comlay.item(iCom))).getAttributeNode("pre")
4536              .getValue(),
4537            ((Element)(comlay.item(iCom))).getAttributeNode("suf")
4538              .getValue()); 
4539          coms.addCom(
4540            tmpLayer,
4541            Integer.parseInt(
4542              ((Element)(comlay.item(iCom))).getFirstChild()
4543                .getNodeValue()));
4544          
4545          rec.setLayerNeurons(
4546            tmpLayer,
4547            hostId);
4548        }
4549        
4550        rec.vectorTimeBinSize= Double.parseDouble(
4551          ((Element)(single.item(su))).getAttributeNode("binSize")
4552            .getValue());
4553      }
4554
4555      // intracellular unit electrode
4556      
4557      single = recorder.getElementsByTagName("Intracellular");
4558      
4559      for(int su=0; su<single.getLength(); su++)
4560      {
4561        rec.intraNames.add(
4562          ((Element)(single.item(su))).getElementsByTagName("Name")
4563            .item(0).getFirstChild().getNodeValue());
4564        
4565        //line
4566        
4567        ArrayList<Integer> mUnit = new ArrayList<Integer>();
4568        
4569        ArrayList<String> mName = new ArrayList<String>();
4570        
4571        ArrayList<Integer> cha = new ArrayList<Integer>();
4572
4573        NodeList line = ((Element)(single.item(su)))
4574          .getElementsByTagName("Line");
4575        
4576        for(int li = 0 ; li < line.getLength(); li++)
4577        {
4578          String sep[] = ((Element)(line.item(li)))
4579            .getFirstChild().getNodeValue().split("[a-z,\t ]");
4580          
4581          mUnit.addAll(
4582            rec.addLine(
4583              Integer.parseInt(sep[0]),
4584              Integer.parseInt(sep[1]),
4585              Integer.parseInt(sep[2]),
4586              Integer.parseInt(sep[3]),
4587              ((Element)(line.item(li))).getAttributeNode("pre").getValue(),
4588              ((Element)(line.item(li))).getAttributeNode("suf").getValue(),
4589              hostId,
4590              mName));
4591        }
4592
4593        //square
4594        
4595        NodeList square = ((Element)(single.item(su)))
4596          .getElementsByTagName("Square");
4597        
4598        for(int li = 0 ; li < square.getLength(); li++)
4599        {
4600          String sep[] = ((Element)(square.item(li)))
4601            .getFirstChild().getNodeValue().split("[a-z,\t ]");
4602          
4603          mUnit.addAll(
4604            rec.addSquare(
4605              Integer.parseInt(sep[0]),
4606              Integer.parseInt(sep[1]),
4607              Integer.parseInt(sep[2]),
4608              Integer.parseInt(sep[3]),
4609              ((Element)(square.item(li))).getAttributeNode("pre")
4610                .getValue(),
4611              ((Element)(square.item(li))).getAttributeNode("suf")
4612                .getValue(),
4613              hostId,
4614              mName));
4615        }
4616
4617        // channel
4618        
4619        square = ((Element)
4620          (single.item(su))).getElementsByTagName("Channel");
4621        
4622        for(int li = 0 ; li < square.getLength(); li++)
4623        {
4624          cha.add(
4625            Integer.parseInt(
4626              ((Element)(square.item(li))).getFirstChild().getNodeValue()));
4627        }
4628        rec.intraEle.add(mUnit);
4629        
4630        rec.currChannel.add(cha);
4631      }
4632
4633      experiment = new Experiment(subs,rec);
4634      
4635      experiment.recorder.simulatorParser=null; //clear pas info;
4636      
4637      LOGGER.trace ( "parseExp(hostId) exiting" );
4638    }
4639
4640    /***********************************************************************
4641    * Find out the minimum synaptic delay from network structure. 
4642    ***********************************************************************/
4643    public void  findMinDelay ( )
4644    ////////////////////////////////////////////////////////////////////////
4645    {
4646      final NodeList
4647        delayNodeList = rootElement.getElementsByTagName ( "Delay" );
4648      
4649      final int  delayNodeListLength = delayNodeList.getLength ( );
4650      
4651      if ( delayNodeListLength == 0 )
4652      {
4653        // TODO:  I added this hack to get around null exception when just
4654        // one layer.  I am not sure if this is reasonable.  -- Croft
4655        
4656        minDelay = 0.010;
4657      }
4658      else
4659      {
4660        final Element
4661          firstDelayElement = ( Element ) delayNodeList.item ( 0 );
4662
4663        Double theDelay;
4664
4665        if ( firstDelayElement.getElementsByTagName ( "Ref" ).getLength ( )
4666          > 0 )
4667        {
4668          final String  refKey
4669            = getFirstElementFirstChildValue ( firstDelayElement, "Ref" );
4670
4671          theDelay = doubleDataMap.get ( refKey );
4672
4673          if ( theDelay == null )
4674          {
4675            throw new RuntimeException (
4676              refKey + " as a reference is not defined in Data Section" );
4677          }
4678        }
4679        else
4680        {
4681          theDelay = Double.parseDouble (
4682            getFirstChildValue ( firstDelayElement ) );
4683        }
4684
4685        minDelay = theDelay.doubleValue ( );
4686
4687// TODO:  Merge the above code with the following; loop from zero, not one      
4688
4689        for ( int  i = 1; i < delayNodeListLength; i++ )
4690        {
4691          final Element
4692            delayElement = ( Element ) delayNodeList.item ( i );
4693
4694          if ( delayElement.getElementsByTagName ( "Ref" ).getLength ( )
4695            > 0 )
4696          {
4697            final String  refKey
4698              = getFirstElementFirstChildValue ( delayElement, "Ref" );
4699
4700            theDelay = doubleDataMap.get ( refKey );
4701
4702            if ( theDelay == null )
4703            {
4704              throw new RuntimeException (
4705                refKey + " as a reference is not defined in Data Section" );
4706            }
4707          }
4708          else
4709          {
4710            theDelay = Double.parseDouble (
4711              getFirstChildValue ( delayElement ) );
4712          }
4713
4714          final double  delayValue = theDelay.doubleValue ( ); 
4715
4716          if ( delayValue < minDelay )
4717          {
4718            minDelay = delayValue;
4719          }
4720        }
4721      }
4722      
4723      LOGGER.trace ( "minDelay = " + minDelay );
4724      
4725      experiment.recorder.intraTimeBinSize = minDelay / 2.0;
4726    }
4727
4728    /***********************************************************************
4729    * Parse the experiment for main host
4730    ***********************************************************************/
4731    public void  parseExperiment ( )
4732    ////////////////////////////////////////////////////////////////////////
4733    {
4734      LOGGER.trace ( "parseExperiment() entered" );
4735      
4736      final Element
4737        experimentElement = getFirstElement ( rootElement, "Experiment" );
4738      
4739      final NodeList  subExperimentNodeList
4740        = experimentElement.getElementsByTagName ( "SubExperiment" );
4741      
4742      final int
4743        subExperimentNodeListLength = subExperimentNodeList.getLength ( );
4744      
4745      // Element gloable = (Element) nList.item(0);
4746      
4747      final SubExp [ ]
4748        subExps = new SubExp [ subExperimentNodeListLength ];
4749      
4750      // add all the layers
4751      
4752      for ( int  subExperimentIndex = 0;
4753        subExperimentIndex < subExperimentNodeListLength;
4754        subExperimentIndex++ )
4755      {
4756        final Element  subExperimentElement
4757          = ( Element ) subExperimentNodeList.item ( subExperimentIndex );
4758
4759        final NodeList  inputNodeList
4760          = subExperimentElement.getElementsByTagName ( "Input" );
4761        
4762        final int  inputNodeListLength = inputNodeList.getLength ( );
4763        
4764        //  System.out.println("num of inputs:"+inputs.getLength());
4765        
4766        final Stimulus [ ]  stimuli = new Stimulus [ inputNodeListLength ];
4767
4768        for ( int inputIndex = 0; inputIndex < inputNodeListLength;
4769          inputIndex++ )
4770        {
4771          final Element
4772            inputElement = ( Element ) inputNodeList.item ( inputIndex );
4773          
4774          final NodeList
4775            matrixNodeList = inputElement.getElementsByTagName ( "Matrix" );
4776          
4777          double [ ] [ ]  conMatrix = null;
4778          
4779          // filter for the retina
4780          
4781          if ( matrixNodeList.getLength ( ) != 0 )
4782          {
4783            final Element
4784              matrixElement = ( Element ) matrixNodeList.item ( 0 );
4785            
4786            conMatrix = getRefMatrix ( matrixElement );
4787          }
4788          else
4789          {
4790            conMatrix = new double [ 1 ] [ 1 ];
4791            
4792            conMatrix [ 0 ] [ 0 ] = 1.0;
4793          }
4794
4795          final Element  typeElement = getFirstElement (
4796            inputElement,
4797            "Type" );
4798          
4799          final int  type = parseSynapseType ( typeElement );
4800                   
4801          final Stimulus  stimulus = new Stimulus (
4802            modelFactory,
4803            this,
4804            Double.parseDouble (
4805              getFirstElementFirstChildValue (
4806                inputElement,
4807                "Strength" ) ),
4808            type,
4809            Double.parseDouble (
4810              inputElement.getAttribute ( "on" ) ),
4811            Double.parseDouble (
4812              inputElement.getAttribute ( "off" ) ),
4813            Double.parseDouble (
4814              getFirstElementFirstChildValue (
4815                inputElement,
4816                "Frequency"  ) ),
4817            Double.parseDouble (
4818              getFirstElementFirstChildValue (inputElement,"Decay")),
4819            idum,
4820            Integer.parseInt (
4821              getFirstElementFirstChildValue (
4822                inputElement,
4823                "Channel" ) ) );
4824
4825          stimuli [ inputIndex ] = stimulus;
4826          
4827          final NodeList  stimulusNodeList
4828            = inputElement.getElementsByTagName ( "Stimulus" );
4829          
4830          final int
4831            stimulusNodeListLength = stimulusNodeList.getLength ( );
4832          
4833          for ( int  stimulusIndex = 0;
4834            stimulusIndex < stimulusNodeListLength;
4835            stimulusIndex++ )
4836          {
4837            final Element  stimulusElement
4838              = ( Element ) stimulusNodeList.item ( stimulusIndex );
4839            
4840            final NodeList  lineNodeList
4841              = stimulusElement.getElementsByTagName ( "Line" );
4842            
4843            final int  lineNodeListLength = lineNodeList.getLength ( );
4844            
4845            for ( int  lineIndex = 0; lineIndex < lineNodeListLength;
4846              lineIndex++)
4847            {
4848              final Element  lineElement
4849                = ( Element ) lineNodeList.item ( lineIndex );
4850              
4851              final String [ ]  sep
4852                = getFirstChildValue ( lineElement ).split ( "[a-z,\t ]" );
4853              
4854              if ( sep.length != 4 )
4855              {
4856                throw new RuntimeException ( "need 4 arguments" );
4857              }
4858              
4859              stimulus.plotLine (
4860                Integer.parseInt ( sep [ 0 ] ),
4861                Integer.parseInt ( sep [ 1 ] ),
4862                Integer.parseInt ( sep [ 2 ] ),
4863                Integer.parseInt ( sep [ 3 ] ),
4864                getFirstElementFirstChildValue (
4865                  inputElement,
4866                  "Prefix" ),
4867                getFirstElementFirstChildValue (
4868                  inputElement,
4869                  "Suffix" ) );
4870            }
4871            
4872            final NodeList  imageNodeList
4873              = stimulusElement.getElementsByTagName ( "Image" );
4874            
4875            final int  imageNodeListLength = imageNodeList.getLength ( );
4876            
4877            for ( int  imageIndex = 0; imageIndex < imageNodeListLength;
4878              imageIndex++ )
4879            {
4880              final Element  imageElement
4881                = ( Element ) imageNodeList.item ( imageIndex );
4882              
4883              final String
4884                reverseValue = imageElement.getAttribute ( "reverse" ),
4885                prefixValue = getFirstElementFirstChildValue (
4886                  inputElement,
4887                  "Prefix" ),
4888                suffixValue = getFirstElementFirstChildValue (
4889                  inputElement,
4890                  "Suffix" ),
4891                filenameValue = getFirstChildValue ( inputElement );
4892              
4893              if ( reverseValue.equals ( "true" )
4894                || reverseValue.equals ( "TRUE" ) )
4895              {
4896                stimulus.plotRImg (
4897                  prefixValue,
4898                  suffixValue,
4899                  filenameValue,
4900                  conMatrix );
4901              }
4902              else
4903              {
4904                stimulus.plotImg (
4905                  prefixValue,
4906                  suffixValue,
4907                  filenameValue,
4908                  conMatrix );
4909              }
4910            }
4911
4912            final NodeList  plotMatrixNodeList
4913              = stimulusElement.getElementsByTagName ( "PlotMatrix" );
4914            
4915            final int
4916              plotMatrixNodeListLength = plotMatrixNodeList.getLength ( );
4917            
4918            for ( int  plotMatrixIndex = 0;
4919              plotMatrixIndex < plotMatrixNodeListLength;
4920              plotMatrixIndex++ )
4921            {
4922              final Element  plotMatrixElement = ( Element )
4923                plotMatrixNodeList.item ( plotMatrixIndex );
4924              
4925              final int  cenX = Integer.parseInt (
4926                plotMatrixElement.getAttribute ( "centerX" ) );
4927              
4928              final int  cenY = Integer.parseInt (
4929                plotMatrixElement.getAttribute ( "centerY" ) );
4930
4931              final String  refKey = getFirstElementFirstChildValue (
4932                plotMatrixElement,
4933                "Ref" );
4934              
4935              final double [ ] [ ]
4936                plotMatrix = matrixDataMap.get ( refKey );
4937              
4938              if ( plotMatrix == null )
4939              {
4940                throw new RuntimeException ( refKey
4941                  + " as a reference is not defined in Data Section" );
4942              }
4943
4944              stimulus.plotMatrix (
4945                getFirstElementFirstChildValue (
4946                  inputElement,
4947                  "Prefix" ),
4948                getFirstElementFirstChildValue (
4949                  inputElement,
4950                  "Suffix" ),
4951                cenX,
4952                cenY,
4953                plotMatrix );
4954            }
4955
4956            final NodeList  backgroundNodeList
4957              = stimulusElement.getElementsByTagName ( "Background" );
4958            
4959            final int  backgroundNodeListLength
4960              = backgroundNodeList.getLength ( );
4961            
4962            for ( int  backgroundIndex = 0;
4963              backgroundIndex < backgroundNodeListLength;
4964              backgroundIndex++ )
4965            {
4966              stimulus.background (
4967                getFirstElementFirstChildValue (
4968                  inputElement,
4969                  "Prefix" ),
4970                getFirstElementFirstChildValue (
4971                  inputElement,
4972                  "Suffix" ) );
4973            }
4974
4975            final NodeList  squareNodeList
4976              = stimulusElement.getElementsByTagName ( "Square" );
4977            
4978            final int  squareNodeListLength = squareNodeList.getLength ( );
4979            
4980            for ( int  squareIndex = 0; squareIndex < squareNodeListLength;
4981              squareIndex++ )
4982            {
4983              final Element  squareElement
4984                = ( Element ) squareNodeList.item ( squareIndex );
4985              
4986              final String [ ]  sep = getFirstChildValue (
4987                squareElement ).split ( "[a-z,\t ]" );
4988              
4989              if ( sep.length != 4 )
4990              {
4991                throw new RuntimeException ( "need 4 arguments" );
4992              }
4993              
4994              stimulus.plotSquare (
4995                Integer.parseInt ( sep [ 0 ] ),
4996                Integer.parseInt ( sep [ 1 ] ),
4997                Integer.parseInt ( sep [ 2 ] ),
4998                Integer.parseInt ( sep [ 3 ] ),
4999                getFirstElementFirstChildValue (
5000                  inputElement,
5001                  "Prefix" ),
5002                getFirstElementFirstChildValue (
5003                  inputElement,
5004                  "Suffix" ) );
5005            }
5006          }
5007          //System.out.println(stis[iter].init(iter));
5008        } // END: for inputs
5009        
5010        for ( int  inputIndex = 0; inputIndex < inputNodeListLength;
5011          inputIndex++ )
5012        {
5013          // release the memory
5014          
5015          stimuli [ inputIndex ].simulatorParser = null;
5016        }
5017        
5018        final Collection<DiscreteEvent>
5019          modulatorDiscreteEventCollection
5020            = parseModulator ( subExperimentElement );
5021        
5022        subExps [ subExperimentIndex ] = new SubExp (
5023          Integer.parseInt (
5024            subExperimentElement.getAttribute ( "repetition" ) ),
5025          Double.parseDouble (
5026            subExperimentElement.getAttribute ( "length" ) ),
5027          stimuli,
5028          modulatorDiscreteEventCollection );
5029        
5030        subExps [ subExperimentIndex ].name
5031          = subExperimentElement.getAttribute ( "name" );
5032      } // END: for subexp
5033
5034      // recorder part
5035
5036      final Element  recorderElement = getFirstElement (
5037        rootElement,
5038        "Recorder" );
5039
5040      final String  plotStr = recorderElement.getAttribute ( "plot" );
5041      
5042      final boolean  plot
5043        =  plotStr.equals ( "true" )
5044        || plotStr.equals ( "TRUE" );
5045
5046      final Recorder  recorder = new Recorder ( this, plot );
5047      
5048      final NodeList  outputFileNodeList
5049        = recorderElement.getElementsByTagName ( "OutputFile" );
5050      
5051      if ( outputFileNodeList.getLength ( ) > 0 )
5052      {
5053        final Element
5054          outputFileElement = ( Element ) outputFileNodeList.item ( 0 );
5055        
5056        recorder.outputFile = getFirstChildValue ( outputFileElement );
5057      }
5058      
5059      // single unit electrode
5060      
5061      final NodeList  singleUnitNodeList
5062        = recorderElement.getElementsByTagName ( "SingleUnit" );
5063      
5064      final int
5065        singleUnitNodeListLength = singleUnitNodeList.getLength ( );
5066      
5067      for ( int  singleUnitIndex = 0;
5068        singleUnitIndex < singleUnitNodeListLength;
5069        singleUnitIndex++ )
5070      {
5071        final Element  singleUnitElement
5072          = ( Element ) singleUnitNodeList.item ( singleUnitIndex );
5073        
5074        // line
5075        // ArrayList<Integer> sUnit = new ArrayList<Integer>();
5076        
5077        final NodeList  lineNodeList
5078          = singleUnitElement.getElementsByTagName ( "Line" );
5079        
5080        final int  lineNodeListLength = lineNodeList.getLength ( );
5081        
5082        for ( int  lineIndex = 0; lineIndex < lineNodeListLength;
5083          lineIndex++ )
5084        {
5085          final Element
5086            lineElement = ( Element ) lineNodeList.item ( lineIndex );
5087          
5088          final String [ ]
5089            sep = getFirstChildValue ( lineElement ).split ( "[a-z,\t ]" );
5090          
5091          recorder.singleUnit.addAll (
5092            recorder.addLine (
5093              Integer.parseInt ( sep [ 0 ] ),
5094              Integer.parseInt ( sep [ 1 ] ),
5095              Integer.parseInt ( sep [ 2 ] ),
5096              Integer.parseInt ( sep [ 3 ] ),
5097              lineElement.getAttribute ( "pre" ),
5098              lineElement.getAttribute ( "suf" ),
5099              recorder.suNames ) );
5100        }
5101
5102        // square
5103        
5104        final NodeList  squareNodeList
5105          = singleUnitElement.getElementsByTagName ( "Square" );
5106        
5107        final int  squareNodeListLength = squareNodeList.getLength ( );
5108        
5109        for ( int squareIndex = 0; squareIndex < squareNodeListLength;
5110          squareIndex++ )
5111        {
5112          final Element
5113            squareElement = ( Element ) squareNodeList.item ( squareIndex );
5114          
5115          final String [ ]  sep
5116            = getFirstChildValue ( squareElement ).split ( "[a-z,\t ]" );
5117          
5118          recorder.singleUnit.addAll (
5119            recorder.addSquare (
5120              Integer.parseInt ( sep [ 0 ] ),
5121              Integer.parseInt ( sep [ 1 ] ),
5122              Integer.parseInt ( sep [ 2 ] ),
5123              Integer.parseInt ( sep [ 3 ] ),
5124              squareElement.getAttribute ( "pre" ),
5125              squareElement.getAttribute ( "suf" ),
5126              recorder.suNames ) );
5127        }
5128        //    System.out.println(rec.suNames);
5129        //    System.out.println(rec.singleUnit);
5130      }
5131
5132      // multi unit electrode
5133      
5134      final NodeList  multiUnitNodeList
5135        = recorderElement.getElementsByTagName ( "MultiUnit" );
5136      
5137      final int  multiUnitNodeListLength = multiUnitNodeList.getLength ( );
5138      
5139      for ( int  multiUnitIndex = 0;
5140        multiUnitIndex < multiUnitNodeListLength;
5141        multiUnitIndex++ )
5142      {
5143        final Element  multiUnitElement
5144          = ( Element ) multiUnitNodeList.item ( multiUnitIndex );
5145        
5146        recorder.timeBinSize = Double.parseDouble (
5147          multiUnitElement.getAttribute ( "binSize" ) );
5148        
5149        recorder.multiNames.add (
5150          getFirstElementFirstChildValue (
5151            multiUnitElement,
5152            "Name" ) );
5153        
5154        // line
5155        
5156        final ArrayList<Integer>  mUnitList = new ArrayList<Integer> ( );
5157        
5158        final ArrayList<String>  mNameList = new ArrayList<String> ( );
5159
5160        final NodeList
5161          lineNodeList = multiUnitElement.getElementsByTagName ( "Line" );
5162        
5163        final int  lineNodeListLength = lineNodeList.getLength ( );
5164        
5165        for ( int  lineIndex = 0; lineIndex < lineNodeListLength;
5166          lineIndex++ )
5167        {
5168          final Element
5169            lineElement = ( Element ) lineNodeList.item ( lineIndex );
5170          
5171          final String [ ]
5172            sep = getFirstChildValue ( lineElement ).split ( "[a-z,\t ]" );
5173          
5174          mUnitList.addAll (
5175            recorder.addLine (
5176              Integer.parseInt ( sep [ 0 ] ),
5177              Integer.parseInt ( sep [ 1 ] ),
5178              Integer.parseInt ( sep [ 2 ] ),
5179              Integer.parseInt ( sep [ 3 ] ),
5180              lineElement.getAttribute ( "pre" ),
5181              lineElement.getAttribute ( "suf" ),
5182              mNameList ) );
5183        }
5184
5185        // square
5186        
5187        final NodeList  squareNodeList
5188          = multiUnitElement.getElementsByTagName ( "Square" );
5189        
5190        final int  squareNodeListLength = squareNodeList.getLength ( );
5191        
5192        for ( int  squareIndex = 0; squareIndex < squareNodeListLength;
5193          squareIndex++ )
5194        {
5195          // LOGGER.trace ( "parsing MultiUnit Square" );
5196          
5197          final Element
5198            squareElement = ( Element ) squareNodeList.item ( squareIndex );
5199          
5200          final String [ ]
5201            sep = getFirstChildValue ( squareElement ).split("[a-z,\t ]");
5202          
5203          mUnitList.addAll (
5204            recorder.addSquare (
5205              Integer.parseInt ( sep [ 0 ] ),
5206              Integer.parseInt ( sep [ 1 ] ),
5207              Integer.parseInt ( sep [ 2 ] ),
5208              Integer.parseInt ( sep [ 3 ] ),
5209              squareElement.getAttribute ( "pre" ),
5210              squareElement.getAttribute ( "suf" ),
5211              mNameList ) );
5212        }
5213
5214        recorder.multiUnit.add ( mUnitList );
5215        
5216        recorder.neuronNames.add ( mNameList );
5217      }
5218
5219      // field electrode
5220      // multi unit electrode
5221      
5222      final NodeList
5223        fieldNodeList = recorderElement.getElementsByTagName ( "Field" );
5224      
5225      final int  fieldNodeListLength = fieldNodeList.getLength ( );
5226      
5227      for ( int  fieldIndex = 0; fieldIndex < fieldNodeListLength;
5228        fieldIndex++ )
5229      {
5230        final Element
5231          fieldElement = ( Element ) fieldNodeList.item ( fieldIndex );
5232        
5233        recorder.fieldNames.add (
5234          getFirstElementFirstChildValue ( fieldElement, "Name" ) );
5235        
5236        final Layer  tmpLayer = layerStructure.getLayer (
5237          getFirstElementFirstChildValue ( fieldElement, "Prefix" ),
5238          getFirstElementFirstChildValue ( fieldElement, "Suffix" ) );
5239        
5240        recorder.fieldEle.add ( tmpLayer );
5241        
5242        recorder.fieldTimeBinSize
5243          = Double.parseDouble ( fieldElement.getAttribute ( "binSize" ) );
5244        
5245        // for slave hosts, they need to set neurons recordable
5246        
5247        recorder.setLayerNeurons ( tmpLayer );
5248      }
5249
5250      // vector electrode
5251      
5252      // vector plots
5253      
5254      final NodeList  vectorMapNodeList
5255        = recorderElement.getElementsByTagName ( "VectorMap" );
5256      
5257      final int  vectorMapNodeListLength = vectorMapNodeList.getLength ( );
5258      
5259      for ( int  vectorMapIndex = 0;
5260        vectorMapIndex < vectorMapNodeListLength;
5261        vectorMapIndex++ )
5262      {
5263        final Element  vectorMapElement
5264          = ( Element ) vectorMapNodeList.item ( vectorMapIndex );        
5265          
5266        recorder.vectorNames.add (
5267          getFirstElementFirstChildValue ( vectorMapElement, "Name" ) );
5268        
5269        final VComponents  coms = recorder.addComs ( );
5270        
5271        final NodeList  layerOrientationNodeList
5272          = vectorMapElement.getElementsByTagName ( "LayerOrientation" );
5273        
5274        final int  layerOrientationNodeListLength
5275          = layerOrientationNodeList.getLength ( );
5276        
5277        for ( int  layerOrientationIndex = 0;
5278          layerOrientationIndex < layerOrientationNodeListLength;
5279          layerOrientationIndex++ )
5280        {
5281          final Element  layerOrientationElement = ( Element )
5282            layerOrientationNodeList.item ( layerOrientationIndex );
5283          
5284          final Layer  tmpLayer = layerStructure.getLayer (
5285            layerOrientationElement.getAttribute ( "pre" ),
5286            layerOrientationElement.getAttribute ( "suf" ) );
5287          
5288          coms.addCom (
5289            tmpLayer,
5290            Integer.parseInt (
5291              getFirstChildValue ( layerOrientationElement ) ) );
5292          
5293          recorder.setLayerNeurons ( tmpLayer );
5294        }
5295        
5296        recorder.vectorTimeBinSize = Double.parseDouble (
5297          vectorMapElement.getAttribute ( "binSize" ) );
5298      }
5299      
5300      // intracellular unit electrode
5301      
5302      final NodeList  intracellularNodeList
5303        = recorderElement.getElementsByTagName ( "Intracellular" );
5304      
5305      final int  intracellularNodeListLength
5306        = intracellularNodeList.getLength ( );
5307      
5308      for ( int  intracellularIndex = 0;
5309        intracellularIndex < intracellularNodeListLength;
5310        intracellularIndex++ )
5311      {
5312        final Element  intracellularElement = ( Element )
5313          intracellularNodeList.item ( intracellularIndex );
5314        
5315        recorder.intraNames.add (
5316          getFirstElementFirstChildValue ( intracellularElement, "Name" ) );
5317        
5318        // line
5319        
5320        final ArrayList<Integer>  mUnitList = new ArrayList<Integer> ( );
5321        
5322        final ArrayList<String>  mNameList = new ArrayList<String> ( );
5323        
5324        final ArrayList<Integer>  chaList = new ArrayList<Integer> ( );
5325
5326        final NodeList  lineNodeList
5327          = intracellularElement.getElementsByTagName ( "Line" );
5328        
5329        final int  lineNodeListLength = lineNodeList.getLength ( ); 
5330        
5331        for ( int  lineIndex = 0; lineIndex < lineNodeListLength;
5332          lineIndex++ )
5333        {
5334          final Element
5335            lineElement = ( Element ) lineNodeList.item ( lineIndex );
5336          
5337          final String [ ]  sep
5338            = getFirstChildValue ( lineElement ).split ( "[a-z,\t ]" );
5339          
5340          mUnitList.addAll (
5341            recorder.addLine (
5342              Integer.parseInt ( sep [ 0 ] ),
5343              Integer.parseInt ( sep [ 1 ] ),
5344              Integer.parseInt ( sep [ 2 ] ),
5345              Integer.parseInt ( sep [ 3 ] ),
5346              lineElement.getAttribute ( "pre" ),
5347              lineElement.getAttribute ( "suf" ),
5348              mNameList ) );
5349        }
5350
5351        // square
5352        
5353        final NodeList  squareNodeList
5354          = intracellularElement.getElementsByTagName ( "Square" );
5355        
5356        final int  squareNodeListLength = squareNodeList.getLength ( );
5357        
5358        for ( int  squareIndex = 0; squareIndex < squareNodeListLength;
5359          squareIndex++ )
5360        {
5361          final Element  squareElement
5362            = ( Element ) squareNodeList.item ( squareIndex );
5363          
5364          final String [ ]  sep
5365            = getFirstChildValue ( squareElement ).split ( "[a-z,\t ]" );
5366          
5367          mUnitList.addAll (
5368            recorder.addSquare (
5369              Integer.parseInt ( sep [ 0 ] ),
5370              Integer.parseInt ( sep [ 1 ] ),
5371              Integer.parseInt ( sep [ 2 ] ),
5372              Integer.parseInt ( sep [ 3 ] ),
5373              squareElement.getAttribute ( "pre" ),
5374              squareElement.getAttribute ( "suf" ),
5375              mNameList ) );
5376        }
5377
5378        // channel
5379        
5380        final NodeList  channelNodeList
5381          = intracellularElement.getElementsByTagName ( "Channel" );
5382        
5383        final int  channelNodeListLength = channelNodeList.getLength ( );
5384        
5385        for ( int  channelIndex = 0; channelIndex < channelNodeListLength;
5386          channelIndex++ )
5387        {
5388          final Element  channelElement
5389            = ( Element ) channelNodeList.item ( channelIndex );
5390          
5391          chaList.add (
5392            Integer.parseInt ( getFirstChildValue ( channelElement ) ) );
5393        }
5394
5395        recorder.intraEle.add ( mUnitList );
5396        
5397        recorder.currChannel.add ( chaList );
5398        
5399        // rec.neuronNames.add(mName);
5400      }
5401      
5402      experiment = new Experiment ( subExps, recorder );
5403      
5404      // clear info
5405      
5406      experiment.recorder.simulatorParser = null;
5407      
5408      LOGGER.trace ( "parseExperiment() exiting" );      
5409    }
5410
5411    /***********************************************************************
5412    * Map the cells and build up the index, for main host.
5413    * 
5414    * Called by class MainSimulator method run().
5415    ***********************************************************************/
5416    public void  parseMapCells ( )
5417    ////////////////////////////////////////////////////////////////////////
5418    {
5419      final Element  overallConfigurationElement = getFirstElement (
5420        rootElement,
5421        "OverallConfiguration" );
5422
5423      // layer size
5424      
5425      xEdgeLength = Integer.parseInt (
5426        getFirstElementFirstChildValue (
5427          overallConfigurationElement,
5428          "xEdgeLength" ) );
5429      
5430      yEdgeLength = Integer.parseInt (
5431        getFirstElementFirstChildValue (
5432          overallConfigurationElement,
5433          "yEdgeLength" ) );
5434      
5435      LOGGER.trace ( "xEdgeLength = {}", xEdgeLength );
5436      
5437      LOGGER.trace ( "yEdgeLength = {}", yEdgeLength );
5438
5439      if ( overallConfigurationElement.getElementsByTagName (
5440        "DataFileName" ).getLength ( ) > 0 )
5441      {
5442        outFile = getFirstElementFirstChildValue (
5443          overallConfigurationElement,
5444          "DataFileName" );
5445      }
5446      
5447      LOGGER.trace ( "outFile = {}", outFile );
5448
5449      parallelHost = Integer.parseInt (
5450        getFirstElementFirstChildValue (
5451          overallConfigurationElement,
5452          "TrialHost" ) );
5453      
5454      LOGGER.trace ( "parallelHost = {}", parallelHost );
5455
5456      // Host info
5457      
5458      final Element  netHostElement = getFirstElement (
5459        overallConfigurationElement,
5460        "NetHost" );
5461      
5462      numOfHosts = Integer.parseInt (
5463        getFirstElementFirstChildValue (
5464          netHostElement,
5465          "Number" ) );
5466      
5467      LOGGER.trace ( "numOfHosts = {}", numOfHosts );
5468      
5469      final Element  mapMethodElement = getFirstElement (
5470        netHostElement,
5471        "MapMethod" );
5472      
5473      aSec = Integer.parseInt ( mapMethodElement.getAttribute ( "A" ) );
5474      
5475      LOGGER.trace ( "aSec = {}", aSec );
5476      
5477      bSec = Integer.parseInt ( mapMethodElement.getAttribute ( "B" ) );
5478      
5479      LOGGER.trace ( "bSec = {}", bSec );
5480      
5481      mapType = LayerStructure.ABMAP;
5482
5483      layerStructure = new LayerStructure (
5484        modelFactory,
5485        numOfHosts,
5486        xEdgeLength,
5487        yEdgeLength );
5488
5489      if ( aSec * bSec != numOfHosts )
5490      {
5491        throw new RuntimeException (
5492          aSec + "x" + bSec + "!=" + numOfHosts );
5493      }
5494
5495      backgroundFrequency = Double.parseDouble (
5496        getFirstElementFirstChildValue (
5497          overallConfigurationElement,
5498          "BackgroundFrequency" ) );
5499      
5500      LOGGER.trace ( "backgroundFrequency = {}", backgroundFrequency );
5501      
5502      backgroundStrength = Double.parseDouble (
5503        getFirstElementFirstChildValue (
5504          overallConfigurationElement,
5505          "BackgroundStrength" ) );
5506      
5507      LOGGER.trace ( "backgroundStrength = {}", backgroundStrength );
5508
5509      final Element  backgroundTypeElement = getFirstElement (
5510        overallConfigurationElement,
5511        "BackgroundType" );
5512      
5513// TODO:  Why is bChannel not used here?  For exception check only?      
5514      
5515      final int  bChannel = parseSynapseType ( backgroundTypeElement );
5516      
5517      LOGGER.trace ( "bChannel = {}", bChannel );
5518      
5519      /*
5520      bFreq = Double.parseDouble(
5521        (gloable.getElementsByTagName("BackgroundFiring").item(0))
5522        .getFirstChild().getNodeValue());
5523        
5524      bSynStr = Double.parseDouble(
5525        (gloable.getElementsByTagName("BackgroundSynapse").item(0))
5526        .getFirstChild().getNodeValue());
5527        
5528      bChannel = Integer.parseInt(
5529        ((Element)(gloable.getElementsByTagName("BackgroundSynapse")
5530        .item(0))).getAttributeNode("channel").getValue());
5531      */
5532
5533      // read layers
5534      
5535      final Element
5536        layersElement = getFirstElement ( rootElement, "Layers" );
5537      
5538      final NodeList
5539        layerNodeList = layersElement.getElementsByTagName ( "Layer" );
5540      
5541      // add all the layers
5542      
5543      final int  layerNodeListLength = layerNodeList.getLength ( );
5544      
5545      for ( int  i = 0; i < layerNodeListLength; i++ )
5546      {
5547        final Element  layerElement = ( Element ) layerNodeList.item ( i );
5548        
5549        final String  prefix = getFirstElementFirstChildValue (
5550          layerElement,
5551          "Prefix" );
5552        
5553        LOGGER.trace ( "prefix = {}", prefix );
5554        
5555        final String  suffix = getFirstElementFirstChildValue (
5556          layerElement,
5557          "Suffix" );
5558        
5559        LOGGER.trace ( "suffix = {}", suffix );
5560        
5561        final int  multiX = Integer.parseInt (
5562          getFirstElementFirstChildValue (
5563            layerElement,
5564            "MultiX" ) );
5565        
5566        LOGGER.trace ( "multiX = {}", multiX );
5567        
5568        final int  multiY = Integer.parseInt (
5569          getFirstElementFirstChildValue (
5570            layerElement,
5571            "MultiY" ) );
5572        
5573        LOGGER.trace ( "multiY = {}", multiY );
5574        
5575        final String  neuronType = getFirstElementFirstChildValue (
5576          layerElement,
5577          "NeuronType" );
5578        
5579        LOGGER.trace ( "neuronType = {}", neuronType );
5580        
5581        layerStructure.addLayer (
5582          prefix,
5583          suffix,
5584          multiX,
5585          multiY,
5586          neuronType );
5587      }
5588      
5589      LOGGER.trace (
5590        "totalNumNeurons = {}",
5591        layerStructure.totalNumNeurons ( ) );
5592      
5593      switch ( mapType )
5594      {
5595        case LayerStructure.ABMAP:
5596          
5597          layerStructure.abmapcells_Main ( aSec, bSec );
5598          
5599          break;
5600          
5601        case LayerStructure.LINEMAP:
5602          
5603// TODO:  Is this case possible?          
5604          
5605          layerStructure.mapcells ( );
5606          
5607          break;
5608          
5609        default:
5610          
5611          break;
5612      }
5613    }
5614    
5615    public Collection<DiscreteEvent>  parseModulator (
5616      final Element  subExperimentElement )
5617    ////////////////////////////////////////////////////////////////////////
5618    {
5619      // LOGGER.trace ( "parseModulator() entered" );
5620
5621      // LOGGER.trace (
5622      //   "total synapse count {}",
5623      //   modulatedSynapses.length );
5624      
5625      final NodeList  nodeList
5626        = subExperimentElement.getElementsByTagName ( "Modulator" );
5627      
5628      final int  length = nodeList.getLength ( );
5629      
5630      if ( length == 0 )
5631      {
5632        return null;
5633      }
5634      
5635      final Collection<DiscreteEvent>
5636        discreteEventCollection = new ArrayList<DiscreteEvent> ( );
5637  
5638      for ( int  i = 0; i < length; i++ )
5639      {
5640        final Element  modulatorElement = ( Element ) nodeList.item ( i );
5641        
5642        final String
5643          attributeTime
5644            = modulatorElement.getAttribute ( "time" ),
5645          attributeName
5646            = modulatorElement.getAttribute ( "name" ),
5647          attributePeakFactor
5648            = modulatorElement.getAttribute ( "peakFactor" );
5649        
5650        LOGGER.debug ( "attribute time = {}", attributeTime );        
5651        
5652        LOGGER.debug ( "attribute name = {}", attributeName );        
5653        
5654        LOGGER.debug ( "attribute peakFactor = {}", attributePeakFactor );
5655        
5656        final double  time = parseDouble (
5657          attributeTime,
5658          0,
5659          "error parsing time" );
5660        
5661        final String  name = attributeName.trim ( );
5662        
5663        final double  peakFactor = parseDouble (
5664          attributePeakFactor,
5665          1,
5666          "error parsing peakFactor" );
5667        
5668// TODO:  parse specific synapses instead of defaulting to global
5669        
5670        discreteEventCollection.add (
5671          modelFactory.createModulationDiscreteEvent (
5672            time,
5673            name,
5674            peakFactor,
5675            modulatedSynapseSeq ) );
5676      }
5677      
5678      // LOGGER.trace ( "parseModulator() exiting" );
5679      
5680      return discreteEventCollection;
5681    }
5682
5683    /***********************************************************************
5684    * Parse the neuron definition, for main host. 
5685    ***********************************************************************/
5686    public void  parseNeuronDef ( )
5687    ////////////////////////////////////////////////////////////////////////
5688    {
5689      final Element  neuronDefinitionElement = getFirstElement (
5690        rootElement,
5691        "NeuronDefinition" );
5692      
5693      final NodeList  neuronNodeList
5694        = neuronDefinitionElement.getElementsByTagName ( "Neuron" );
5695      
5696      final int  neuronNodeListLength = neuronNodeList.getLength ( );
5697      
5698      // add all the layers
5699
5700      for ( int  i = 0; i < neuronNodeListLength; i++ )
5701      {
5702        final Element
5703          neuronElement = ( Element ) neuronNodeList.item ( i );
5704        
5705        final String  name = getFirstElementFirstChildValue (
5706          neuronElement,
5707          "Name" );
5708        
5709        final String  model = getFirstElementFirstChildValue (
5710          neuronElement,
5711          "Model" );
5712        
5713        if ( model.equals ( "SIFNeuron" ) )
5714        {
5715          modelParaMap.put (
5716            name,
5717            parseParametersSifNeuron ( neuronElement ) );
5718        }
5719        else if ( model.equals ( "VSICLIFNeuron" ) )
5720        {
5721          modelParaMap.put (
5722            name,
5723            parseParametersVsiclifNeuron ( neuronElement ) );
5724        }
5725        else if ( model.equals ( "VSICLIFNeuronV2" ) )
5726        {
5727          modelParaMap.put (
5728            name,
5729            parseParametersVsiclifNeuronV2 ( neuronElement ) );
5730        }
5731        else if ( model.equals( "MiNiNeuron" ) )
5732        {
5733          modelParaMap.put(
5734              name,
5735              parseParametersMiNiNeuron ( neuronElement ) );
5736        }
5737        else if ( model.equals ( "BKPoissonNeuron" ) )
5738        {
5739          modelParaMap.put (
5740            name,
5741            parseParametersBkPoissonNeuron ( neuronElement ) );
5742        }
5743        else if ( model.equals ( "UserSenNeuron" ) )
5744        {
5745          modelParaMap.put (
5746            name,
5747            parseParametersUserSenNeuron ( neuronElement ) );
5748        }
5749        else
5750        {
5751          throw new RuntimeException ( model + " not defined neuron type" );
5752        }
5753      }
5754
5755      // Read predefined data
5756      
5757      final Element  constantDefinitionElement = getFirstElement (
5758        rootElement,
5759        "ConstantDefinition" ); 
5760      
5761      final NodeList  doubleNodeList
5762        = constantDefinitionElement.getElementsByTagName ( "Double" );
5763      
5764      // add all the layers
5765      
5766      final int  doubleNodeListLength = doubleNodeList.getLength ( );
5767      
5768      for ( int  i = 0; i < doubleNodeListLength; i++ )
5769      {
5770// TODO:  Why is ab added to each loop?        
5771        
5772        doubleDataMap.put ( "ab", new Double ( 1.0 ) );
5773        
5774        final Element
5775          doubleElement = ( Element ) doubleNodeList.item ( i );
5776      
5777        doubleDataMap.put (
5778          doubleElement.getAttribute ( "id" ),
5779          Double.parseDouble ( getFirstChildValue ( doubleElement ) ) );
5780      }
5781      
5782      final NodeList  matrixNodeList
5783        = constantDefinitionElement.getElementsByTagName ( "Matrix" );
5784      
5785      // add all the layers
5786      
5787      for ( int  i = 0; i < matrixNodeList.getLength ( ); i++)
5788      {
5789        final Element
5790          matrixElement = ( Element ) matrixNodeList.item ( i );
5791        
5792        matrixDataMap.put (
5793          matrixElement.getAttribute ( "id" ),
5794          parseMatrix ( matrixElement ) );
5795      }
5796    }
5797
5798    /***********************************************************************
5799    * populate the neurons for net host 
5800    ***********************************************************************/
5801    public void  parsePopNeurons ( final int  hostId )
5802    ////////////////////////////////////////////////////////////////////////
5803    {
5804      layerStructure.setSeed(idum);
5805      int secX = hostId/bSec;
5806      int secY = hostId%bSec;
5807      //    System.out.println("SecX"+ hostId/bSec);
5808      //    System.out.println("SecY"+ hostId%bSec);
5809
5810      //    System.out.println(ls.numberOfNeurons);
5811      /*
5812      for(int i = 0 ; i< ls.nodeEndIndices.length; i++)
5813      {
5814        System.out.print(ls.nodeEndIndices[i]+" ");
5815      }
5816      System.out.println();
5817      */
5818
5819      // reserve one place for the sync neuron
5820      
5821      layerStructure.neurons = new Neuron [
5822        layerStructure.neuron_end - layerStructure.base + 1 + 1 ];
5823      
5824      //    ls.branchmaps = new TreeMap[ls.neuron_end-ls.base+1+1];
5825      //    ls.scaffold = new TreeMap[ls.neuron_end-ls.base+1+1];
5826
5827      //      for(int a=0;a<ls.neuron_end-ls.base+1+1;a++) 
5828      //    {
5829      //      ls.branchmaps[a]=new TreeMap<String, TreeSet<Synapse>>(); 
5830      //      ls.scaffold[a]=new TreeMap<String, SizeID>(); 
5831      //    }
5832
5833      NodeList nList = rootElement.getElementsByTagName("Layers");
5834      
5835      Element ele = (Element)nList.item(0);
5836      
5837      NodeList lay = ele.getElementsByTagName("Layer");
5838
5839      int xTotal=0;           
5840      int yTotal=0;
5841      int xstep=0;
5842      int ystep=0;
5843      int xMul,yMul;
5844      int xOri,yOri;
5845      int xresosize,yresosize;
5846      String neu;
5847
5848      for(int it= 0 ; it< lay.getLength(); it++) // add all the layers;
5849      {
5850        xMul = Integer.parseInt(((Element)(lay.item(it)))
5851          .getElementsByTagName("MultiX").item(0).getFirstChild()
5852            .getNodeValue());
5853        
5854        yMul = Integer.parseInt(
5855          ((Element)(lay.item(it))).getElementsByTagName("MultiY").item(0)
5856            .getFirstChild().getNodeValue());
5857        
5858        if(xMul>0)
5859        {
5860          xstep=1;
5861          
5862          if(secX!=0)
5863          {
5864            xOri=(int)((double)xMul*(double)xEdgeLength
5865              /(double)aSec*(double)(secX));
5866          }
5867          else
5868          {
5869            xOri=0;
5870          }
5871          
5872          if(secX!=aSec-1)
5873          {
5874            xresosize=(int)((double)xMul*(double)xEdgeLength
5875              /(double)aSec*(double)(secX+1));
5876          }
5877          else
5878          {
5879            xresosize=xMul*xEdgeLength;
5880          }
5881        }
5882        else
5883        {
5884          xstep=-xMul;
5885          
5886          if(secX!=0)
5887          {
5888            xOri = (int)((double)xEdgeLength/(double)aSec*(double)(secX));
5889            
5890            xOri = xOri + xstep - xOri % xstep;
5891          }
5892          else
5893          {
5894            xOri=0;
5895          }
5896          
5897          if(secX!=aSec-1)
5898          {
5899            xresosize=(int)((double)xEdgeLength
5900              /(double)aSec*(double)(secX+1));
5901            
5902            xresosize = xresosize + xstep - xresosize % xstep;
5903            
5904            if(xresosize>xEdgeLength)
5905              xresosize=xEdgeLength;
5906          }
5907          else
5908          {
5909            xresosize=xEdgeLength;
5910          }
5911        }
5912        
5913        if(yMul>0)
5914        {
5915          ystep=1;
5916          
5917          if(secY!=0)
5918          {
5919            yOri=(int)((double)yMul*(double)yEdgeLength
5920              /(double)bSec*(double)(secY));
5921          }
5922          else
5923          {
5924            yOri=0;
5925          }
5926          if(secY!=bSec-1)
5927          {
5928            yresosize=(int)((double)yMul*(double)yEdgeLength
5929              /(double)bSec*(double)(secY+1));
5930          }
5931          else
5932          {
5933            yresosize=yMul*yEdgeLength;
5934          }
5935        }
5936        else
5937        {
5938          ystep=-(yMul);
5939          
5940          if(secY!=0)
5941          {
5942            yOri=(int)((double)yEdgeLength/(double)bSec*(double)(secY));
5943            
5944            yOri=yOri + ystep - yOri % ystep;
5945          }
5946          else
5947          {
5948            yOri=0;
5949          }
5950          
5951          if(secY!=bSec-1)
5952          {
5953            yresosize=(int)((double)yEdgeLength
5954              /(double)bSec*(double)(secY+1));
5955            
5956            yresosize=yresosize + ystep -  yresosize % ystep;
5957            
5958            if(yresosize>yEdgeLength)yresosize=yEdgeLength;
5959          }
5960          else
5961          {
5962            yresosize=yEdgeLength;
5963          }
5964        }
5965        
5966        String n_pre = ((Element)(lay.item(it)))
5967          .getElementsByTagName("Prefix").item(0)
5968          .getFirstChild().getNodeValue();
5969        
5970        String n_suf = ((Element)(lay.item(it)))
5971          .getElementsByTagName("Suffix").item(0)
5972          .getFirstChild().getNodeValue();
5973        
5974        for(int x=xOri;x<xresosize;x+=xstep)
5975        {
5976          for(int y=yOri;y<yresosize;y+=ystep)
5977          {
5978            // neu=((Element)(lay.item(it))).getElementsByTagName("Prefix")
5979            //   .item(0).getFirstChild().getNodeValue()+","+x+","+y+","
5980            //   +((Element)(lay.item(it))).getElementsByTagName("Suffix")
5981            //   .item(0).getFirstChild().getNodeValue();
5982            
5983            Para neuPara = modelParaMap.get(
5984              ((Element)(lay.item(it))).getElementsByTagName("NeuronType")
5985              .item(0).getFirstChild().getNodeValue());
5986
5987            if(neuPara != null) 
5988            {
5989              if( (neuPara.getModel()).equals("SIFNeuron"))
5990              {
5991                final SIFNeuronPara
5992                  sifNeuronPara = ( SIFNeuronPara ) neuPara;
5993                
5994                final SIFNeuron
5995                  sifNeuron = new SIFNeuron ( sifNeuronPara );
5996                
5997                layerStructure.neurons[layerStructure.cellmap_slow(
5998                  n_pre,n_suf,x,y)-layerStructure.base] = sifNeuron;
5999              }
6000              else if((neuPara.getModel()).equals("BKPoissonNeuron"))
6001              {
6002
6003                layerStructure.neurons[layerStructure.cellmap_slow(
6004                  n_pre,n_suf,x,y)-layerStructure.base]
6005                    = new BKPoissonNeuron(
6006                      idum,
6007                      (BKPoissonNeuronPara)neuPara);
6008              } 
6009              else if((neuPara.getModel()).equals("VSICLIFNeuron"))
6010              {
6011                layerStructure.neurons[layerStructure.cellmap_slow(
6012                  n_pre,n_suf,x,y)-layerStructure.base]
6013                    = new VSICLIFNeuron((VSICLIFNeuronPara)neuPara);
6014              } 
6015              else if((neuPara.getModel()).equals("VSICLIFNeuronV2"))
6016              {
6017                layerStructure.neurons[layerStructure.cellmap_slow(
6018                  n_pre,n_suf,x,y)-layerStructure.base]
6019                    = new VSICLIFNeuronV2((VSICLIFNeuronParaV2)neuPara);
6020              } 
6021              else if ((neuPara.getModel()).equals("MiNiNeuron"))
6022              {
6023                layerStructure.neurons[layerStructure.cellmap_slow(
6024                  n_pre,n_suf,x,y)-layerStructure.base]
6025                    = new MiNiNeuron((MiNiNeuronPara)neuPara);
6026              }
6027              else if((neuPara.getModel()).equals("UserSenNeuron"))
6028              {
6029                layerStructure.neurons[
6030                  layerStructure.cellmap_slow(n_pre,n_suf,x,y)
6031                    -layerStructure.base]
6032                      = new UserSenNeuron(
6033                        (UserSenNeuronPara)neuPara, n_pre, n_suf,x,y);
6034              }
6035            }
6036            else
6037            {
6038              throw new RuntimeException(
6039                "Neuron type "
6040                  +((Element)(lay.item(it))).getElementsByTagName(
6041                    "NeuronType").item(0).getFirstChild().getNodeValue()
6042                  +" not defined");
6043            }
6044          }
6045        }
6046      }
6047    }
6048
6049    /***********************************************************************
6050    * populate the neurons for main host, minimum memory useage
6051    ***********************************************************************/
6052    public void parsePopNeurons()
6053    ////////////////////////////////////////////////////////////////////////
6054    {
6055      //    System.out.println(ls.numberOfNeurons);
6056      //    for(int i = 0 ; i< ls.nodeEndIndices.length; i++)
6057      //    {
6058      //      System.out.print(ls.nodeEndIndices[i]+" ");
6059      //    }
6060      //    System.out.println();
6061
6062      layerStructure.neurons = new Neuron[layerStructure.numberOfNeurons];
6063      
6064      //    ls.branchmaps = new TreeMap[ls.numberOfNeurons];
6065      //    for(int a=0;a<ls.numberOfNeurons;a++) ls.branchmaps[a]
6066      //      =new TreeMap<String, TreeSet<Synapse>>();
6067
6068      NodeList nList = rootElement.getElementsByTagName("Layers");
6069      
6070      Element ele = (Element)nList.item(0);
6071      
6072      NodeList lay = ele.getElementsByTagName("Layer");
6073
6074      int xTotal=0;
6075      
6076      int yTotal=0;
6077      
6078      int xstep=0;
6079      
6080      int ystep=0;
6081      
6082      int xMul, yMul;
6083      
6084      String neu;
6085
6086      for(int it= 0 ; it< lay.getLength(); it++) // add all the layers;
6087      {
6088        xMul = Integer.parseInt(
6089          ((Element)(lay.item(it))).getElementsByTagName("MultiX")
6090          .item(0).getFirstChild().getNodeValue());
6091        
6092        yMul = Integer.parseInt(
6093          ((Element)(lay.item(it))).getElementsByTagName("MultiY")
6094          .item(0).getFirstChild().getNodeValue());
6095        
6096        if(xMul < 0 )
6097        {           
6098          xTotal=layerStructure.edgeLengthX;
6099          
6100          xstep=-xMul;
6101        }
6102        else
6103        {       
6104          xTotal=layerStructure.edgeLengthX*xMul;
6105          
6106          xstep=1;
6107        } 
6108        
6109        if(yMul < 0 )
6110        {       
6111          yTotal=layerStructure.edgeLengthY;
6112          
6113          ystep=-yMul;
6114        }
6115        else
6116        {       
6117          yTotal=layerStructure.edgeLengthY*yMul;
6118          
6119          ystep=1;
6120        }
6121
6122        String n_pre = ((Element)(lay.item(it)))
6123          .getElementsByTagName("Prefix").item(0).getFirstChild()
6124            .getNodeValue();
6125        
6126        String n_suf = ((Element)(lay.item(it)))
6127          .getElementsByTagName("Suffix").item(0).getFirstChild()
6128            .getNodeValue(); 
6129
6130        for(int x = 0 ; x < xTotal; x+=xstep)
6131        {       
6132          for(int y = 0 ; y < yTotal; y+=ystep)
6133          {       
6134            Para neuPara = modelParaMap.get(
6135              ((Element)(lay.item(it))).getElementsByTagName("NeuronType")
6136                .item(0).getFirstChild().getNodeValue());
6137
6138            if(neuPara != null) 
6139            {
6140              if( (neuPara.getModel()).equals("SIFNeuron"))
6141              {
6142                layerStructure.neurons[layerStructure.cellmap_slow(
6143                  n_pre,n_suf,x,y)] = new SIFNeuron((SIFNeuronPara)neuPara);
6144              }
6145              else if((neuPara.getModel()).equals("BKPoissonNeuron"))
6146              {
6147                layerStructure.neurons[layerStructure.cellmap_slow(
6148                  n_pre,n_suf,x,y)] = new BKPoissonNeuron(
6149                    idum,
6150                    (BKPoissonNeuronPara)neuPara);
6151
6152              } 
6153              else if((neuPara.getModel()).equals("VSICLIFNeuron"))
6154              {
6155                layerStructure.neurons[
6156                  layerStructure.cellmap_slow(n_pre,n_suf,x,y)]
6157                    = new VSICLIFNeuron((VSICLIFNeuronPara)neuPara);
6158              } 
6159              else if((neuPara.getModel()).equals("VSICLIFNeuronV2"))
6160              {
6161                layerStructure.neurons[layerStructure.cellmap_slow(
6162                  n_pre,n_suf,x,y)-layerStructure.base]
6163                    = new VSICLIFNeuronV2((VSICLIFNeuronParaV2)neuPara);
6164              } 
6165              else if((neuPara.getModel()).equals("MiNiNeuron"))
6166              {
6167                layerStructure.neurons[layerStructure.cellmap_slow(
6168                  n_pre,n_suf,x,y)-layerStructure.base]
6169                    = new MiNiNeuron((MiNiNeuronPara)neuPara);
6170              } 
6171              else if((neuPara.getModel()).equals("UserSenNeuron"))
6172              {
6173                layerStructure.neurons[layerStructure.cellmap_slow(
6174                  n_pre,n_suf,x,y)] = new UserSenNeuron(
6175                    (UserSenNeuronPara)neuPara, n_pre, n_suf,x,y);
6176              }
6177            }
6178            else
6179            {
6180              throw new RuntimeException(
6181                "Neuron type "
6182                  +((Element)(lay.item(it))).getElementsByTagName(
6183                    "NeuronType").item(0).getFirstChild().getNodeValue()
6184                      +" not defined");
6185            }
6186          }
6187        }
6188      }
6189    }
6190
6191/*
6192    private static double[][] parseConnections(String filename)
6193    ////////////////////////////////////////////////////////////////////////
6194    {  
6195    double[][] conn;
6196    FileReader fr=null;
6197    ArrayList<ArrayList<Double>>
6198      connList=new ArrayList<ArrayList<Double>>();
6199
6200    try
6201    {
6202      fr= new FileReader(filename);
6203    }
6204    catch(FileNotFoundException e)
6205    {
6206      System.err.println("Couldn't get File: " + filename);
6207      System.exit(0);
6208    }
6209
6210    BufferedReader br=new BufferedReader(fr);
6211
6212    try
6213    {
6214      String currentLine;//holds the current line of the file being read.
6215      
6216      // holds each connection weight separated by a space on the line we
6217      // are currently reading.
6218     
6219      String[] currentConnections;
6220      int currLine=0;
6221      boolean moreLines=true;
6222
6223      try
6224      {
6225        while(moreLines)
6226        {
6227          currentLine=br.readLine();
6228          currentConnections=currentLine.split(" ");
6229          if(currentConnections[0].equals("END"))
6230          {
6231            moreLines=false;
6232          }
6233          else
6234          {
6235            connList.add(currLine,new ArrayList<Double>());
6236            for(int a=0;a<currentConnections.length;a++)
6237            {
6238              ((ArrayList) connList.get(currLine)).add(
6239                a,new Double(Double.parseDouble(currentConnections[a])));
6240            }
6241            currLine++;
6242          }
6243        }
6244      }
6245      catch(NumberFormatException e)
6246      {
6247        System.out.println("Number formatting problem in: " + filename);
6248        System.exit(0);
6249      }
6250
6251      br.close();
6252      fr.close();
6253    }
6254    catch(IOException e)
6255    {
6256      System.err.println("Couldn't get IO for: " + filename);
6257      System.exit(0);
6258    }
6259
6260    conn=new double[((ArrayList) connList.get(0)).size()][connList.size()];
6261    for(int y=0;y<connList.size();y++)
6262    {
6263      for(int x=0;x<((ArrayList) connList.get(0)).size();x++)
6264      {
6265        conn[x][y]
6266          =((Double) ((ArrayList) connList.get(y)).get(x)).doubleValue();
6267      }
6268    }
6269
6270    return conn;
6271    }
6272    */
6273
6274    /***********************************************************************
6275    * set the target host id.
6276    ***********************************************************************/
6277    public void parseTarget(JpvmInfo info) throws jpvmException
6278    ////////////////////////////////////////////////////////////////////////
6279    {
6280      TargetID [] targetID = new TargetID[info.numTasks];
6281
6282      for(int i = 0 ; i < info.numTasks; i++)
6283      {
6284        if(i != info.idIndex)
6285        {
6286          targetID[i] = new TargetID(info.idIndex);
6287        }
6288      }
6289
6290      Iterator<Integer> keyIter = layerStructure.axons.keySet().iterator();
6291      long self = (1L<<info.idIndex);
6292      while(keyIter.hasNext())
6293      {
6294        int target = keyIter.next();
6295        int hostDD = FunUtil.hostId(layerStructure.nodeEndIndices,target);
6296        if(hostDD != info.idIndex)
6297        {
6298          targetID[hostDD].target.add(target);
6299        }
6300        else if(hostDD == info.idIndex)
6301        {
6302          // if the neuron doesn't have a target synapse at node then set it
6303          
6304          if((layerStructure.neurons[target - layerStructure.base]
6305            .getTHost() & self )==0)
6306          {
6307            layerStructure.neurons[target - layerStructure.base]
6308              .setTHost(
6309                (layerStructure.neurons[target - layerStructure.base]
6310                  .getTHost() | self));
6311          }
6312        }
6313      }
6314
6315      for(int i = 0 ; i < info.numTasks; i++)
6316      {
6317        if(i != info.idIndex)
6318        {
6319          jpvmBuffer buf2 = new jpvmBuffer();
6320
6321          buf2.pack(targetID[i]); //pack the info
6322
6323          info.jpvm.pvm_send(
6324            buf2,
6325            info.tids[i],
6326            NetMessageTag.assignTargets);
6327        }
6328      }
6329      
6330      //receive all the target info
6331      
6332      jpvmMessage m;
6333      
6334      for(int i = 0 ; i < info.numTasks-1; i++)
6335      {
6336        // receive info from others
6337        
6338        m = info.jpvm.pvm_recv(NetMessageTag.assignTargets);
6339        
6340        TargetID reTID =  (TargetID)m.buffer.upkcnsobj();
6341        
6342        long setID = (1L<<(reTID.target.get(0)));
6343        
6344        int neuronID;
6345        
6346        for(int ii=1; ii< reTID.target.size(); ii++)
6347        {
6348          neuronID = reTID.target.get(ii);
6349          
6350          // if the neuron doesn't have a target synapse at node then set it
6351          
6352          if((layerStructure.neurons[neuronID - layerStructure.base]
6353            .getTHost() & setID )==0)
6354          {
6355            layerStructure.neurons[neuronID - layerStructure.base].setTHost(
6356              (layerStructure.neurons[neuronID - layerStructure.base]
6357                .getTHost() | (setID)));
6358          }
6359        }
6360      }
6361    }
6362    
6363    ////////////////////////////////////////////////////////////////////////
6364    // private methods
6365    ////////////////////////////////////////////////////////////////////////
6366    
6367    private static void  checkDataSetContainsAttributeValues (
6368      final Set<String>  dataSet,
6369      final Element      branchElement,
6370      final String       tagName,
6371      final String       attributeName,
6372      final String       errorMessageSuffix )      
6373    ////////////////////////////////////////////////////////////////////////
6374    {
6375      final NodeList
6376        nodeList = branchElement.getElementsByTagName ( tagName );
6377
6378      final int  nodeListLength = nodeList.getLength ( );
6379
6380      for ( int  i = 0; i < nodeListLength; i++ )
6381      {
6382        final Element  element = ( Element ) nodeList.item ( i );
6383        
6384        final Attr  attr = element.getAttributeNode ( attributeName );
6385        
6386        final String  value = attr.getNodeValue ( );
6387        
6388        if ( !dataSet.contains ( value ) )
6389        {
6390          throw new RuntimeException ( value + errorMessageSuffix );
6391        }
6392      }
6393    }
6394    
6395    private static void  checkDataSetContainsFirstChildValues (
6396      final Set<String>  dataSet,
6397      final Element      branchElement,
6398      final String       tagName,
6399      final String       errorMessageSuffix )      
6400    ////////////////////////////////////////////////////////////////////////
6401    {
6402      final NodeList
6403        nodeList = branchElement.getElementsByTagName ( tagName );
6404
6405      final int  nodeListLength = nodeList.getLength ( );
6406
6407      for ( int  i = 0; i < nodeListLength; i++ )
6408      {
6409        final Element  element = ( Element ) nodeList.item ( i );
6410        
6411        final String  value = element.getFirstChild ( ).getNodeValue ( );
6412        
6413        if ( !dataSet.contains ( value ) )
6414        {
6415          throw new RuntimeException ( value + errorMessageSuffix );
6416        }
6417      }
6418    }
6419    
6420    private static void  checkDataSetContainsFirstGrandchildValues (
6421      final Set<String>  dataSet,
6422      final Element      branchElement,
6423      final String       childTagName,
6424      final String       grandchildTagName,
6425      final String       errorMessageSuffix )
6426    ////////////////////////////////////////////////////////////////////////
6427    {
6428      final NodeList
6429        nodeList = branchElement.getElementsByTagName ( childTagName );
6430  
6431      final int  nodeListLength = nodeList.getLength ( );
6432  
6433      for ( int  i = 0; i < nodeListLength; i++ )
6434      {
6435        final Element  childElement = ( Element ) nodeList.item ( i );
6436    
6437        final NodeList  grandchildNodeList
6438          = childElement.getElementsByTagName ( grandchildTagName );
6439        
6440        if ( grandchildNodeList.getLength ( ) > 0 )
6441        {
6442          final String  value = grandchildNodeList.item ( 0 )
6443            .getFirstChild ( ).getNodeValue ( );
6444      
6445          if ( !dataSet.contains ( value ) )
6446          {
6447            throw new RuntimeException ( value + errorMessageSuffix );
6448          }
6449        }
6450      }
6451    }
6452    
6453    private final static int  checkMax (
6454      final int       max,
6455      final NodeList  nodeList )
6456    ////////////////////////////////////////////////////////////////////////
6457    {
6458      final int  nodeListLength = nodeList.getLength ( );
6459      
6460      if ( nodeListLength != 1 )
6461      {
6462        if ( max != 1
6463          && nodeListLength != max )
6464        {
6465          throw new RuntimeException ( "number does not match" );
6466        }
6467        
6468        return nodeListLength;
6469      }
6470      
6471      return max;
6472    }
6473    
6474    private final static int  checkMax (
6475      final NodeList...  nodeLists )
6476    ////////////////////////////////////////////////////////////////////////
6477    {
6478      int  max = 1;
6479      
6480      for ( final NodeList  nodeList : nodeLists )
6481      {
6482        max = checkMax ( max, nodeList );
6483      }
6484      
6485      return max;
6486    }
6487    
6488    private final double  computeStrength (
6489      final Element  strengthElement,
6490      final Element  multiplierElement,
6491      final Element  offsetElement )
6492    ////////////////////////////////////////////////////////////////////////
6493    {
6494      final double
6495        strength
6496          = getRefDouble ( strengthElement ),
6497        multiplier
6498          = Double.parseDouble (
6499            multiplierElement.getFirstChild ( ).getNodeValue ( ) ),
6500        offset
6501          = Double.parseDouble (
6502            offsetElement.getFirstChild ( ).getNodeValue ( ) );
6503      
6504      return strength * multiplier + offset;
6505    }
6506    
6507    private static Set<String>  createDataSetFromAttributeValues (
6508      final Element  branchElement,
6509      final String   tagName,
6510      final String   attributeName )
6511    ////////////////////////////////////////////////////////////////////////
6512    {
6513      final Set<String>  dataSet = new HashSet<String> ( );
6514      
6515      final NodeList
6516        nodeList = branchElement.getElementsByTagName ( tagName );
6517      
6518      final int  nodeListLength = nodeList.getLength ( );
6519      
6520      for ( int  i = 0; i < nodeListLength; i++ )
6521      {
6522        final Element  element = ( Element ) nodeList.item ( i );
6523        
6524        final Attr  attr = element.getAttributeNode ( attributeName );
6525        
6526        final String  value = attr.getNodeValue ( );
6527        
6528        dataSet.add ( value );
6529      }      
6530      
6531      return dataSet;
6532    }
6533    
6534    private static Set<String>  createDataSetFromFirstChildValues (
6535      final Element  branchElement,
6536      final String   tagName )
6537    ////////////////////////////////////////////////////////////////////////
6538    {
6539      final Set<String>  dataSet = new HashSet<String> ( );
6540      
6541      final NodeList
6542        nodeList = branchElement.getElementsByTagName ( tagName );
6543      
6544      final int  nodeListLength = nodeList.getLength ( );
6545      
6546      for ( int  i = 0; i < nodeListLength; i++ )
6547      {
6548        final Element  element = ( Element ) nodeList.item ( i );
6549        
6550        final String  value = element.getFirstChild ( ).getNodeValue ( );
6551        
6552        dataSet.add ( value );
6553      }      
6554      
6555      return dataSet;
6556    }
6557    
6558    private static Element  getElementAtIndex (
6559      final NodeList  nodeList,
6560      final int       max,
6561      final int       index )
6562    ////////////////////////////////////////////////////////////////////////
6563    {
6564      final int  nodeListLength = nodeList.getLength ( );
6565      
6566      if ( nodeListLength == max )
6567      {
6568        return ( Element ) nodeList.item ( index );
6569      }
6570      
6571      return ( Element ) nodeList.item ( 0 );
6572    }
6573    
6574    private static String  getFirstChildValue ( final Element  element )
6575    ////////////////////////////////////////////////////////////////////////
6576    {
6577      return element.getFirstChild ( ).getNodeValue ( );      
6578    }
6579    
6580    private static Element  getFirstElement (
6581      final Element  parentElement,
6582      final String   tagName )
6583    ////////////////////////////////////////////////////////////////////////
6584    {
6585      final NodeList
6586        nodeList = parentElement.getElementsByTagName ( tagName );
6587      
6588      if ( nodeList.getLength ( ) == 0 )
6589      {
6590        return null;
6591      }        
6592      
6593      return ( Element ) nodeList.item ( 0 );
6594    }
6595    
6596    private static String  getFirstElementFirstChildValue (
6597      final Element  parentElement,
6598      final String   tagName )
6599    ////////////////////////////////////////////////////////////////////////
6600    {
6601      final Element
6602        firstElement = getFirstElement ( parentElement, tagName );
6603      
6604      if ( firstElement == null )
6605      {
6606        return null;
6607      }
6608      
6609      return getFirstChildValue ( firstElement );
6610    }
6611    
6612    
6613    private Double  getRefDouble ( final Element  element )
6614    ////////////////////////////////////////////////////////////////////////
6615    {
6616      final NodeList  refNodeList = element.getElementsByTagName ( "Ref" );
6617      
6618      if ( refNodeList.getLength ( ) > 0 )
6619      {
6620        final String
6621          key = refNodeList.item ( 0 ).getFirstChild ( ).getNodeValue ( );
6622          
6623        final Double  value = doubleDataMap.get ( key );
6624        
6625        if ( value == null )
6626        {
6627          throw new RuntimeException (
6628            key + " as a reference is not defined in Data Section" );
6629        }
6630        
6631        return value;
6632      }
6633      
6634      return Double.parseDouble (
6635        element.getFirstChild ( ).getNodeValue ( ) );
6636    }
6637    
6638    private final double [ ] [ ]
6639      getRefMatrix ( final Element  matrixElement )
6640    ////////////////////////////////////////////////////////////////////////
6641    {
6642      final String  matrixKey
6643        = getFirstElementFirstChildValue ( matrixElement, "Ref" );
6644      
6645      if ( matrixKey != null )
6646      {      
6647        final double [ ] [ ]  matrix = matrixDataMap.get ( matrixKey );
6648
6649        if ( matrix == null )
6650        {
6651          throw new RuntimeException ( matrixKey
6652            +" as a reference is not defined in Data Section" );
6653        }
6654        
6655        return matrix;
6656      }
6657      
6658      return parseMatrix ( matrixElement );
6659    }
6660    
6661    private static final double [ ]  parseDoubleArray (
6662      final String  value )
6663    ////////////////////////////////////////////////////////////////////////
6664    {      
6665      final String [ ]  sep = value.split ( "[,\t ]" );
6666      
6667      final double [ ]  doubleArray = new double [ sep.length ];
6668      
6669      for ( int i = 0; i < sep.length; i++ )
6670      {
6671        doubleArray [ i ] = Double.parseDouble ( sep [ i ] );
6672      }
6673      
6674      return doubleArray;      
6675    }
6676    
6677    private static double [ ] [ ]
6678      parseMatrix ( final Element  matrixElement )
6679    ////////////////////////////////////////////////////////////////////////
6680    {
6681      final NodeList  matrixRowNodeList
6682        = matrixElement.getElementsByTagName ( "Row" );
6683
6684      final String  firstRowValue = matrixRowNodeList
6685        .item ( 0 ).getFirstChild ( ).getNodeValue ( );
6686
6687      final String [ ]
6688        firstSep = firstRowValue.split ( "[a-z,\t ]" );
6689
6690      // System.out.println(sep.length);
6691
6692      final int  matrixRowNodeListLength = matrixRowNodeList.getLength ( );
6693
6694      final double [ ] [ ]  matrix
6695        = new double [ matrixRowNodeListLength ] [ firstSep.length ];
6696
6697      for ( int  colId = 0; colId < firstSep.length; colId++ )
6698      {
6699        matrix [ 0 ] [ colId ]
6700          = Double.parseDouble ( firstSep [ colId ] );
6701      }
6702
6703      for ( int  rowId = 1; rowId < matrixRowNodeListLength; rowId++ )
6704      {
6705        final String  rowValue = matrixRowNodeList
6706          .item ( rowId ).getFirstChild ( ).getNodeValue ( );
6707
6708        final String [ ]  sep = rowValue.split ( "[a-z,\t ]" );
6709
6710        for ( int  colId = 0; colId < sep.length; colId++ )
6711        {
6712          matrix [ rowId ] [ colId ]
6713            = Double.parseDouble ( sep [ colId ] );
6714        }
6715      }
6716      
6717      return matrix;
6718    }
6719    
6720    private static final BKPoissonNeuronPara
6721      parseParametersBkPoissonNeuron ( final Element  neuronElement )
6722    ////////////////////////////////////////////////////////////////////////
6723    {
6724      final BKPoissonNeuronPara
6725        bkPoissonNeuronPara = new BKPoissonNeuronPara ( );
6726      
6727      final String
6728        frequencyValue
6729          = getFirstElementFirstChildValue (
6730            neuronElement,
6731            "Frequency" ),
6732        saturationFrequencyValue
6733          = getFirstElementFirstChildValue (
6734            neuronElement,
6735            "SaturationFrequency" ),
6736        inverseFrequencyDecayTimeValue
6737          = getFirstElementFirstChildValue (
6738            neuronElement,
6739            "InverseFrequencyDecayTime" );
6740      
6741// TODO:  Are high and low frequency flipped?      
6742      
6743      if ( frequencyValue != null )
6744      {
6745        bkPoissonNeuronPara.HighFre
6746          = Double.parseDouble ( frequencyValue );
6747      }
6748      
6749      if ( saturationFrequencyValue != null )
6750      {
6751        bkPoissonNeuronPara.LowFre
6752          = Double.parseDouble ( saturationFrequencyValue );
6753      }
6754      
6755      if ( inverseFrequencyDecayTimeValue != null )
6756      {
6757        bkPoissonNeuronPara.timeCon
6758          = Double.parseDouble ( inverseFrequencyDecayTimeValue );
6759      }
6760      
6761      return bkPoissonNeuronPara;
6762    }
6763    
6764    private static final SIFNeuronPara  parseParametersSifNeuron (
6765      final Element  neuronElement )
6766    ////////////////////////////////////////////////////////////////////////
6767    {
6768      final SIFNeuronPara  sifNeuronPara = new SIFNeuronPara ( );
6769      
6770      final String
6771        capacitanceValue
6772          = getFirstElementFirstChildValue (
6773            neuronElement,
6774            "Capacitance" ),
6775        leakConductanceValue
6776          = getFirstElementFirstChildValue (
6777            neuronElement,
6778            "LeakConductance" ),
6779        decayConstantExcitatoryValue
6780          = getFirstElementFirstChildValue (
6781            neuronElement,
6782            "DecayConstantE" ),
6783        decayConstantInhibitoryValue
6784          = getFirstElementFirstChildValue (
6785            neuronElement,
6786            "DecayConstantI" ),
6787        restingPotentialValue
6788          = getFirstElementFirstChildValue (
6789            neuronElement,
6790            "RestingPotential" ),
6791        resetPotentialValue
6792          = getFirstElementFirstChildValue (
6793            neuronElement,
6794            "ResetPotential" ),
6795        thresholdValue
6796          = getFirstElementFirstChildValue (
6797            neuronElement,
6798            "Threshold" ),
6799        refractoryCurrentValue
6800          = getFirstElementFirstChildValue (
6801            neuronElement,
6802            "RefractoryCurrent" ),
6803        refractoryPeriodValue
6804          = getFirstElementFirstChildValue (
6805            neuronElement,
6806            "RefractoryPeriod" ),
6807        minRiseTimeValue
6808          = getFirstElementFirstChildValue (
6809            neuronElement,
6810            "MinRiseTime" ),
6811        membraneVoltageValue
6812          = getFirstElementFirstChildValue (
6813            neuronElement,
6814            "MembraneVoltage" ),
6815        varMembraneVoltageValue
6816          = getFirstElementFirstChildValue (
6817            neuronElement,
6818            "VarMembraneVoltage" );
6819      
6820      if ( capacitanceValue != null )
6821      {
6822        sifNeuronPara.CAP
6823          = Double.parseDouble ( capacitanceValue );
6824      }
6825      
6826      if ( leakConductanceValue != null )
6827      {
6828        sifNeuronPara.GL
6829          = Double.parseDouble ( leakConductanceValue );
6830      }
6831      
6832      if ( decayConstantExcitatoryValue != null )
6833      {
6834        sifNeuronPara.DECAY_E
6835          = 1 / Double.parseDouble ( decayConstantExcitatoryValue );
6836      }
6837      
6838      if ( decayConstantInhibitoryValue != null )
6839      {
6840        sifNeuronPara.DECAY_I
6841          = 1 / Double.parseDouble ( decayConstantInhibitoryValue );
6842      }
6843      
6844      if ( resetPotentialValue != null )
6845      {
6846        sifNeuronPara.VRESET
6847          = Double.parseDouble ( resetPotentialValue );
6848      }
6849      
6850      if ( restingPotentialValue != null )
6851      {
6852        sifNeuronPara.VREST
6853          = Double.parseDouble ( restingPotentialValue );
6854      }
6855      
6856      if ( thresholdValue != null )
6857      {
6858        sifNeuronPara.THRESHOLD
6859          = Double.parseDouble ( thresholdValue );
6860      }
6861      
6862      if ( refractoryCurrentValue != null )
6863      {
6864        sifNeuronPara.REFCURR
6865          = Math.abs ( Double.parseDouble ( refractoryCurrentValue ) );
6866      }
6867      
6868      if ( refractoryPeriodValue != null )
6869      {
6870        sifNeuronPara.ABSREF
6871          = Double.parseDouble ( refractoryPeriodValue );
6872      }
6873      
6874      if ( minRiseTimeValue != null )
6875      {
6876        sifNeuronPara.MINRISETIME
6877          = Double.parseDouble ( minRiseTimeValue );
6878      }
6879      
6880      if ( membraneVoltageValue != null )
6881      {
6882        sifNeuronPara.ini_mem
6883          = Double.parseDouble ( membraneVoltageValue );
6884      }
6885      
6886      if ( varMembraneVoltageValue != null )
6887      {
6888        sifNeuronPara.ini_memVar
6889          = Double.parseDouble ( varMembraneVoltageValue );
6890      }
6891      
6892      return sifNeuronPara;
6893    }
6894    
6895    private static UserSenNeuronPara  parseParametersUserSenNeuron (
6896      final Element  neuronElement )
6897    ////////////////////////////////////////////////////////////////////////
6898    {
6899      final UserSenNeuronPara
6900        userSenNeuronPara = new UserSenNeuronPara ( );
6901      
6902      final String  dataFileValue = getFirstElementFirstChildValue (
6903        neuronElement,
6904        "DataFile" );
6905
6906      if ( dataFileValue != null )
6907      {
6908        userSenNeuronPara.datafile = dataFileValue;
6909      }
6910      
6911      return userSenNeuronPara;
6912    }
6913
6914    private static VSICLIFNeuronPara  parseParametersVsiclifNeuron (
6915      final Element  neuronElement )
6916    ////////////////////////////////////////////////////////////////////////
6917    {
6918      final VSICLIFNeuronPara
6919        vsiclifNeuronPara = new VSICLIFNeuronPara ( );
6920      
6921      final String
6922        capacitanceValue
6923          = getFirstElementFirstChildValue (
6924            neuronElement,
6925            "Capacitance" ),
6926        leakConductanceValue
6927          = getFirstElementFirstChildValue (
6928            neuronElement,
6929            "LeakConductance" ),
6930        restingPotentialValue
6931          = getFirstElementFirstChildValue (
6932            neuronElement,
6933            "RestingPotential" ),
6934        resetPotentialValue
6935          = getFirstElementFirstChildValue (
6936            neuronElement,
6937            "ResetPotential" ),
6938        asymptoticThresholdValue
6939          = getFirstElementFirstChildValue (
6940            neuronElement,
6941            "AsymptoticThreshold" ),
6942        refractoryCurrentValue
6943          = getFirstElementFirstChildValue (
6944            neuronElement,
6945            "RefractoryCurrent" ),
6946        refractoryPeriodValue
6947          = getFirstElementFirstChildValue (
6948            neuronElement,
6949            "RefractoryPeriod" ),
6950        minRiseTimeValue
6951          = getFirstElementFirstChildValue (
6952            neuronElement,
6953            "MinRiseTime" ),
6954        membraneVoltageValue
6955          = getFirstElementFirstChildValue (
6956            neuronElement,
6957            "MembraneVoltage" ),
6958        varMembraneVoltageValue
6959          = getFirstElementFirstChildValue (
6960            neuronElement,
6961            "VarMembraneVoltage" ),
6962        thresholdAdaptationValue
6963          = getFirstElementFirstChildValue (
6964            neuronElement,
6965            "ThresholdAdaptation" ),
6966        thresholdReboundValue
6967          = getFirstElementFirstChildValue (
6968            neuronElement,
6969            "ThresholdRebound" ),
6970        thresholdResetValue
6971          = getFirstElementFirstChildValue (
6972            neuronElement,
6973            "ThresholdReset" ),
6974        thresholdAdditionValue
6975          = getFirstElementFirstChildValue (
6976            neuronElement,
6977            "ThresholdAddition" ),
6978        externalCurrentValue
6979          = getFirstElementFirstChildValue (
6980            neuronElement,
6981            "ExternalCurrent" ),
6982        initThresholdValue
6983          = getFirstElementFirstChildValue (
6984            neuronElement,
6985            "InitThreshold" ),
6986        decaysValue
6987          = getFirstElementFirstChildValue (
6988            neuronElement,
6989            "Decays" ),
6990        currentsAdditionValue
6991          = getFirstElementFirstChildValue (
6992            neuronElement,
6993            "CurrentsAddition" ),
6994        currentsRatioValue
6995          = getFirstElementFirstChildValue (
6996            neuronElement,
6997            "CurrentsRatio" ),
6998        initCurrentsValue
6999          = getFirstElementFirstChildValue (
7000            neuronElement,
7001            "InitCurrents" );
7002      
7003      if ( capacitanceValue != null )
7004      {
7005        vsiclifNeuronPara.CAP
7006          = Double.parseDouble ( capacitanceValue );
7007      }
7008      
7009      if ( leakConductanceValue != null )
7010      {
7011        vsiclifNeuronPara.GL
7012          = Double.parseDouble ( leakConductanceValue );
7013      }
7014      
7015      if ( resetPotentialValue != null )
7016      {
7017        vsiclifNeuronPara.VRESET
7018          = Double.parseDouble ( resetPotentialValue );
7019      }
7020      
7021      if ( restingPotentialValue != null )
7022      {
7023        vsiclifNeuronPara.VREST
7024          = Double.parseDouble ( restingPotentialValue );
7025      }
7026      
7027      if ( asymptoticThresholdValue != null )
7028      {
7029        vsiclifNeuronPara.THRESHOLD
7030          = Double.parseDouble ( asymptoticThresholdValue );
7031      }
7032      
7033      if ( refractoryCurrentValue != null )
7034      {
7035        vsiclifNeuronPara.REFCURR
7036          = Math.abs ( Double.parseDouble ( refractoryCurrentValue ) );
7037      }
7038      
7039      if ( refractoryPeriodValue != null )
7040      {
7041        vsiclifNeuronPara.ABSREF
7042          = Double.parseDouble ( refractoryPeriodValue );
7043      }
7044      
7045      if ( minRiseTimeValue != null )
7046      {
7047        vsiclifNeuronPara.MINRISETIME
7048          = Double.parseDouble ( minRiseTimeValue );
7049      }
7050      
7051      if ( membraneVoltageValue != null )
7052      {
7053        vsiclifNeuronPara.ini_mem
7054          = Double.parseDouble ( membraneVoltageValue );
7055      }
7056      
7057      if ( varMembraneVoltageValue != null )
7058      {
7059        vsiclifNeuronPara.ini_memVar
7060          = Double.parseDouble ( varMembraneVoltageValue );
7061      }
7062      
7063      if ( thresholdAdaptationValue != null )
7064      {
7065        vsiclifNeuronPara.A
7066          = Double.parseDouble ( thresholdAdaptationValue );
7067      }
7068      
7069      if ( thresholdReboundValue != null )
7070      {
7071        vsiclifNeuronPara.B
7072          = Double.parseDouble ( thresholdReboundValue );
7073      }
7074      
7075      if ( thresholdResetValue != null )
7076      {
7077        vsiclifNeuronPara.RRESET
7078          = Double.parseDouble ( thresholdResetValue );
7079      }
7080      
7081      if ( thresholdAdditionValue != null )
7082      {
7083        vsiclifNeuronPara.THRESHOLDADD
7084          = Double.parseDouble ( thresholdAdditionValue );
7085      }
7086      
7087      if ( externalCurrentValue != null )
7088      {
7089        vsiclifNeuronPara.IEXT
7090          = Double.parseDouble ( externalCurrentValue );
7091      }
7092      
7093      if ( initThresholdValue != null )
7094      {
7095        vsiclifNeuronPara.ini_threshold
7096          = Double.parseDouble ( initThresholdValue );
7097      }
7098      
7099      if ( decaysValue != null )
7100      {
7101        vsiclifNeuronPara.DECAY
7102          = invertDoubleArray ( parseDoubleArray ( decaysValue ) );
7103      }
7104      
7105      if ( currentsAdditionValue != null )
7106      {
7107        vsiclifNeuronPara.IADD
7108          = parseDoubleArray ( currentsAdditionValue );
7109      }
7110      
7111      if ( currentsRatioValue != null )
7112      {
7113        vsiclifNeuronPara.IRATIO
7114          = parseDoubleArray ( currentsRatioValue );
7115      }
7116      
7117      if ( initCurrentsValue != null )
7118      {
7119        vsiclifNeuronPara.ini_curr
7120          = parseDoubleArray ( initCurrentsValue );
7121      }
7122      
7123      // calculate all the necessary things
7124
7125      vsiclifNeuronPara.calConstants ( );
7126      
7127      return vsiclifNeuronPara;
7128    }
7129    
7130    private static MiNiNeuronPara  parseParametersMiNiNeuron (
7131      final Element  neuronElement )
7132    ////////////////////////////////////////////////////////////////////////
7133    {
7134      final MiNiNeuronPara
7135        miNiNeuronPara = new MiNiNeuronPara ( );
7136      
7137      final String
7138        capacitanceValue
7139          = getFirstElementFirstChildValue (
7140            neuronElement,
7141            "Capacitance" ),
7142        leakConductanceValue
7143          = getFirstElementFirstChildValue (
7144            neuronElement,
7145            "LeakConductance" ),
7146        restingPotentialValue
7147          = getFirstElementFirstChildValue (
7148            neuronElement,
7149            "RestingPotential" ),
7150        resetPotentialValue
7151          = getFirstElementFirstChildValue (
7152            neuronElement,
7153            "ResetPotential" ),
7154        asymptoticThresholdValue
7155          = getFirstElementFirstChildValue (
7156            neuronElement,
7157            "AsymptoticThreshold" ),
7158        refractoryCurrentValue
7159          = getFirstElementFirstChildValue (
7160            neuronElement,
7161            "RefractoryCurrent" ),
7162        refractoryPeriodValue
7163          = getFirstElementFirstChildValue (
7164            neuronElement,
7165            "RefractoryPeriod" ),
7166        membraneVoltageValue
7167          = getFirstElementFirstChildValue (
7168            neuronElement,
7169            "MembraneVoltage" ),
7170        varMembraneVoltageValue
7171          = getFirstElementFirstChildValue (
7172            neuronElement,
7173            "VarMembraneVoltage" ),
7174        thresholdAdaptationValue
7175          = getFirstElementFirstChildValue (
7176            neuronElement,
7177            "ThresholdAdaptation" ),
7178        thresholdReboundValue
7179          = getFirstElementFirstChildValue (
7180            neuronElement,
7181            "ThresholdRebound" ),
7182        thresholdResetValue
7183          = getFirstElementFirstChildValue (
7184            neuronElement,
7185            "ThresholdReset" ),
7186        thresholdAdditionValue
7187          = getFirstElementFirstChildValue (
7188            neuronElement,
7189            "ThresholdAddition" ),
7190        externalCurrentValue
7191          = getFirstElementFirstChildValue (
7192            neuronElement,
7193            "ExternalCurrent" ),
7194        initThresholdValue
7195          = getFirstElementFirstChildValue (
7196            neuronElement,
7197            "InitThreshold" ),
7198        kLtdValue
7199          = getFirstElementFirstChildValue (
7200            neuronElement,
7201            "K_LTD" ),
7202        kLtpValue
7203          = getFirstElementFirstChildValue (
7204            neuronElement,
7205            "K_LTP" ),
7206        alphaLtpValue
7207          = getFirstElementFirstChildValue (
7208            neuronElement,
7209            "Alpha_LTP" ),
7210        alphaLtdValue
7211          = getFirstElementFirstChildValue (
7212            neuronElement,
7213            "Alpha_LTD" ),
7214        spikeDecaysValue
7215          = getFirstElementFirstChildValue (
7216            neuronElement,
7217            "SpikeDecays" ),
7218        synapseDecaysValue
7219            = getFirstElementFirstChildValue (
7220              neuronElement,
7221              "SynapseDecays" ),
7222        spikeCurrentsAdditionValue
7223          = getFirstElementFirstChildValue (
7224            neuronElement,
7225            "SpikeCurrentsAddition" ),
7226        spikeCurrentsRatioValue
7227          = getFirstElementFirstChildValue (
7228            neuronElement,
7229            "SpikeCurrentsRatio" ),
7230        initSpikeCurrentsValue
7231          = getFirstElementFirstChildValue (
7232            neuronElement,
7233            "InitSpikeCurrents" );
7234      
7235      if ( capacitanceValue != null )
7236      {
7237        miNiNeuronPara.CAP
7238          = Double.parseDouble ( capacitanceValue );
7239      }
7240      
7241      if ( leakConductanceValue != null )
7242      {
7243        miNiNeuronPara.GL
7244          = Double.parseDouble ( leakConductanceValue );
7245      }
7246      
7247      if ( resetPotentialValue != null )
7248      {
7249        miNiNeuronPara.VRESET
7250          = Double.parseDouble ( resetPotentialValue );
7251      }
7252      
7253      if ( restingPotentialValue != null )
7254      {
7255        miNiNeuronPara.VREST
7256          = Double.parseDouble ( restingPotentialValue );
7257      }
7258      
7259      if ( asymptoticThresholdValue != null )
7260      {
7261        miNiNeuronPara.THRESHOLD
7262          = Double.parseDouble ( asymptoticThresholdValue );
7263      }
7264      
7265      if ( refractoryCurrentValue != null )
7266      {
7267        miNiNeuronPara.REFCURR
7268          = Math.abs ( Double.parseDouble ( refractoryCurrentValue ) );
7269      }
7270      
7271      if ( refractoryPeriodValue != null )
7272      {
7273        miNiNeuronPara.ABSREF
7274          = Double.parseDouble ( refractoryPeriodValue );
7275      }
7276          
7277      if ( membraneVoltageValue != null )
7278      {
7279        miNiNeuronPara.ini_mem
7280          = Double.parseDouble ( membraneVoltageValue );
7281      }
7282      
7283      if ( varMembraneVoltageValue != null )
7284      {
7285        miNiNeuronPara.ini_memVar
7286          = Double.parseDouble ( varMembraneVoltageValue );
7287      }
7288      
7289      if ( thresholdAdaptationValue != null )
7290      {
7291        miNiNeuronPara.A
7292          = Double.parseDouble ( thresholdAdaptationValue );
7293      }
7294      
7295      if ( thresholdReboundValue != null )
7296      {
7297        miNiNeuronPara.B
7298          = Double.parseDouble ( thresholdReboundValue );
7299      }
7300      
7301      if ( thresholdResetValue != null )
7302      {
7303        miNiNeuronPara.RRESET
7304          = Double.parseDouble ( thresholdResetValue );
7305      }
7306      
7307      if ( thresholdAdditionValue != null )
7308      {
7309        miNiNeuronPara.THRESHOLDADD
7310          = Double.parseDouble ( thresholdAdditionValue );
7311      }
7312      
7313      if ( externalCurrentValue != null )
7314      {
7315        miNiNeuronPara.IEXT
7316          = Double.parseDouble ( externalCurrentValue );
7317      }
7318      
7319      if ( initThresholdValue != null )
7320      {
7321        miNiNeuronPara.ini_threshold
7322          = Double.parseDouble ( initThresholdValue );
7323      }
7324      
7325      // begin spike-timing depependent plasticity (STDP) parameters
7326      
7327      if ( kLtdValue != null )
7328      {
7329        miNiNeuronPara.K_LTD
7330          = Double.parseDouble ( kLtdValue );
7331      }
7332      
7333      if ( kLtpValue != null )
7334      {
7335        miNiNeuronPara.K_LTP
7336          = Double.parseDouble ( kLtpValue );
7337      }
7338      
7339      if ( alphaLtpValue != null )
7340      {
7341        miNiNeuronPara.Alpha_LTP
7342          = Double.parseDouble ( alphaLtpValue );
7343      }
7344      
7345      if ( alphaLtdValue != null )
7346      {
7347        miNiNeuronPara.Alpha_LTD
7348          = Double.parseDouble ( alphaLtdValue );
7349      }
7350      
7351      // end STDP parameters
7352      
7353      if ( spikeDecaysValue != null )
7354      {
7355        miNiNeuronPara.DECAY_SPIKE
7356          = invertDoubleArray ( parseDoubleArray ( spikeDecaysValue ) );
7357      }
7358      
7359      if ( synapseDecaysValue != null )
7360      {
7361        miNiNeuronPara.DECAY_SYNAPSE
7362          = invertDoubleArray ( parseDoubleArray ( synapseDecaysValue ) );
7363      }
7364      
7365      if ( spikeCurrentsAdditionValue != null )
7366      {
7367        miNiNeuronPara.SPIKE_ADD
7368          = parseDoubleArray ( spikeCurrentsAdditionValue );
7369      }
7370      
7371      if ( spikeCurrentsRatioValue != null )
7372      {
7373        miNiNeuronPara.SPIKE_RATIO
7374          = parseDoubleArray ( spikeCurrentsRatioValue );
7375      }
7376      
7377      if ( initSpikeCurrentsValue != null )
7378      {
7379        miNiNeuronPara.ini_spike_curr
7380          = parseDoubleArray ( initSpikeCurrentsValue );
7381      }
7382      
7383      // calculate all the necessary things
7384
7385      miNiNeuronPara.calConstants ( );
7386    
7387      return miNiNeuronPara;
7388    }
7389    
7390    private static VSICLIFNeuronParaV2  parseParametersVsiclifNeuronV2 (
7391        final Element  neuronElement )
7392      ////////////////////////////////////////////////////////////////////////
7393      {
7394        final VSICLIFNeuronParaV2
7395          vsiclifNeuronParaV2 = new VSICLIFNeuronParaV2 ( );
7396        
7397        final String
7398          capacitanceValue
7399            = getFirstElementFirstChildValue (
7400              neuronElement,
7401              "Capacitance" ),
7402          leakConductanceValue
7403            = getFirstElementFirstChildValue (
7404              neuronElement,
7405              "LeakConductance" ),
7406          restingPotentialValue
7407            = getFirstElementFirstChildValue (
7408              neuronElement,
7409              "RestingPotential" ),
7410          resetPotentialValue
7411            = getFirstElementFirstChildValue (
7412              neuronElement,
7413              "ResetPotential" ),
7414          asymptoticThresholdValue
7415            = getFirstElementFirstChildValue (
7416              neuronElement,
7417              "AsymptoticThreshold" ),
7418          refractoryCurrentValue
7419            = getFirstElementFirstChildValue (
7420              neuronElement,
7421              "RefractoryCurrent" ),
7422          refractoryPeriodValue
7423            = getFirstElementFirstChildValue (
7424              neuronElement,
7425              "RefractoryPeriod" ),
7426          minRiseTimeValue
7427            = getFirstElementFirstChildValue (
7428              neuronElement,
7429              "MinRiseTime" ),
7430          membraneVoltageValue
7431            = getFirstElementFirstChildValue (
7432              neuronElement,
7433              "MembraneVoltage" ),
7434          varMembraneVoltageValue
7435            = getFirstElementFirstChildValue (
7436              neuronElement,
7437              "VarMembraneVoltage" ),
7438          thresholdAdaptationValue
7439            = getFirstElementFirstChildValue (
7440              neuronElement,
7441              "ThresholdAdaptation" ),
7442          thresholdReboundValue
7443            = getFirstElementFirstChildValue (
7444              neuronElement,
7445              "ThresholdRebound" ),
7446          thresholdResetValue
7447            = getFirstElementFirstChildValue (
7448              neuronElement,
7449              "ThresholdReset" ),
7450          thresholdAdditionValue
7451            = getFirstElementFirstChildValue (
7452              neuronElement,
7453              "ThresholdAddition" ),
7454          externalCurrentValue
7455            = getFirstElementFirstChildValue (
7456              neuronElement,
7457              "ExternalCurrent" ),
7458          initThresholdValue
7459            = getFirstElementFirstChildValue (
7460              neuronElement,
7461              "InitThreshold" ),
7462          kLtdValue
7463            = getFirstElementFirstChildValue (
7464              neuronElement,
7465              "K_LTD" ),
7466          kLtpValue
7467            = getFirstElementFirstChildValue (
7468              neuronElement,
7469              "K_LTP" ),
7470          alphaLtpValue
7471            = getFirstElementFirstChildValue (
7472              neuronElement,
7473              "Alpha_LTP" ),
7474          alphaLtdValue
7475            = getFirstElementFirstChildValue (
7476              neuronElement,
7477              "Alpha_LTD" ),
7478          decaysValue
7479            = getFirstElementFirstChildValue (
7480              neuronElement,
7481              "Decays" ),
7482          currentsAdditionValue
7483            = getFirstElementFirstChildValue (
7484              neuronElement,
7485              "CurrentsAddition" ),
7486          currentsRatioValue
7487            = getFirstElementFirstChildValue (
7488              neuronElement,
7489              "CurrentsRatio" ),
7490          initCurrentsValue
7491            = getFirstElementFirstChildValue (
7492              neuronElement,
7493              "InitCurrents" );
7494        
7495        if ( capacitanceValue != null )
7496        {
7497          vsiclifNeuronParaV2.CAP
7498            = Double.parseDouble ( capacitanceValue );
7499        }
7500        
7501        if ( leakConductanceValue != null )
7502        {
7503          vsiclifNeuronParaV2.GL
7504            = Double.parseDouble ( leakConductanceValue );
7505        }
7506        
7507        if ( resetPotentialValue != null )
7508        {
7509          vsiclifNeuronParaV2.VRESET
7510            = Double.parseDouble ( resetPotentialValue );
7511        }
7512        
7513        if ( restingPotentialValue != null )
7514        {
7515          vsiclifNeuronParaV2.VREST
7516            = Double.parseDouble ( restingPotentialValue );
7517        }
7518        
7519        if ( asymptoticThresholdValue != null )
7520        {
7521          vsiclifNeuronParaV2.THRESHOLD
7522            = Double.parseDouble ( asymptoticThresholdValue );
7523        }
7524        
7525        if ( refractoryCurrentValue != null )
7526        {
7527          vsiclifNeuronParaV2.REFCURR
7528            = Math.abs ( Double.parseDouble ( refractoryCurrentValue ) );
7529        }
7530        
7531        if ( refractoryPeriodValue != null )
7532        {
7533          vsiclifNeuronParaV2.ABSREF
7534            = Double.parseDouble ( refractoryPeriodValue );
7535        }
7536        
7537        if ( minRiseTimeValue != null )
7538        {
7539          vsiclifNeuronParaV2.MINRISETIME
7540            = Double.parseDouble ( minRiseTimeValue );
7541        }
7542        
7543        if ( membraneVoltageValue != null )
7544        {
7545          vsiclifNeuronParaV2.ini_mem
7546            = Double.parseDouble ( membraneVoltageValue );
7547        }
7548        
7549        if ( varMembraneVoltageValue != null )
7550        {
7551          vsiclifNeuronParaV2.ini_memVar
7552            = Double.parseDouble ( varMembraneVoltageValue );
7553        }
7554        
7555        if ( thresholdAdaptationValue != null )
7556        {
7557          vsiclifNeuronParaV2.A
7558            = Double.parseDouble ( thresholdAdaptationValue );
7559        }
7560        
7561        if ( thresholdReboundValue != null )
7562        {
7563          vsiclifNeuronParaV2.B
7564            = Double.parseDouble ( thresholdReboundValue );
7565        }
7566        
7567        if ( thresholdResetValue != null )
7568        {
7569          vsiclifNeuronParaV2.RRESET
7570            = Double.parseDouble ( thresholdResetValue );
7571        }
7572        
7573        if ( thresholdAdditionValue != null )
7574        {
7575          vsiclifNeuronParaV2.THRESHOLDADD
7576            = Double.parseDouble ( thresholdAdditionValue );
7577        }
7578        
7579        if ( externalCurrentValue != null )
7580        {
7581          vsiclifNeuronParaV2.IEXT
7582            = Double.parseDouble ( externalCurrentValue );
7583        }
7584        
7585        if ( initThresholdValue != null )
7586        {
7587          vsiclifNeuronParaV2.ini_threshold
7588            = Double.parseDouble ( initThresholdValue );
7589        }
7590        
7591        // begin spike-timing depependent plasticity (STDP) parameters
7592        
7593        if ( kLtdValue != null )
7594        {
7595          vsiclifNeuronParaV2.K_LTD
7596            = Double.parseDouble ( kLtdValue );
7597        }
7598        
7599        if ( kLtpValue != null )
7600        {
7601          vsiclifNeuronParaV2.K_LTP
7602            = Double.parseDouble ( kLtpValue );
7603        }
7604        
7605        if ( alphaLtpValue != null )
7606        {
7607          vsiclifNeuronParaV2.Alpha_LTP
7608            = Double.parseDouble ( alphaLtpValue );
7609        }
7610        
7611        if ( alphaLtdValue != null )
7612        {
7613          vsiclifNeuronParaV2.Alpha_LTD
7614            = Double.parseDouble ( alphaLtdValue );
7615        }
7616        
7617        // end STDP parameters
7618        
7619        if ( decaysValue != null )
7620        {
7621          vsiclifNeuronParaV2.DECAY
7622            = invertDoubleArray ( parseDoubleArray ( decaysValue ) );
7623        }
7624        
7625        if ( currentsAdditionValue != null )
7626        {
7627          vsiclifNeuronParaV2.IADD
7628            = parseDoubleArray ( currentsAdditionValue );
7629        }
7630        
7631        if ( currentsRatioValue != null )
7632        {
7633          vsiclifNeuronParaV2.IRATIO
7634            = parseDoubleArray ( currentsRatioValue );
7635        }
7636        
7637        if ( initCurrentsValue != null )
7638        {
7639          vsiclifNeuronParaV2.ini_curr
7640            = parseDoubleArray ( initCurrentsValue );
7641        }
7642        
7643        // calculate all the necessary things
7644
7645        vsiclifNeuronParaV2.calConstants ( );
7646      
7647        return vsiclifNeuronParaV2;
7648      }
7649    
7650    private static boolean  parsePeriodic (
7651      final Element  connectionElement )
7652    ////////////////////////////////////////////////////////////////////////
7653    {
7654      final String  value = connectionElement.getAttribute ( "periodic" );
7655
7656      return value.equals ( "true" )
7657          || value.equals ( "TRUE" );
7658    }
7659    
7660// TODO:  Merge the parseScaffold methods into one if possible
7661    
7662    private void  parseScaffold (
7663      final int      hostId,
7664      final Element  connectionElement )
7665    ////////////////////////////////////////////////////////////////////////
7666    {
7667      final NodeList
7668        fromLayerNodeList
7669          = connectionElement.getElementsByTagName ( "FromLayer" ),
7670        toLayerNodeList
7671          = connectionElement.getElementsByTagName ( "ToLayer" ),
7672        strengthNodeList
7673          = connectionElement.getElementsByTagName ( "Strength" ),
7674        multiplierNodeList
7675          = connectionElement.getElementsByTagName ( "Multiplier" ),
7676        offsetNodeList
7677          = connectionElement.getElementsByTagName ( "Offset" ),
7678        typeNodeList
7679          = connectionElement.getElementsByTagName ( "Type" ),
7680        delayNodeList
7681          = connectionElement.getElementsByTagName ( "Delay" ),          
7682        matrixNodeList
7683          = connectionElement.getElementsByTagName ( "Matrix" ),
7684        rotationNodeList
7685          = connectionElement.getElementsByTagName ( "Rotation" );
7686      
7687      final int  max = checkMax (
7688        fromLayerNodeList,
7689        toLayerNodeList,
7690        strengthNodeList,
7691        multiplierNodeList,
7692        offsetNodeList,
7693        typeNodeList,
7694        delayNodeList,
7695        matrixNodeList,
7696        rotationNodeList );
7697      
7698      for ( int  i = 0; i < max; i++ )
7699      {
7700        final Element
7701          fromLayerElement
7702            = getElementAtIndex ( fromLayerNodeList,  max, i ),
7703          toLayerElement
7704            = getElementAtIndex ( toLayerNodeList,    max, i ),
7705          strengthElement
7706            = getElementAtIndex ( strengthNodeList,   max, i ),
7707          multiplierElement
7708            = getElementAtIndex ( multiplierNodeList, max, i ),
7709          offsetElement
7710            = getElementAtIndex ( offsetNodeList,     max, i ),
7711          typeElement
7712            = getElementAtIndex ( typeNodeList,       max, i ),
7713          delayElement
7714            = getElementAtIndex ( delayNodeList,      max, i ),
7715          matrixElement
7716            = getElementAtIndex ( matrixNodeList,     max, i ),
7717          rotationElement
7718            = getElementAtIndex ( rotationNodeList,   max, i );
7719            
7720        
7721        // no periodic, no vergence, no strength matrix arguments
7722
7723        layerStructure.popScaffold (
7724          fromLayerElement.getAttribute ( "prefix" ),
7725          fromLayerElement.getAttribute ( "suffix" ),
7726          toLayerElement  .getAttribute ( "prefix" ),
7727          toLayerElement  .getAttribute ( "suffix" ),
7728          computeStrength (
7729            strengthElement,
7730            multiplierElement,
7731            offsetElement ),
7732          parseSynapseType ( typeElement ),
7733          getRefDouble ( delayElement ),
7734          rotateMatrix (
7735            getRefMatrix ( matrixElement ),
7736            rotationElement ),
7737          hostId );
7738      }
7739    }
7740    
7741    private void  parseScaffoldWithPeriodicAndStrengthMatrix (
7742      final int      hostId,
7743      final Element  connectionElement )
7744    ////////////////////////////////////////////////////////////////////////
7745    {
7746      final NodeList
7747        fromLayerNodeList
7748          = connectionElement.getElementsByTagName ( "FromLayer" ),
7749        toLayerNodeList
7750          = connectionElement.getElementsByTagName ( "ToLayer" ),          
7751        styleNodeList
7752          = connectionElement.getElementsByTagName ( "Style" ),
7753        strengthNodeList
7754          = connectionElement.getElementsByTagName ( "Strength" ),
7755        multiplierNodeList
7756          = connectionElement.getElementsByTagName ( "Multiplier" ),
7757        offsetNodeList
7758          = connectionElement.getElementsByTagName ( "Offset" ),
7759        typeNodeList
7760          = connectionElement.getElementsByTagName ( "Type" ),
7761        delayNodeList
7762          = connectionElement.getElementsByTagName ( "Delay" ),
7763        pMatrixNodeList
7764          = connectionElement.getElementsByTagName ( "PMatrix" ),
7765        sMatrixNodeList
7766          = connectionElement.getElementsByTagName ( "SMatrix" ),
7767        rotationNodeList
7768          = connectionElement.getElementsByTagName ( "Rotation" );
7769      
7770      int  max = checkMax (
7771        fromLayerNodeList,
7772        toLayerNodeList,
7773        styleNodeList,
7774        strengthNodeList,
7775        multiplierNodeList,
7776        offsetNodeList,
7777        typeNodeList,
7778        delayNodeList,        
7779        pMatrixNodeList,
7780        rotationNodeList );
7781      
7782      // strength matrix exist or not
7783
7784      boolean  str_matrix = false;
7785
7786      if ( sMatrixNodeList.getLength ( ) > 0 )
7787      {
7788        max = checkMax ( max, sMatrixNodeList );
7789
7790        str_matrix = true;
7791      }
7792
7793      final boolean  periodic = parsePeriodic ( connectionElement );
7794
7795      for ( int  i = 0; i < max; i++ )
7796      {
7797        final Element
7798          fromLayerElement
7799            = getElementAtIndex ( fromLayerNodeList,  max, i ),
7800          toLayerElement
7801            = getElementAtIndex ( toLayerNodeList,    max, i ),
7802          styleElement
7803            = getElementAtIndex ( styleNodeList,      max, i ),
7804          strengthElement
7805            = getElementAtIndex ( strengthNodeList,   max, i ),
7806          multiplierElement
7807            = getElementAtIndex ( multiplierNodeList, max, i ),
7808          offsetElement
7809            = getElementAtIndex ( offsetNodeList,     max, i ),
7810          typeElement
7811            = getElementAtIndex ( typeNodeList,       max, i ),
7812          delayElement
7813            = getElementAtIndex ( delayNodeList,      max, i ),
7814          pMatrixElement
7815            = getElementAtIndex ( pMatrixNodeList,    max, i ),
7816          rotationElement
7817            = getElementAtIndex ( rotationNodeList,   max, i );
7818      
7819        double [ ] [ ]  sconMatrix = null;
7820
7821        // if strength matrix exists
7822        
7823        if ( str_matrix )
7824        {
7825          final Element
7826            eSmatrix = getElementAtIndex ( sMatrixNodeList, max, i );
7827
7828          sconMatrix = rotateMatrix (
7829            getRefMatrix ( eSmatrix ),
7830            rotationElement );
7831        }
7832        
7833        // accepts periodic and strength matrix
7834
7835        layerStructure.popScaffold (
7836          fromLayerElement.getAttribute ( "prefix" ),
7837          fromLayerElement.getAttribute ( "suffix" ),
7838          toLayerElement  .getAttribute ( "prefix" ),
7839          toLayerElement  .getAttribute ( "suffix" ),
7840          parseVergenceStyle ( styleElement ),
7841          computeStrength (
7842            strengthElement,
7843            multiplierElement,
7844            offsetElement ),
7845          parseSynapseType ( typeElement ),
7846          getRefDouble ( delayElement ),
7847          rotateMatrix (
7848            getRefMatrix ( pMatrixElement ),
7849            rotationElement ),
7850          sconMatrix,
7851          hostId,
7852          periodic );
7853      }
7854    }
7855    
7856    private void  parseScaffoldWithPeriodic (
7857      final int      hostId,
7858      final Element  connectionElement )
7859    ////////////////////////////////////////////////////////////////////////
7860    {
7861      final NodeList
7862        fromLayerNodeList
7863          = connectionElement.getElementsByTagName ( "FromLayer" ),
7864        toLayerNodeList
7865          = connectionElement.getElementsByTagName ( "ToLayer" ),
7866        styleNodeList
7867          = connectionElement.getElementsByTagName ( "Style" ),
7868        strengthNodeList
7869          = connectionElement.getElementsByTagName ( "Strength" ),
7870        multiplierNodeList
7871          = connectionElement.getElementsByTagName ( "Multiplier" ),
7872        offsetNodeList
7873          = connectionElement.getElementsByTagName ( "Offset" ),
7874        typeNodeList
7875          = connectionElement.getElementsByTagName ( "Type" ),
7876        delayNodeList
7877          = connectionElement.getElementsByTagName ( "Delay" ),
7878        matrixNodeList
7879          = connectionElement.getElementsByTagName ( "Matrix" ),
7880        rotationNodeList
7881          = connectionElement.getElementsByTagName ( "Rotation" );
7882      
7883      final int  max = checkMax (
7884        fromLayerNodeList,
7885        toLayerNodeList,
7886        styleNodeList,
7887        strengthNodeList,
7888        multiplierNodeList,
7889        offsetNodeList,
7890        typeNodeList,
7891        delayNodeList,
7892        matrixNodeList,
7893        rotationNodeList );
7894      
7895      final boolean  periodic = parsePeriodic ( connectionElement );
7896      
7897      for ( int  i = 0; i < max; i++ )
7898      {
7899        final Element
7900          fromLayerElement
7901            = getElementAtIndex ( fromLayerNodeList,  max, i ),
7902          toLayerElement
7903            = getElementAtIndex ( toLayerNodeList,    max, i ),
7904          styleElement
7905            = getElementAtIndex ( styleNodeList,      max, i ),
7906          strengthElement
7907            = getElementAtIndex ( strengthNodeList,   max, i ),
7908          multiplierElement
7909            = getElementAtIndex ( multiplierNodeList, max, i ),
7910          offsetElement
7911            = getElementAtIndex ( offsetNodeList,     max, i ),
7912          typeElement
7913            = getElementAtIndex ( typeNodeList,       max, i ),
7914          delayElement
7915            = getElementAtIndex ( delayNodeList,      max, i ),
7916          matrixElement
7917            = getElementAtIndex ( matrixNodeList,     max, i ),
7918          rotationElement
7919            = getElementAtIndex ( rotationNodeList,   max, i );
7920        
7921        // accepts periodic argument
7922        
7923        layerStructure.popScaffold (
7924          fromLayerElement.getAttribute ( "prefix" ),
7925          fromLayerElement.getAttribute ( "suffix" ),
7926          toLayerElement  .getAttribute ( "prefix" ),
7927          toLayerElement  .getAttribute ( "suffix" ),
7928          parseVergenceStyle ( styleElement ),
7929          computeStrength (
7930            strengthElement,
7931            multiplierElement,
7932            offsetElement ),
7933          parseSynapseType ( typeElement ),
7934          getRefDouble ( delayElement ),
7935          rotateMatrix (
7936            getRefMatrix ( matrixElement ),
7937            rotationElement ),
7938          hostId,
7939          periodic );
7940      }
7941    }
7942    
7943    private void  parseScaffoldWithStrengthMatrix (
7944      int      hostId,
7945      Element  connectionElement )
7946    ////////////////////////////////////////////////////////////////////////
7947    {
7948      final NodeList
7949        fromLayerNodeList
7950          = connectionElement.getElementsByTagName ( "FromLayer" ),
7951        toLayerNodeList
7952          = connectionElement.getElementsByTagName ( "ToLayer" ),
7953        styleNodeList
7954          = connectionElement.getElementsByTagName ( "Style" ),
7955        strengthNodeList
7956          = connectionElement.getElementsByTagName ( "Strength" ),
7957        multiplierNodeList
7958          = connectionElement.getElementsByTagName ( "Multiplier" ),
7959        offsetNodeList
7960          = connectionElement.getElementsByTagName ( "Offset" ),
7961        typeNodeList
7962          = connectionElement.getElementsByTagName ( "Type" ),
7963        delayNodeList
7964          = connectionElement.getElementsByTagName ( "Delay" ),
7965        pMatrixNodeList
7966          = connectionElement.getElementsByTagName ( "PMatrix" ),
7967        sMatrixNodeList
7968          = connectionElement.getElementsByTagName ( "SMatrix" ),
7969        rotationNodeList
7970          = connectionElement.getElementsByTagName ( "Rotation" );
7971
7972      int  max = checkMax (
7973        fromLayerNodeList,
7974        toLayerNodeList,
7975        styleNodeList,
7976        strengthNodeList,
7977        multiplierNodeList,
7978        offsetNodeList,
7979        typeNodeList,
7980        delayNodeList,
7981        pMatrixNodeList,
7982        rotationNodeList );
7983      
7984      // strength matrix exist or not
7985
7986      boolean  str_matrix = false;
7987
7988      if ( sMatrixNodeList.getLength ( ) > 0 )
7989      {
7990        max = checkMax ( max, sMatrixNodeList );
7991
7992        str_matrix = true;
7993      }
7994
7995      // System.out.println("max"+max);
7996
7997      for ( int  i = 0; i < max; i++ )
7998      {
7999        final Element
8000          fromElement
8001            = getElementAtIndex ( fromLayerNodeList,  max, i ),
8002          toElement
8003            = getElementAtIndex ( toLayerNodeList,    max, i ),
8004          strengthElement
8005            = getElementAtIndex ( strengthNodeList,   max, i ),
8006          multiplierElement
8007            = getElementAtIndex ( multiplierNodeList, max, i ),
8008          offsetElement
8009            = getElementAtIndex ( offsetNodeList,     max, i ),
8010          typeElement
8011            = getElementAtIndex ( typeNodeList,       max, i ),
8012          delayElement
8013            = getElementAtIndex ( delayNodeList,      max, i ),
8014          pMatrixElement
8015            = getElementAtIndex ( pMatrixNodeList,    max, i ),
8016          rotationElement
8017            = getElementAtIndex ( rotationNodeList,   max, i );
8018    
8019        double [ ] [ ]  sConMatrix = null;
8020
8021        if ( str_matrix ) // if strength matrix exists
8022        {
8023          final Element
8024            eSmatrix = getElementAtIndex ( strengthNodeList, max, i );
8025
8026          sConMatrix = rotateMatrix (
8027            getRefMatrix ( eSmatrix ),
8028            rotationElement );
8029        }
8030        
8031        // accepts strength matrix but no vergence style argument
8032
8033        layerStructure.popScaffold (
8034          fromElement.getAttribute ( "prefix" ),
8035          fromElement.getAttribute ( "suffix" ),
8036          toElement  .getAttribute ( "prefix" ),
8037          toElement  .getAttribute ( "suffix" ),
8038          computeStrength (
8039            strengthElement,
8040            multiplierElement,
8041            offsetElement ),
8042          parseSynapseType ( typeElement ),
8043          getRefDouble ( delayElement ),
8044          rotateMatrix (
8045            getRefMatrix ( pMatrixElement ),
8046            rotationElement ),
8047          sConMatrix,
8048          hostId );
8049      }
8050    }
8051    
8052    /***********************************************************************
8053    * This one differs from the others in that it assumes there is just one
8054    * of each element and that the prefixes and suffixes are taken from
8055    * node values instead of attributes. 
8056    ***********************************************************************/    
8057    private void  parseScaffoldWithPeriodicAndSingleElement (
8058      final int      hostId,
8059      final Element  connectionElement )
8060    ////////////////////////////////////////////////////////////////////////
8061    {
8062      final Element
8063        fromLayerElement
8064          = getFirstElement ( connectionElement, "FromLayer" ),
8065        toLayerElement
8066          = getFirstElement ( connectionElement, "ToLayer" ),
8067        styleElement
8068          = getFirstElement ( connectionElement, "Style" ),
8069        strengthElement
8070          = getFirstElement ( connectionElement, "Strength" ),
8071        multiplierElement
8072          = getFirstElement ( connectionElement, "Multiplier" ),
8073        offsetElement
8074          = getFirstElement ( connectionElement, "Offset" ),
8075        typeElement
8076          = getFirstElement ( connectionElement, "Type" ),
8077        delayElement
8078          = getFirstElement ( connectionElement, "Delay" ),
8079        matrixElement
8080          = getFirstElement ( connectionElement, "Matrix" ),
8081        rotationElement
8082          = getFirstElement ( connectionElement, "Rotation" ),
8083        fromLayerPrefixElement
8084          = getFirstElement ( fromLayerElement, "Prefix" ),
8085        fromLayerSuffixElement
8086          = getFirstElement ( fromLayerElement, "Suffix" ),
8087        toLayerPrefixElement
8088          = getFirstElement ( toLayerElement,   "Prefix" ),
8089        toLayerSuffixElement
8090          = getFirstElement ( toLayerElement,   "Suffix" );
8091      
8092      // accepts periodic argument
8093
8094      layerStructure.popScaffold (
8095        getFirstChildValue ( fromLayerPrefixElement ),
8096        getFirstChildValue ( fromLayerSuffixElement ),
8097        getFirstChildValue ( toLayerPrefixElement ),
8098        getFirstChildValue ( toLayerSuffixElement ),
8099        parseVergenceStyle ( styleElement ),
8100        computeStrength (
8101          strengthElement,
8102          multiplierElement,
8103          offsetElement ),
8104        parseSynapseType ( typeElement ),
8105        Double.parseDouble ( getFirstChildValue ( delayElement ) ),
8106        rotateMatrix (
8107          parseMatrix ( matrixElement ),
8108          rotationElement ),
8109        hostId,
8110        parsePeriodic ( connectionElement ) );
8111    }
8112    
8113    private static int  parseSynapseType ( final Element  typeElement )
8114    ////////////////////////////////////////////////////////////////////////
8115    {
8116      final String
8117        typeValue = typeElement.getFirstChild ( ).getNodeValue ( );
8118
8119      if ( typeValue.equals ( "Glutamate" ) )
8120      {
8121        return 0;
8122      }
8123      
8124      if ( typeValue.equals ( "GABA" ) )
8125      {
8126        return 1;
8127      }
8128      
8129      throw new RuntimeException ( "only Glutamate and GABA are allowed" );
8130    }
8131    
8132    private static boolean  parseVergenceStyle (
8133      final Element  styleElement )
8134    ////////////////////////////////////////////////////////////////////////
8135    {    
8136      final String
8137        styleValue = styleElement.getFirstChild ( ).getNodeValue ( );
8138    
8139      if ( styleValue.equals ( "Convergent" ) )
8140      {
8141        return true;
8142      }
8143      
8144      if ( styleValue.equals ( "Divergent" ) )
8145      {
8146        return false;
8147      }
8148
8149      throw new RuntimeException (
8150        "only convergent and divergent are allowed" );
8151    }
8152    
8153    private static double [ ] [ ]  rotateMatrix (
8154      final double [ ] [ ]  matrix,
8155      final Element         rotationElement )
8156    ////////////////////////////////////////////////////////////////////////
8157    {
8158      double [ ] [ ]  rotatedMatrix = matrix;
8159      
8160      final int  rotation = Integer.parseInt (
8161        rotationElement.getFirstChild ( ).getNodeValue ( ) ) / 90;
8162
8163      if ( rotation > 0 )
8164      {
8165        for ( int  ii = 0; ii < rotation; ii++ )
8166        {
8167          rotatedMatrix = FunUtil.rRotate90 ( rotatedMatrix );
8168        }
8169      }
8170      else if ( rotation < 0 )
8171      {
8172        for ( int  ii = 0; ii < -rotation; ii++ )
8173        {
8174          rotatedMatrix = FunUtil.lRotate90 ( rotatedMatrix );
8175        }
8176      }
8177      
8178      return rotatedMatrix;
8179    }
8180    
8181    private void  populateModulatedSynapseSeq ( )
8182    ////////////////////////////////////////////////////////////////////////
8183    {    
8184      if ( layerStructure == null )
8185      {
8186        // parseMapCells() has not been called
8187        
8188        return;
8189      }
8190      
8191      final Map<Integer, Axon>  neuronIndexToAxonMap = layerStructure.axons;
8192
8193      final Collection<Axon>  values = neuronIndexToAxonMap.values ( );
8194
8195      // LOGGER.trace ( "axon count:  {}", values.size ( ) );
8196
8197      for ( final Axon  axon : values )
8198      {
8199        final Branch [ ]  branches = axon.branches;
8200
8201        // LOGGER.trace ( "branch count:  {}", branches.length );
8202
8203        for ( final Branch  branch : branches )
8204        {
8205          final Synapse [ ]  synapses = branch.synapses;
8206
8207          // LOGGER.trace ( "synapse count:  {}", synapses.length );
8208
8209          for ( final Synapse  synapse : synapses )
8210          {
8211            modulatedSynapseList.add ( ( ModulatedSynapse ) synapse );
8212          }
8213        }
8214      }
8215    }
8216    
8217    private static double  parseDouble (
8218      final String  text,
8219      final double  defaultValue,
8220      final String  errorMessage )
8221      throws NumberFormatException
8222    ////////////////////////////////////////////////////////////////////////
8223    {
8224      if ( text == null )
8225      {
8226        return defaultValue;
8227      }
8228      
8229      final String  trimmedText = text.trim ( );
8230      
8231      if ( trimmedText.equals ( "" ) )
8232      {
8233        return defaultValue;
8234      }
8235      
8236      try
8237      {
8238        return Double.parseDouble ( trimmedText );
8239      }
8240      catch ( NumberFormatException  nfe )
8241      {
8242        LOGGER.error ( errorMessage, nfe );
8243        
8244        throw nfe;
8245      }
8246    }
8247    
8248    private static double[] invertDoubleArray ( double [ ] array)
8249    ////////////////////////////////////////////////////////////////////////
8250    {
8251      double [ ] out = new double [ array.length ];
8252      
8253      for (int i = 0; i < array.length; i++)
8254      {
8255        out [ i ] = 1 / array [ i ];
8256      }
8257      
8258      return out;
8259    }
8260    
8261    ////////////////////////////////////////////////////////////////////////
8262    ////////////////////////////////////////////////////////////////////////
8263    }