text: #!/usr/bin/python
  #
  #   HRLAnalysis(TM) Software License - Version 1.0 - August 27th, 2013
  #
  #   Permission is hereby granted, free of charge, to any person or 
  #   organization obtaining a copy of the software and accompanying 
  #   documentation covered by this license (the "Software") to use, 
  #   reproduce, display, distribute, execute, and transmit the 
  #   Software, and to prepare derivative works of the Software, and 
  #   to permit third-parties to whom the Software is furnished to do 
  #   so, all subject to the following:
  #
  #   The copyright notices in the Software and this entire statement, 
  #   including the above license grant, this restriction and the 
  #   following disclaimer, must be included in all copies of the 
  #   Software, in whole or in part, and all derivative works of the 
  #   Software, unless such copies or derivative works are solely in 
  #   the form of machine-executable object code generated by a source 
  #   language processor.
  #
  #   THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 
  #   EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES 
  #   OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, TITLE AND 
  #   NON-INFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS OR 
  #   ANYONE DISTRIBUTING THE SOFTWARE BE LIABLE FOR ANY DAMAGES OR 
  #   OTHER LIABILITY, WHETHER IN CONTRACT, TORT OR OTHERWISE, ARISING 
  #   FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR 
  #   OTHER DEALINGS IN THE SOFTWARE, INCLUDING BUT NOT LIMITED TO THE 
  #   COMPATIBILITY OF THIS LICENSE WITH OTHER SOFTWARE LICENSES.
  #
  import sys
  import os
  import re
  import argparse
  
  
  def uniqueFilename(path,filename,extension):
  
      fileName = os.path.join(path,filename+extension)
      if( os.path.exists(fileName)):
          createFileName = lambda i: os.path.join(
                                          path,"%s_%d%s"% (filename,i,extension))
          for i in xrange(1, sys.maxint):
              fileName = createFileName(i)
              if not os.path.exists(fileName):
                  return fileName
      else:
          return fileName
  
      return None
  
  
  def analyzeData(cellGroup,options,binFiles):
  
      fileList = libHrlAnalysis.vector_string()
      for f in binFiles:
          fileList.append(f)
      analysis = libHrlAnalysis.HrlNeuralAnalysisHRLSim(
                              options.startTime,options.endTime,
                              cellGroup['startIdx'],cellGroup['endIdx'],
                              fileList)
      analysis.buildDataStructures()
      # Get the Raster Data.
      rasterInfo = analysis.getSpikeTimes()
      # Get the Cell Rates.
      if options.windowRateType == "binned":
          rateInfo = analysis.getWindowRate(options.StepSize,options.WindowSize)
      else:
          rateInfo = analysis.getGaussWindowRate(options.StepSize,
                                                 options.WindowSize)
      # Get the Window Rates and the Binned Rates
      cellRateBinInfo = analysis.getRatesWithBins(100)
      # Get the COV analysis.
      covInfo = analysis.getCOV()
  
      # Plot the results
      if options.plotType == "detailed":
          import hrlAnalysisPlt
          plotter = hrlAnalysisPlt.spikePlotter(
                                  cellGroup['name'],
                                  options.startTime,options.endTime,
                                  cellGroup['startIdx'],cellGroup['endIdx'])
          plotter.plotRaster(rasterInfo.time,rasterInfo.spikes)
          plotter.plotWindowRate(rateInfo.rates)
          if len(covInfo.cov) > 0:
              plotter.plotCOV(covInfo.cells,covInfo.cov)
  
          plotter.plotCellRates(cellRateBinInfo.cells,cellRateBinInfo.rates)
          plotter.plotSpikeBins(cellRateBinInfo.freqs,cellRateBinInfo.counts)
  
          plotter.savePlot(os.path.join(options.outputPath,
                                        cellGroup['name']+'.png'))
          plotter.closePlot()
  
      elif options.plotType == "display":
          import hrlAnalysisPlt_display
          plotter = hrlAnalysisPlt_display.spikePlotter_display(
                                      cellGroup['name'],
                                      options.startTime,options.endTime,
                                      cellGroup['startIdx'],cellGroup['endIdx'])
          plotter.plotRaster(rasterInfo.time,rasterInfo.spikes)
          plotter.plotWindowRate(rateInfo.rates)
          if len(covInfo.cov) > 0:
              plotter.plotCOV(covInfo.cells,covInfo.cov)
  
          plotter.plotCellRates(cellRateBinInfo.cells,cellRateBinInfo.rates)
          plotter.plotSpikeBins(cellRateBinInfo.freqs,cellRateBinInfo.counts)
  
          plotter.show()
  
      else:
          import hrlAnalysisPlt_biggles
          plotter = hrlAnalysisPlt_biggles.spikePlotterBiggles(
                                      cellGroup['name'],
                                      options.startTime,options.endTime,
                                      cellGroup['startIdx'],cellGroup['endIdx'])
          savePlot = False
          if len(rasterInfo.spikes) > 0:
              plotter.plotRaster(rasterInfo.time,rasterInfo.spikes)
              plotter.plotWindowRate(rateInfo.rates)
              savePlot = True
  
          if len(covInfo.cov) > 0:
              plotter.plotCOV(covInfo.cells,covInfo.cov)
              savePlot = True
  
          if savePlot:
              try:
                  plotter.savePlot(os.path.join(options.outputPath,
                                                cellGroup['name']+'.png'))
              except:
                  print "Error saving: %s.png" % (cellGroup['name'])
                  pass
          else:
              print "There were no spikes so a plot was not created for group: %s!" %(cellGroup['name'])
  
  
  def getParser():
  
      parser = argparse.ArgumentParser(
                          description='Analyze HRLSimulator results.')
  
      parser.add_argument('startTime', metavar='T_start', type=int,
                          help='the time, in ms, to start the analysis.')
  
      parser.add_argument('endTime', metavar='T_end', type=int,
                          help='the time, in ms, to stop the analysis.')
  
      config_group = parser.add_argument_group('configuration')
  
      config_group.add_argument(
                      "-o", "--outputPath", dest="outputPath",
                      action="store",default="../results/",
                      help="Output path to store the plots.", metavar="PATH")
  
      config_group.add_argument(
                      "-c", "--config", dest="configFileName",
                      action="store",default="../../test/python/analysisConfig",
                      help="Configuration file to import", metavar="FILE")
  
      config_group.add_argument(
                      "-i", "--includepath", dest="includePath",
                      action="store",default="../lib/",
                      help="Path to the hrlAnalysis libraries.", metavar="PATH")
  
      config_group.add_argument(
                      "-a", "--searchpath", dest="searchPath",
                      action="store",default="../../test/data/CA1/",
                      help="The directory to search for binary files.", 
                      metavar="PATH")
  
      config_group.add_argument(
                      "--rateType", dest="windowRateType",
                      action="store",default="guassian",
                      help="The type of analysis to use when calculating the mean spike rate: options are guassian: uses a Guassian weighting function (default).  binned: uses a nonoverlapping moving window", 
                      metavar="TYPE")
  
      config_group.add_argument(
                      "-w", "--windowsize", dest="WindowSize",
                      action="store",type=int,default=100,
                      help="window size in ms to use for mean spike rate analysis.", 
                      metavar="VAL")
  
      config_group.add_argument(
                      "-s", "--stepsize", dest="StepSize",
                      action="store",type=int,default=50,
                      help="size in ms to move the mean reate analysis window.", 
                      metavar="VAL")
  
      plot_group = parser.add_argument_group('plotting')
  
      plot_group.add_argument(
                      "-p", "--plotType", dest="plotType",
                      action="store",default="minimal",
                      help="The type of plot to output: options for type are minimal: uses the biggles plot library (Faster).  detailed: uses the matplotlib library.", 
                      metavar="TYPE")
  
      plot_group.add_argument(
                      "--nocov", dest="calcCOV",
                      action="store_false",default=True,
                      help="Do not calculate the COV. (not used)")
  
      plot_group.add_argument(
                      "--nocellrates", dest="calcCellRates",
                      action="store_false",default=True,
                      help="Do not calculate the Cell Rates. (not used)")
  
      plot_group.add_argument(
                      "--nobins", dest="calcBins",
                      action="store_false",default=True,
                      help="Do not bin the Cell Rates. (not used)")
  
      plot_group.add_argument(
                      "--nowindowrate", dest="calcWindowRate",
                      action="store_false",default=True,
                      help="Do not calculate the mean cell rate. (not used)")
  
      plot_group.add_argument(
                      "--noraster", dest="calcRaster",
                      action="store_false",default=True,
                      help="Do not calculate the cell raster. (not used)")
  
      plot_group.add_argument(
                      "--plot", dest="CreatePlot",
                      action="store_true",default=False,
                      help="Create the plot of the data. (not used)")
  
      plot_group.add_argument(
                      "--notable", dest="outputTable",
                      action="store_false",default=True,
                      help="Do not create the output table.  This assumes that a plot is desired instead. (not used)")
  
      return parser
  
  
  if __name__ == '__main__':
  
      # Parse the command line.
      parser = getParser()
      options = parser.parse_args()
  
      # Add the library include path
      sys.path.append(options.includePath)
      # import the analysis library
      import libHrlAnalysis
  
      # Import the configuration module.
      (directory,fileName) = os.path.split(options.configFileName)
      sys.path.append(directory)
      try:
          exec('from %s import *' % fileName)
      except:
          print "Error: Cannot find the requested configuration file: ",fileName
          raise
  
      # Search for binary files in the search path.
      binFiles = os.listdir(options.searchPath)
      #filterTest = re.compile("spikes\.bin$",re.IGNORECASE)
      filterTest = re.compile("^spikes",re.IGNORECASE)
      binFiles = filter(filterTest.search,binFiles)
  
      for i in xrange(len(binFiles)):
          binFiles[i] = os.path.join(options.searchPath,binFiles[i])
  
      # Sort the list of files since some machines will return the files 
      # in reverse order
      binFiles.sort()
  
      # Get the cell groups and the parameters
      cellGroups = getCellGroups()
  
      for cells in cellGroups:
          analyzeData(cells,options,binFiles)
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
  
          
  
  