#!/bin/sh  
# \
exec oagwish "$0" "$@"

set auto_path [linsert $auto_path 0  /usr/local/oag/apps/lib/$env(HOST_ARCH)]
set auto_path [linsert $auto_path 0 /usr/local/oag/lib_patch/$env(HOST_ARCH)]
APSDebugPath

APSApplication . -name takeLifetimeData -version 1.0 

set status Ready.
APSScrolledStatus .status -parent .userFrame -textVariable status -width 80 -height 4
update

set minCurrentChange 0.2
set maxCurrentChange 1
set maxTime 300
set minTime 10
set timeInterval 0.5
set takeTunes 0
set takeOrbit 1
set takeBunchPattern 1
set takeSRVSA 0
set rootname ""
set comment ""

APSFrame .parameters -parent .userFrame -label "Experiment parameters" \
    -packOption "-fill both"
set w .userFrame.parameters.frame
APSLabeledEntry .le1 -parent $w -label "Minimum current change (mA)" \
  -textVariable minCurrentChange  -width 10 -contextHelp \
  "If the current changes by more than this minimum amount and if the minimum data collection time has elapsed, then data collection for the present set is terminated.  Represents how much of a current change you'd like to have in order to get an accurate lifetime value."
APSLabeledEntry .le2 -parent $w -label "Maximum current change (mA)" \
  -textVariable maxCurrentChange  -width 10 -contextHelp \
  "If the current changes by more than this amount, then present set is terminated.  Use this to present excessive current loss for short lifetime."
APSLabeledEntry .le3 -parent $w -label "Minimum data collection time (s)" \
  -textVariable minTime -width 10 -contextHelp \
  "The minimum time for which data will be collected for each set, unless the maximum current loss is seen."
APSLabeledEntry .le4 -parent $w -label "Maximum data collection time (s)" \
  -textVariable maxTime -width 10 -contextHelp \
  "The maximum time for which data will be collected for each set, regardless of whether the minimum current loss has occured."
APSLabeledEntry .le6 -parent $w -label "Experiment description" \
  -textVariable comment -width 70 -contextHelp \
  "Enter a text description of the experiment."
APSCheckButtonFrame .cb1 -parent $w -label "Additional data to include " \
  -orientation horizontal -variableList {takeTunes takeOrbit takeBunchPattern} \
  -buttonList {"Tune spectrum" "Orbit snapshot" "Bunch pattern"} \
   -allNone 1  -limitPerRow 4 -contextHelp \
  "Choose additional data that you'd like to have collected.  If none are selected, only the time-series file is produced with current, lifetime, and vacuum pressure."

set setsInSeries 1
set timeBetweenSets 60
set plotData 1
set PVToVary ""
set PVToVaryStart 0
set PVToVaryEnd 0
set geometricVariation 0
set postChangePause 0
APSFrame .series -parent .userFrame -label "Series data collection" \
    -packOption "-fill both"
set w .userFrame.series.frame
APSLabeledEntry .le7 -parent $w -label "Sets in series" \
  -textVariable setsInSeries -width 10 -contextHelp \
  "Enter the number of data sets to take when the \"Take series\" button is pressed.  You can always add to the series later by keeping the same rootname."
APSLabeledEntry .lev1 -parent $w -label "PV to vary" \
    -textVariable PVToVary -width 32 -contextHelp \
    "Enter the name of a PV to vary between sets.  If blank, no PV is varied."
APSRadioButtonFrame .levrb1 -parent $w -label "Preset PV choices" \
    -variable PVToVary -orientation horizontal \
    -buttonList {S37-WBD S38-WBD S39-WBD S40-WBD S01-WBD RfVoltage RfVoltageS36S37 Clear} \
    -valueList {S37A:HCOLL1:Mtr S38A:HCOLL1:Mtr S39A:HCOLL1:Mtr S40A:HCOLL1:Mtr S01A:HCOLL1:Mtr RfVoltage RfVoltageS36S37 ""} \
    -contextHelp "Use to choose one of the preset PVs to vary.  Choice is determined by contents of the entry box. Choose \"Clear\" if you want to enter a custom PV."
APSLabeledEntry .lev2 -parent $w -label "Starting value" -textVariable PVToVaryStart -width 10 
APSLabeledEntry .lev3 -parent $w -label "Final value" -textVariable PVToVaryEnd -width 10
APSRadioButtonFrame .rbg -parent $w -label "Geometric variation?" -orientation horizontal \
                    -buttonList "Yes No" -valueList "1 0" -variable geometricVariation
