# $Log: not supported by cvs2svn $
# Revision 1.8  2011/08/16 23:19:52  soliday
# Got my math backwards.
#
# Revision 1.7  2011/08/16 23:02:01  soliday
# Fixed a bug in APSMpSRSlowBeamDumpFreqRestore. Also changed the
# calculation of the pause step to pause = pause * current / 100
#
# Revision 1.6  2011/08/16 22:24:50  soliday
# Fixed a few things while testing.
#
# Revision 1.5  2011/08/16 21:58:01  soliday
# Fixed a bug.
#
# Revision 1.4  2011/08/16 21:46:16  soliday
# Added an initial dialog to the APSMpSRSlowBeamDumpFreqRestore routine.
#
# Revision 1.3  2011/08/16 21:39:41  soliday
# Added the APSMpSRSlowBeamDumpFreqRestore procedure to restore the rf
# frequency value incase the slow dump procedures are aborted.
#
# Revision 1.2  2011/08/16 21:25:03  soliday
# Fixed a bug in the dialog screen.
#
# Revision 1.1  2011/08/16 21:05:14  soliday
# Added procedures for doing a slow beam dump.
#
#
#

proc APSMpSRSlowBeamDump24SingletsInfo {} {
    return "The rf frequency is ramped down until the current is 20mA. Then the beam is dumped."
}

proc APSMpSRSlowBeamDump24SingletsInitDialog {frame} {
    global APSMpSRSlowBeamDump24Singlets
    APSLabeledEntry .le1 -parent $frame -label " Initial RF frequency change (HZ): " \
      -textVariable APSMpSRSlowBeamDump24Singlets(initialFrequencyChange) \
      -contextHelp "The PV BRF:S:Hp8657RefFreqAO will be changed by this amount initially"
    APSLabeledEntry .le2 -parent $frame -label "RF frequency change per step (HZ): " \
      -textVariable APSMpSRSlowBeamDump24Singlets(frequencyChange) \
      -contextHelp "The PV BRF:S:Hp8657RefFreqAO will be changed by this amount each step"
    APSLabeledEntry .le3 -parent $frame -label "    Pause between steps (seconds): " \
      -textVariable APSMpSRSlowBeamDump24Singlets(pauseBetweenSteps) \
      -contextHelp "The amount of time to wait before changing the RF frequency again"
    APSLabeledEntry .le4 -parent $frame -label "     Threshold lifetime (minutes): " \
      -textVariable APSMpSRSlowBeamDump24Singlets(thresholdLifetime) \
      -contextHelp "The SR lifetime must be greater than this amount otherwise the program will pause and wait for the lifetime to increase"
    APSLabeledEntry .le5 -parent $frame -label " Threshold current reduction (mA): " \
      -textVariable APSMpSRSlowBeamDump24Singlets(thresholdCurrentReduction) \
      -contextHelp "If the SR current is not reduced by this amount in one step, the program will not pause even if the SR lifetime is less than the given threshold lifetime"
    APSLabeledEntry .le6 -parent $frame -label " Threshold radiation level (mR/h): " \
      -textVariable APSMpSRSlowBeamDump24Singlets(thresholdRadiationLevel) \
      -contextHelp "The ID3 and ID4 radiation levels must be lower than this threshold or the program will pause and wait for them to decrease"
    APSLabeledEntry .le7 -parent $frame -label "              Dump condition (mA): " \
      -textVariable APSMpSRSlowBeamDump24Singlets(dumpCondition) \
      -contextHelp "Once the SR current goes below this level the beam will be dumped"

    return
}


