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

# $Log: not supported by cvs2svn $
# Revision 1.8  2005/02/16 14:05:30  emery
# Change data directory to logging
#
# Revision 1.7  2004/10/01 18:43:46  emery
# Added a plot with -arrow option which gives a 2D map of the search
# with symbol size proportional to the optimization function value.
#
# Revision 1.6  2004/08/02 21:50:28  emery
# Added filtering of monopulse bpms for special monitor file.
#
# Revision 1.5  2004/01/23 15:43:11  borland
# Added "include IS" option to include IS1 and IS2 in the optimization.
# Also increased the test out-of-range count limit from 3 to 100.
#
# Revision 1.4  2002/10/15 04:38:42  emery
# Added save button for pulsedPS
#
# Revision 1.3  2002/06/11 02:40:24  emery
# Added -leg to sddsplot
#
# Revision 1.2  2002/04/17 08:19:42  emery
# Corrected a few typos.
#
# Revision 1.1  2002/04/17 03:32:24  emery
# Premiere installation.
#

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)]
APSStandardSetup
set CVSRevisionAuthor "\$Revision: 1.9 $ \$Author: emery $"

APSApplication . -name "SROnAxis" -version $CVSRevisionAuthor \
  -overview "SROnAxis adjusts the kickers for an on-axis injection condition. The first turn trajectory must be setup before running this optimizer. The IK3 and IK4 are minimized for a given BTS trajectory condition. IK1 and IK2 and septums are not adjusted."

proc MakeActionWidget {widget args} {
    set parent ""
    APSParseArguments {parent}
    
    APSFrame $widget -parent $parent -label "" \
      -contextHelp "Control widgets"
    set w $parent$widget.frame

    APSFrame .setup -parent $parent$widget.frame -label "" \
      -contextHelp "Setup quantities"
    set w $parent$widget.frame.setup.frame

    APSLabeledEntry .logDir -parent $w -width 60 \
      -textVariable logDir \
      -label "Log directory:" \
      -contextHelp "Directory for log file of minimization."

   APSButton .daily -parent $w.logDir -packOption "-anchor e" \
      -text "daily" -size small \
      -command {set logDir [APSGoToDailyDirectory -subDirectory .]}

    APSLabeledEntry .measFile -parent $w -width 60 \
      -textVariable measFile \
      -label "Measurement file for bpm rms:" \
      -contextHelp "Measurement file that will be created for the set of :ms:x:ErrorCC from the selected sectors. This file will be written to the log directory."

    APSLabeledEntry .ave -parent $w \
      -label "BPM averager weight:" -textVariable averagerWeight \
      -contextHelp "Enter a value for the BPM memory/scanner averager weight (S:bpm:memscan_wt_ao.VAL)"

    APSLabeledEntry .bpm -parent $w \
      -label "BPM sector range for rms (i.e. 10,20):" -textVariable sectors \
      -contextHelp "Enter a range of sectors of bpms whose rms errors will be minimized."

    APSLabeledEntry .saveFile -parent $w \
      -label "Save snap file:" -textVariable saveFile \
      -contextHelp "Enter a snapshot file name for the pulsed power supply setpoints to be written in the directory above"

    APSRadioButtonFrame .includeIS -parent $w -label "Include IS?" \
      -variable includeIS \
      -orientation horizontal -buttonList "Yes No" -valueList "1 0" \
      -commandList {"set scriptDir /home/helios/oagData/sr/optimizeScripts/onaxisWithIS" \
                      "set scriptDir /home/helios/oagData/sr/optimizeScripts/onaxis"} \
      -contextHelp "Include IS1 and IS2 in the optimization?  If No, then only IK3 and IK4 are used."

    APSFrame .optimize -parent $parent$widget.frame -label "" \
      -contextHelp "Optimize frame"
    set w $parent$widget.frame.optimize.frame

    APSButton .setup  -parent $w -text "Setup averaging and bpm file" \
      -command {Setup -logDir $logDir -averagerWeight $averagerWeight -sectors $sectors} \
      -contextHelp "Sets up bpm averaging and creates a bpm file before starting the minimizing the first turn trajectory."

    APSButton .save  -parent $w -text "Save PulsedPS" \
      -command {SavePulsed -logDir $logDir -saveFile $saveFile} \
      -contextHelp "Saves pulsed magnets setpoints to file above."

    APSButton .minimize  -parent $w -text "Optimize on-axis trajectory" \
      -command {runOptimize -logDir $logDir \
                  -averagerWeight $averagerWeight -measFile $measFile \
                  -includeIS $includeIS} \
      -contextHelp "Starts sddsoptimize for on axis injection."

    APSButton .plotProg  -parent $w -text "Plot Progress" \
      -command {plotProgress -logDir $logDir} \
      -contextHelp "Plots the knob values and emittance."

}