APSLabeledEntry .lev4 -parent $w -label "Post change pause (s)" -textVariable postChangePause -width 10 
APSLabeledEntry .le8 -parent $w -label "Time between sets (s)" -textVariable timeBetweenSets -width 10 -contextHelp \
  "Amount of time to pause between each data set in the series."
APSRadioButtonFrame .rb1 -parent $w -label "Plot results" -buttonList {Yes No} -valueList {1 0} -variable plotData \
  -orientation horizontal -contextHelp "Select whether to plot results as each data set is taken."
APSLabeledEntry .le5 -parent $w -label "File rootname" -textVariable rootname -width 60 -contextHelp \
  "Rootname for the output files.  The filenames are of the form <rootname>.<ddd>.*, where ddd is a three-digit integer starting at 000.  A new index is automatically chosen for each data set to avoid overwriting existing files."

APSButton .b0 -parent $w -text "Go to daily directory" -contextHelp \
    "Sets the directory part of the file rootname to point to the daily directory." \
    -command {set rtail [file tail $rootname]; set rootname [APSGoToDailyDirectory]$rtail}

set buttonWidget $w.b1.button
APSButton .b1 -parent $w -text "Take series" -contextHelp \
  "Initiates data collection for the number of data sets given above." \
  -command \
  {set abort 0;
      APSSRTakeLifetimeDataSeries -buttonWidget $buttonWidget \
      -PVToVary $PVToVary -PVToVaryStart $PVToVaryStart \
      -PVToVaryEnd $PVToVaryEnd -postChangePause $postChangePause \
      -geometricVariation $geometricVariation \
     -minCurrentChange $minCurrentChange -maxCurrentChange $maxCurrentChange \
     -minTime $minTime -maxTime $maxTime \
     -rootname $rootname -comment $comment -takeSRVSA $takeSRVSA \
     -takeTunes $takeTunes -takeOrbit $takeOrbit -takeBunchPattern $takeBunchPattern \
     -sets $setsInSeries -timeBetweenSets $timeBetweenSets \
     -plot $plotData \
     -abortVariable abort -statusCallback "APSSetVarAndUpdate status" \
 }
APSButton .b2 -parent $w -text "Abort" \
  -command "set abort 1" -contextHelp \
  "Aborts data collection.  The present data set will be imcomplete."

APSFrame .postproc -parent .userFrame -label "Post-processing" -packOption "-fill both"
set w .userFrame.postproc.frame

APSButton .b3 -parent $w -text "Process Sets" \
  -command {ProcessSeries -rootname $rootname -PVToVary $PVToVary} -contextHelp \
  "Processes all the data sets for the rootname given above.  Processing consists of fitting the current data to get the lifetime."
APSButton .b4 -parent $w -text "Plot Sets" \
    -command {PlotSeries -rootname $rootname}
APSFrame .pf -parent $w -label "" 
set plSeriesAveCur 1
set plSeriesBunCur 1
set plSeriesSeqNum 0
set plSeries38SCPos 0
set plSeries37SCPos 0
set plSeries39SCPos 0
set plSeries40SCPos 0
set plSeries01SCPos 0
APSButton .b5 -parent $w.pf.frame -text "Plot Fits" \
  -command {PlotSeries -rootname $rootname -fitsOnly 1 \
          -averageCurrent $plSeriesAveCur -bunchCurrent $plSeriesBunCur \
          -sequenceNumber $plSeriesSeqNum \
          -S37WBDump $plSeries37SCPos -S38WBDump $plSeries38SCPos -S39WBDump $plSeries39SCPos \
          -S40WBDump $plSeries40SCPos -S01WBDump $plSeries01SCPos \
          -userPV $PVToVary}
APSCheckButtonFrame .cb1 -parent $w.pf.frame -label "plot vs: " \
    -orientation horizontal -buttonList \
    {"Average current" "Bunch current" "Sequence number" \
                       "S37 WBD jaw" "S38 WBD jaw" "S39 WBD jaw" "S40 WBD jaw" "S01 WBD jaw" } \
    -variableList {plSeriesAveCur plSeriesBunCur plSeriesSeqNum plSeries37SCPos plSeries38SCPos \
                                  plSeries39SCPos plSeries40SCPos plSeries01SCPos} \
    -allNone 1 -limitPerRow 3 -contextHelp \
    "Choose the parameters against which to plot lifetime."