#This procedure has been placed in the attic
proc APSMpSRSlowBeamDump24Singlets {args} {
    set initialFrequencyChange -1800
    set frequencyChange -20
    set dumpCondition 30
    set thresholdCurrentReduction .2
    set pauseBetweenSteps 1
    set thresholdLifetime 12
    set thresholdRadiationLevel 3

    APSStrictParseArguments {initialFrequencyChange frequencyChange dumpCondition thresholdCurrentReduction pauseBetweenSteps thresholdLifetime thresholdRadiationLevel}

    APSMpStep init -promptDialog APSMpSRSlowBeamDump24SingletsInitDialog -vars {initialFrequencyChange frequencyChange dumpCondition thresholdCurrentReduction pauseBetweenSteps thresholdLifetime thresholdRadiationLevel}

    APSMpStep "Running APSMpSRSlowBeamDump" -desc "Run APSMpSRSlowBeamDump" -proc "APSMpSRSlowBeamDump"
    if {[catch {APSMpSRSlowBeamDump \
                  -initialFrequencyChange $initialFrequencyChange \
                  -frequencyChange $frequencyChange \
                  -dumpCondition $dumpCondition \
                  -thresholdCurrentReduction $thresholdCurrentReduction \
                  -pauseBetweenSteps $pauseBetweenSteps \
                  -thresholdLifetime $thresholdLifetime \
                  -thresholdRadiationLevel $thresholdRadiationLevel} results]} {
        if {[APSPEMTKDialog .warningDialog -text "APSMpSRSlowBeamDump: \n$results"] == 1} {
            APSMpReturn error "APSMpSRSlowBeamDump24Singlets: $results"
        }
    }
    APSMpReturn ok
}

proc APSMpSRSlowBeamDumpHybridInfo {} {
    return "The rf frequency is ramped down until the current is 20mA. Then the beam is dumped."
}

proc APSMpSRSlowBeamDumpHybridInitDialog {frame} {
    global APSMpSRSlowBeamDumpHybrid
    APSLabeledEntry .le1 -parent $frame -label " Initial RF frequency change (HZ): " \
      -textVariable APSMpSRSlowBeamDumpHybrid(initialFrequencyChange) \
      -contextHelp "The PV BRF:S:Hp8657RefFreqAO will be changed by this amount initially"
    APSLabeledEntry .le2 -parent $frame -label "RF frequency change per step (HZ): " \
      -textVariable APSMpSRSlowBeamDumpHybrid(frequencyChange) \
      -contextHelp "The PV BRF:S:Hp8657RefFreqAO will be changed by this amount each step"
    APSLabeledEntry .le3 -parent $frame -label "    Pause between steps (seconds): " \
      -textVariable APSMpSRSlowBeamDumpHybrid(pauseBetweenSteps) \
      -contextHelp "The amount of time to wait before changing the RF frequency again"
    APSLabeledEntry .le4 -parent $frame -label "     Threshold lifetime (minutes): " \
      -textVariable APSMpSRSlowBeamDumpHybrid(thresholdLifetime) \
      -contextHelp "The SR lifetime must be greater than this amount otherwise the program will pause and wait for the lifetime to increase"
    APSLabeledEntry .le5 -parent $frame -label " Threshold current reduction (mA): " \
      -textVariable APSMpSRSlowBeamDumpHybrid(thresholdCurrentReduction) \
      -contextHelp "If the SR current is not reduced by this amount in one step, the program will not pause even if the SR lifetime is less than the given threshold lifetime"
    APSLabeledEntry .le6 -parent $frame -label " Threshold radiation level (mR/h): " \
      -textVariable APSMpSRSlowBeamDumpHybrid(thresholdRadiationLevel) \
      -contextHelp "The ID3 and ID4 radiation levels must be lower than this threshold or the program will pause and wait for them to decrease"
    APSLabeledEntry .le7 -parent $frame -label "              Dump condition (mA): " \
      -textVariable APSMpSRSlowBeamDumpHybrid(dumpCondition) \
      -contextHelp "Once the SR current goes below this level the beam will be dumped"

    return
}