proc SavePulsed {args} {
    global scriptDir
    set logDir .
    set saveFile ""
    APSParseArguments {logDir saveFile}
    if [file exists $logDir/$saveFile] {
        return -code error "File $logDir/$saveFile already exists!"
    }
    exec burtrb -f $scriptDir/pulsedPS.req -o $logDir/$saveFile
    SetStatus "File $logDir/$saveFile written."
    return
}

proc plotProgress {args} {
    set logDir .
    APSParseArguments {logDir}
    exec sddsplot $logDir/onAxis.optLog \
      -col=EvalIndex,(S:IK3:VoltageSetSendAO,S:IK4:VoltageSetSendAO) \
      -grap=line,vary -alignzero=yfactor -leg \
      -col=EvalIndex,currentValue  \
      -grap=line,vary -alignzero=yfactor -leg \
      -yscale=id=eval -uns=y \
      -end \
      -col=S:IK3:VoltageSetSendAO,S:IK4:VoltageSetSendAO \
      -grap=sym,thick=10,vary=subtype -split=column=currentValue,width=0.1 \
      -order=spectral \
      &
}

proc SetStatus {text} {
    global status
    set status $text
}

proc Setup {args} {
    set averagerWeight 2
    set sectors ""
    set logDir .
    APSParseArguments {logDir averagerWeight sectors}

    if [catch {exec cavput -list=S:bpm:memscan_wt_ao.VAL=$averagerWeight \
                 -pen=5 \
             } result ] {
        return -code error "Setup: $result"
    }
    if ![regexp , $sectors] {
        return -code error "Setup: Bad synatx for sectors: $sectors"
    }

    set file /home/helios/oagData/logging/srBPMs/srBPMs.mon
    SetStatus "Creating file ${logDir}/srBPMs.special.mon..."
    # should filter on monopulse bpms.
    if [catch {exec sddsprocess $file -pipe=out \
                 -match=col,ControlName=S*\[AB\]:P?:ms:x:ErrorCC \
                 -edit=col,DeviceName,ControlName,2S/:/K \
                 -scan=col,Sector,ControlName,S%ld,type=long \
                 -filter=col,Sector,$sectors \
                 | sddsxref -pipe /home/helios/oagData/sr/BPMStatus/config.sdds \
                 -match=DeviceName -take=ElectronicsType \
                 | sddsprocess -pipe \
                 -match=col,ElectronicsType=Monopulse \
                 | sddsconvert -pipe=in ${logDir}/srBPMs.special.mon \
                 -retain=col,ControlName \
             } result ] {
        return -code error "Setup: $result"
    }
    
    SetStatus "Setup done."
}

proc runOptimize {args} {
    global scriptDir
    set logDir .
    set measFile ""
    set averagerWeight 2
    APSParseArguments {logDir averagerWeight measFile}

    if ![llength $measFile] {
        return -code error "runOptimize: Measurement file not specified."
    }
    if ![file exists $logDir/$measFile] {
        return -code error "runOptimize: Measurement file $logDir/$measFile doesn't exist."
    }

    set tmpfile /tmp/[APSTmpString]
    set pause [expr pow(2,$averagerWeight) + 2]
    if [catch {exec sddsprocess $scriptDir/var $tmpfile.var \
                 -redef=para,pauseAfterChange,$pause \
             } result ] {
        return -code error $result
    }
    APSExecLog .onAxis \
      -lineLimit 2048 -width 90 \
      -name "SR on axis injection optimization" \
      -unixCommand "sddsoptimize -measFile=$logDir/$measFile \
            -varFile=$tmpfile.var  -tolerance=0.2 \
            -simplex=restarts=1,cycles=1,evaluations=50 \
            -testValues=file=$scriptDir/tests,limit=100 \
            -target=0.0 -verbose \
            -logFile=$logDir/onAxis.optLog"
}

set averagerWeight 3
set sectors 1,20
set logDir .
set measFile srBPMs.special.mon
set saveFile onaxis.snp
set scriptDir /home/helios/oagData/sr/optimizeScripts/onaxis
set includeIS 0    

set status "Working."
APSScrolledStatus .status -parent .userFrame -textVariable status -width 90
MakeActionWidget .action -parent .userFrame
set status "Ready."
