#!/usr/bin/env python
'''
Convert glups .trk files into gwinparameters file

Yves Revaz
mer oct 25 10:27:24 CEST 2006
'''


import sys
import string
import os
import types
from optparse import OptionParser

from pylab import *


from numpy import *
#from Nbody import myNumeric
from scipy import interpolate
from Gtools import io


def parse_options():

  usage = "usage: %prog [options] file"
  parser = OptionParser(usage=usage)
  
  parser.add_option("-n",
		   action="store", 
		   dest="Nout",
		   type="int",
		   default = 10,		   
		   help="number of final frames",	 
		   metavar=" INT")    


  parser.add_option("--basename",
		   action="store", 
		   dest="basename",
		   type="string",
		   default = 'newtrack',		   
		   help="image base name",	 
		   metavar=" STRING")    

  parser.add_option("--dirname",
		   action="store", 
		   dest="dirname",
		   type="string",
		   default = 'track',		   
		   help="image directory name",	 
		   metavar=" STRING")   

  parser.add_option("-p",
		   action="store", 
		   dest="parameterfile",
		   type="string",
		   default = None,		   
		   help="""parameter file : allows to force some parameters
		   the file must constains some commands like :
                   forceDic["Points0:Color_a"] = 0.1
		   forceDic["Points1:Color_a"] = 0.1
		   forceDic["Points5:Color_a"] = 0.7
		   """,	 
		   metavar=" FILE")    

  parser.add_option("-s",
		   action="store", 
		   dest="s",
		   type="float",
		   default = 1,		   
		   help="smoothing factor",	 
		   metavar=" FLOAT")   
		   		    		    		    
  (options, args) = parser.parse_args()
        
  if len(args) == 0:
    print "you must specify at least a filename"
    sys.exit(0)
    
  files = args
  
  return files,options

#######################################
# GET OPTIONS
#######################################

# get options
files,options = parse_options()
Nout = options.Nout
basename = options.basename
parameterfile = options.parameterfile
dirname = options.dirname
sfact =  options.s

def myInterpolation(vec,time):
  
  if time==None:
   time = arange(len(vec)).astype(float32)+1
  
  # number of interpoleted points
  xvals = arange(min(time),max(time),(max(time)-min(time))/float(Nout))

  
  # compute interpolation
  #yvals = array([],float)
  #for xval in xvals:    
  #  #y = myNumeric.polint(time.astype(float32),vec.astype(float32),xval)
  #  #y = myNumeric.ratint(time.astype(float32),vec.astype(float32),xval)
  #  
  #  y2a = myNumeric.spline(time.astype(float32),vec.astype(float32),0,0)
  #  y = myNumeric.splint(time.astype(float32),vec.astype(float32),y2a,xval)
  #  
  #  yvals =  concatenate((yvals,y))
  
  
  n=len(time)
  s1 = n-sqrt(2*n)
  s2 = n+sqrt(2*n)
  s = s1*sfact
  
  tck   = interpolate.fitpack.splrep(time,vec,s=s,k=2)
  yvals = interpolate.fitpack.splev(xvals,tck)
  
  
  
    
  return yvals




# force some values
forceDic = {}
forceDic["Mainwindow:ShowInfo"] = 0
forceDic["Mainwindow:ShowHelp"] = 0
forceDic["Mainwindow:ShowHelp"] = 0
forceDic["Track:show"]          = 0
forceDic["Mainwindow:DisplayMode"] = 2

if parameterfile!=None:
  execfile(parameterfile)

#forceDic["Points0:Color_a"]          = 0.1
#forceDic["Points1:Color_a"]          = 0.1
#forceDic["Points5:Color_a"]          = 0.7


################################################
# read first file and create main dic
################################################
mainDic = io.read_tracks(files)

  

################################################
# interpolate
################################################


newDic = {}
  
for key in mainDic.keys():  

  if type(mainDic[key]) == types.ListType: 
  
    # if there is a default value
    if forceDic.has_key(key):
      newDic[key] = []
      for i in range(Nout):
        newDic[key].append(forceDic[key])     
    else:
      newDic[key] = mainDic[key]




    
  else:  
    
    # if there is a default value
    if forceDic.has_key(key):
      newDic[key] = ones(Nout)*forceDic[key] 
    
    else:  
      # if they are all identical, do not interpolate
      if sum((mainDic[key][0] == mainDic[key]).astype(int))==len(mainDic[key]):
        newDic[key] = ones(Nout)*mainDic[key][0]
      else:
        newDic[key] = myInterpolation(mainDic[key],time=None)
    
       
  
  
  
  
################################################  
# write output
################################################

if not os.path.isdir(dirname):
   os.mkdir(dirname)



for n in range(Nout):

  file = "%s%06d.trk"%(basename,n)
  file = os.path.join(dirname,file)
  


  f = open(file,'w') 
  
  for key in newDic.keys():
    
    if type(newDic[key]) == types.ListType:
      line = "%s = %s\n"%(key,newDic[key][0])
    else:
      line = "%s = %f\n"%(key,newDic[key][n])
    
    f.write(line)
   
    
  f.close()