#This procedure has been placed in the attic
proc APSMpSRSlowBeamDumpHybrid {args} {
    set initialFrequencyChange -500
    set frequencyChange -20
    set dumpCondition 20
    set thresholdCurrentReduction 1
    set pauseBetweenSteps 1
    set thresholdLifetime 2
    set thresholdRadiationLevel 3

    APSStrictParseArguments {initialFrequencyChange frequencyChange dumpCondition thresholdCurrentReduction pauseBetweenSteps thresholdLifetime thresholdRadiationLevel}

    APSMpStep init -promptDialog APSMpSRSlowBeamDumpHybridInitDialog -vars {initialFrequencyChange frequencyChange dumpCondition thresholdCurrentReduction pauseBetweenSteps thresholdLifetime thresholdRadiationLevel}

    APSMpStep "Running APSMpSRSlowBeamDump" -desc "Run APSMpSRSlowBeamDump" -proc "APSMpSRSlowBeamDump"
    if {[catch {APSMpSRSlowBeamDump \
                  -initialFrequencyChange $initialFrequencyChange \
                  -frequencyChange $frequencyChange \
                  -dumpCondition $dumpCondition \
                  -thresholdCurrentReduction $thresholdCurrentReduction \
                  -pauseBetweenSteps $pauseBetweenSteps \
                  -thresholdLifetime $thresholdLifetime \
                  -thresholdRadiationLevel $thresholdRadiationLevel} results]} {
        if {[APSPEMTKDialog .warningDialog -text "APSMpSRSlowBeamDump: \n$results"] == 1} {
            APSMpReturn error "APSMpSRSlowBeamDumpHybrid: $results"
        }
    }
    APSMpReturn ok
}