proc PlotSeries {args} {
    set rootname ""
    set fitsOnly 0
    set averageCurrent 0
    set bunchCurrent 0 
    set sequenceNumber 0
    set S37WBDump 0
    set S38WBDump 0
    set S39WBDump 0
    set S40WBDump 0
    set S01WBDump 0
    set userPV ""
    APSStrictParseArguments {rootname fitsOnly averageCurrent bunchCurrent sequenceNumber \
                           S37WBDump S38WBDump S39WBDump S40WBDump S01WBDump userPV}

    set fileList [lsort [glob -nocomplain $rootname.*.ltfit]]
    if ![llength $fileList] {
        return -code error "PlotSeries: no files found."
    }
    if [catch {eval exec sddscombine $fileList -pipe=out -collapse \
                 | sddsprocess -pipe -define=column,SequenceNumber,i_row,type=long \
                 | sddssort -pipe=in -column=SDCCTMean,incr $rootname.all} result] {
        return -code error "PlotSeries: $result"
    }
    eval exec sddsplot -groupby=fileindex -sep=fileindex \
        -column=TimeElapsed,lnSDCCT -graph=dot $fileList -topline=@LifetimeLabel \
        -title=@Comment \
        -column=TimeElapsed,lnSDCCTFit -graph=line,type=1 $fileList &
    
    set plotArgs ""
    set haveUserPV 0
    if [string length $userPV] {
        set haveUserPV 1
    }
    set columnList ""
    foreach item {averageCurrent bunchCurrent sequenceNumber S37WBDump S38WBDump S39WBDump S40WBDump S01WBDump haveUserPV} {
        if ![set $item] continue
        switch $item {
            averageCurrent { lappend columnList SDCCTMean }
            bunchCurrent   { lappend columnList BunchCurrentMean }
            sequenceNumber { lappend columnList SequenceNumber }
            S37WBDump    { lappend columnList S37HCollimatorPositionMean }
            S38WBDump    { lappend columnList S38HCollimatorPositionMean }
            S39WBDump    { lappend columnList S39HCollimatorPositionMean }
            S40WBDump    { lappend columnList S40HCollimatorPositionMean }
            S01WBDump    { lappend columnList S01HCollimatorPositionMean }
            haveUserPV     { lappend columnList $userPV}
        }
    }
    foreach column $columnList {
        lappend plotArgs -column=$column,Rate,RateSigma 
        lappend plotArgs -graph=error
        lappend plotArgs $rootname.all 
        lappend plotArgs -pointLabel=Filename,edit=Z.%/.ltfit//,scale=0.5
        if [catch {exec sddspfit -column=$column,Rate,ysigma=RateSigma  \
                       -terms=2 $rootname.all $rootname.all.fit.$column} result] {
            lappend plotArgs -end 
            continue
        }
        lappend plotArgs -column=$column,RateFit 
        lappend plotArgs $rootname.all.fit.$column 
        lappend plotArgs -graph=line,type=1
        lappend plotArgs -topline=@sddspfitLabel
        lappend plotArgs -end 
    }
    if [llength $plotArgs] {
        eval exec sddsplot  $plotArgs &
    }
    if !$fitsOnly {
        eval exec sddsplot -same=y,global -column=Bucket,BunchCurrent \
            [glob -nocomplain $rootname.*.bpat] -filename -sep &
        eval exec sddsplot -same=y,global -column=Frequency,Waveform -mode=y=log,y=special \
            [glob -nocomplain $rootname.*.vsa] -filename -sep &
    }
}

proc ProcessSeries {args} {
    set rootname ""
    set PVToVary "" 
    APSStrictParseArguments {rootname PVToVary}

    set fileList [lsort [glob -nocomplain $rootname.*.monData $rootname.*.monData.gz]]
    if ![llength $fileList] {
        return -code error "ProcessSeries: no files found."
    }
    foreach filename $fileList {
        set rootname [file root [APSRemoveGzipExtension $filename]]
        APSSRProcessLifetimeData -input $filename  -PVToVary $PVToVary -output $rootname.ltfit
    }
}

set comment ""
update
