#!/usr/bin/env python
# *-----------------------------------------------------------------------*
# |                                                                       |
# |  Copyright (c) 2016 by Paul Scherrer Institute (http://www.psi.ch)    |
# |                                                                       |
# |              Author Thierry Zamofing (thierry.zamofing@psi.ch)        |
# *-----------------------------------------------------------------------*

#Testing the interferometer 
'''
zamofing_t@ganymede:~/Documents/prj/SwissFEL/epics_ioc_modules/ESB_MX/cfg$ gpasciiCommander --host $PPMAC -i
$$$***
!common()
!mx-stage()

Gather.Enable=0
Gather.Items=6
Gather.MaxSamples=1000000
Gather.Period=10
Gather.Addr[0]=Motor[2].DesPos.a
Gather.Addr[1]=Motor[3].DesPos.a
Gather.Addr[2]=Motor[2].ActPos.a
Gather.Addr[3]=Motor[3].ActPos.a
Gather.Addr[4]=Motor[4].ActPos.a
Gather.Addr[5]=Motor[5].ActPos.a
open prog 2
  linear abs
  X1000 Y1000
  dwell 10
  Gather.Enable=2
  X28000 Y1000
  dwell 100
  X1000 Y1000
  dwell 100
  X1000 Y28000
  dwell 100
  X1000 Y1000
  dwell 1000
Gather.Enable=0
close
&1
b2r

download data with
PPMAC=SAR-CPPM-EXPMX1
PBGatherPlot -m24 -v7 --host $PPMAC --dat gather.txt

cat /tmp/gather.txt

Motor[2].MaxSpeed=20;Motor[3].MaxSpeed=20
Motor[2].MaxSpeed=5;Motor[3].MaxSpeed=5
Motor[2].MaxSpeed=2
Motor[3].MaxSpeed=2
b2r



'''

import os, sys, json
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import subprocess as sprc
import telnetlib

if __name__=='__main__':
  def plot_gather(base):
    #rec=Motor[1].ActPos,Motor[2].ActPos,Motor[3].ActPos,Motor[1].DesPos,Motor[2].DesPos,Motor[3].DesPos
    #res=rot.ActPos,y.ActPos,x.ActPos,rot.DesPos,y.DesPos,x.DesPos
    #idx     0        1        2          3        4        5
    f1=plt.figure()
    #f2 = plt.figure()
    ax1 = f1.add_subplot(1,1,1)
    #ax2 = f2.add_subplot(1, 1, 1)

    for fn in sorted(os.listdir(base)):
      print fn
      rec = np.genfromtxt(base+'/'+fn, delimiter=' ')
      print rec.shape

      x=range(len(rec[:,0]))
      #hl=ax[0].plot(x, y, color=col)

      hl=ax1.plot(x,-(rec[:,0]-rec[0,0]),'k')
      hl=ax1.plot(x,-(rec[:,2]-rec[0,2]),'r')
      hl=ax1.plot(x,-(rec[:,4]-rec[0,4])/100,'m')
      hl=ax1.plot(x,rec[:,1]-rec[0,1],'k')
      hl=ax1.plot(x,rec[:,3]-rec[0,3],'b')
      hl=ax1.plot(x,-(rec[:,5]-rec[0,5])/100,'c')

    plt.show()

#plot_gather(base='/home/zamofing_t/Documents/prj/SwissFEL/epics_ioc_modules/ESB_MX/gather5/')
#plot_gather(base='/home/zamofing_t/Documents/prj/SwissFEL/epics_ioc_modules/ESB_MX/gather50/')
#plot_gather(base='/home/zamofing_t/Documents/prj/SwissFEL/epics_ioc_modules/ESB_MX/python/tmp/')
#plot_gather(base='/home/zamofing_t/Documents/prj/SwissFEL/epics_ioc_modules/ESB_MX/data_interfero_spd10')
#plot_gather(base='/home/zamofing_t/Documents/prj/SwissFEL/epics_ioc_modules/ESB_MX/data_interfero_spd20')
plot_gather(base='data_interfero_spd10')