proc APSMpSRSlowBeamDump {args} {
    set initialFrequencyChange -1000
    set frequencyChange -20
    set dumpCondition 20
    set thresholdCurrentReduction 1
    set pauseBetweenSteps 1
    set thresholdLifetime 2
    set thresholdRadiationLevel 3
    
    APSStrictParseArguments {initialFrequencyChange frequencyChange dumpCondition thresholdCurrentReduction pauseBetweenSteps thresholdLifetime thresholdRadiationLevel}
    
    set rfFrequencyPV BRF:S:Hp8657RefFreqAO
    set lifetimePV SRlifeTimeSUB
    set currentPV S35DCCT:currentCC
    set id3radiationPV S:RM:ID3:NRateAi
    set id4radiationPV S:RM:ID4:NRateAi

    #Read the initial freq
    APSMpStep "Reading the initial rf frequency" -desc "Read the initial rf frequency"
    global rfFrequency
    pv linkw rfFrequency $rfFrequencyPV
    pv linkw rfFrequencyDesc ${rfFrequencyPV}.DESC

    set initialRfFrequency $rfFrequency
    set rfFrequencyLimit [expr $initialRfFrequency + $initialFrequencyChange]
    #Set the .DESC field to the initial value so that it can be quickly restored incase the procedure is canceled
    APSMpStep "Recording the initial rf frequency in the .DESC field" -desc "Record the initial rf frequency in the .DESC field"
    set rfFrequencyDesc $initialRfFrequency
    pv putw rfFrequencyDesc

    #Read the SR Current
    APSMpStep "Reading the SR current" -desc "Read the SR current"
    if {[catch {APScavget -list=$currentPV -printErrors} current]} {
        APSMpReturn error "APSMpSRSlowBeamDump: $current"
    }
    set previousCurrent $current
    while {$current > $dumpCondition} {
        APSMpStep "Reading the SR lifetime and ID3 and ID4 radiation levels" -desc "Read the SR lifetime and ID3 and ID4 radiation levels"
        #Read the lifetime
        if {[catch {APScavget -list=$lifetimePV -printErrors} lifetime]} {
            APSMpReturn error "APSMpSRSlowBeamDump: $lifetime"
        }
        #Read ID3 radiation level
        if {[catch {APScavget -list=$id3radiationPV -printErrors} id3radiation]} {
            APSMpReturn error "APSMpSRSlowBeamDump: $id3radiation"
        }
        #Read ID4 radiation level
        if {[catch {APScavget -list=$id4radiationPV -printErrors} id4radiation]} {
            APSMpReturn error "APSMpSRSlowBeamDump: $id4radiation"
        }
        if {($id3radiation < $thresholdRadiationLevel) && \
              ($id4radiation < $thresholdRadiationLevel) && \
              (($lifetime > $thresholdLifetime) || ([expr abs($previousCurrent - $current)] < $thresholdCurrentReduction))} {

            if {$rfFrequency > $rfFrequencyLimit} {
                #Step down df= -100 hz in single step
                APSMpStep "Reducing rf frequency by 100 hz" -desc "Reduce rf frequency"
                set rfFrequency [expr $rfFrequency - 100]
                pv putw rfFrequency
            } else {
                #Step down df= -20 hz in single step
                APSMpStep "Reducing rf frequency by $frequencyChange hz" -desc "Reduce rf frequency"
                set rfFrequency [expr $rfFrequency + $frequencyChange]
                pv putw rfFrequency
            }
        } else {
            APSMpStep "Pausing for $pauseBetweenSteps seconds(s)" -desc "Pause"
        }
        set pauseTime [expr $pauseBetweenSteps * 100.0 / $current]
        APSWaitWithUpdate -waitSeconds $pauseTime
        #Read the SR Current
        APSMpStep "Reading the SR current" -desc "Read the SR current"
        set previousCurrent $current
        if {[catch {APScavget -list=$currentPV -printErrors} current]} {
            APSMpReturn error "APSMpSRSlowBeamDump: $current"
        }
    }
    APSMpStep "Dumping beam" -desc "Dump beam"
    if {[catch {APSMpSRDumpBeam} results]} {
        if {[APSPEMTKDialog .warningDialog -text "APSMpSRSlowBeamDump: \n$results"] == 1} {
            APSMpReturn error "APSMpSRSlowBeamDump: $results"
        }
    }
    APSMpStep "Resetting the MPS" -desc "Reset MPS"
    if {[catch {APSMpSRResetMPS} results]} {
        if {[APSPEMTKDialog .warningDialog -text "APSMpSRSlowBeamDump: \n$results"] == 1} {
            APSMpReturn error "APSMpSRSlowBeamDump: $results"
        }
    }
    APSWaitWithUpdate -waitSeconds 1
    #Restore initial RF frequency
    APSMpStep "Restoring the initial rf frequency" -desc "Restore the initial rf frequency"
    set rfFrequency $initialRfFrequency
    pv putw rfFrequency
    APSMpReturn ok
}

proc APSMpSRSlowBeamDumpFreqRestoreInfo {} {
    return "If the slow beam dump was aborted then we probably need to restore the rf frequency. This procedure does that by taking the value previously stored in BRF:S:Hp8657RefFreqAO.DESC and placing it in BRF:S:Hp8657RefFreqAO.VAL"
}

#This procedure has been placed in the attic
proc APSMpSRSlowBeamDumpFreqRestore {args} {
    APSMpStep init -promptDialog APSMpPromptInitDialog
    set rfFrequencyPV BRF:S:Hp8657RefFreqAO

    #Read the initial freq
    APSMpStep "Reading the initial rf frequency from the .DESC field" -desc "Read the initial rf frequency from the .DESC field"
    global rfFrequency rfFrequencyDesc
    pv linkw rfFrequencyDesc ${rfFrequencyPV}.DESC
    pv linkw rfFrequency ${rfFrequencyPV}

    APSMpStep "Restoring the initial rf frequency from the .DESC field" -desc "Restore the initial rf frequency from the .DESC field"
    set rfFrequency ${rfFrequencyDesc}
    pv putw rfFrequency

    APSMpReturn ok
}
