#!/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

#
# $Log: SRQuadSextHistograms,v $
# Revision 1.5 2023/07/28 00:13:00 lobach
# Changes for APS-U. Added skew quads. Still need to add magnet temperature PVs when they become available
#

set CVSRevisionAuthor "\$Revision: 1.2 $ \$Author: lobach $"
APSApplication . -name  "Power supplies histograms"\
  -version $CVSRevisionAuthor \
  -overview "Collects, archives, and analyzes storage-ring power supplies statistics for quads and sextupoles."
set status "Working..."
APSScrolledStatus .status -parent .userFrame -textVariable status -width 78 -height 8
update

set archiveDir /home/helios/oagData/sr/QuadSextHistograms

proc MakeMainMenu {} {
    global familySelected dataSelected nDcctSamples

    APSCheckButtonFrame .types -parent .userFrame -label "Magnet Types: " \
      -variableList {familySelected(Q1) familySelected(Q2) familySelected(Q3) familySelected(Q4) familySelected(Q5) familySelected(Q6) familySelected(Q7) familySelected(Q8) familySelected(S1) familySelected(S2) familySelected(S3) familySelected(SQ1) familySelected(SQ2)} \
      -buttonList {Q1 Q2 Q3 Q4 Q5 Q6 Q7 Q8 S1 S2 S3 SQ1 SQ2} \
      -orientation horizontal -allNone 1 -contextHelp \
      "Choose quadrupole and sextupole magnet families for display."

    APSFrame .f1 -parent .userFrame -label "Single-sample histograms" 
    set w .userFrame.f1.frame
    APSCheckButtonFrame .data -parent $w -label "Data: " \
      -variableList {dataSelected(MeasCurrentM) dataSelected(DCCT) dataSelected(SetCurrentC) \
                       dataSelected(VoltageM)} \
      -buttonList {MeasCurrentM DCCT:CurrentM SetCurrentC VoltageM} \
      -orientation horizontal -allNone 1 -contextHelp \
      "Choose types of data for display"

    APSButton .acquire -parent $w -text Acquire/Display \
      -command "AcquireData ; DisplayLastData; APSEnableButton $w.redisplay.button" 
    APSButton .redisplay -parent $w -text "Display Again" \
      -command DisplayLastData 
    APSDisableButton $w.redisplay.button
    APSButton .display -parent $w -text "Plot..." -command "ChooseAndDisplayData"

    APSFrame .f2 -parent .userFrame -label "10Hz-sampled external DCCT histograms"
    set w .userFrame.f2.frame

    set nDcctSamples 100
    APSLabeledEntry .le1 -parent $w -label "Samples: " -textVariable nDcctSamples
    
    APSButton .acquire -parent $w -text Acquire/Display \
      -command "Acquire10HzDcctData ; DisplayLast10HzDcctData; APSEnableButton $w.redisplay.button" 
    APSButton .display1 -parent $w -text "Plot..." -command "ChooseAndDisplay10HzDcctData -mode plot"
    APSButton .display2 -parent $w -text "List..." -command "ChooseAndDisplay10HzDcctData -mode list"
} 

proc setStatusText {text} {
    global status
    set status $text
    update
}

set lastDataFile ""
proc AcquireData {} {
    global lastDataFile archiveDir
    set lastDataFile $archiveDir/dataFiles/QS-[clock format [clock seconds] -format %Y-%m%d-%H%M%S].gz

    if [catch {eval exec sddssnapshot $archiveDir/inputFiles/QuadSextSkewQuadCurrentVoltageTemp.mon \
        -pipe=out | gzip -c > $lastDataFile} result] {
       setStatusText "Problem taking data: $result"
       return
    }  
    setStatusText "Data taken."
}        

proc DisplayLastData {} {
    global lastDataFile 
    DisplayData -fileName $lastDataFile
}

proc ChooseAndDisplayData {} {
    global archiveDir
    set origDir [pwd]
    cd $archiveDir/dataFiles
    set fileList [lsort -decreasing [glob -nocomplain QS-????-????-??????.gz]]
    if ![llength $fileList] {
        setStatusText "No files found."
        cd $origDir
        return
    }
    set fileChosen [APSChooseItemFromList -itemList $fileList -returnIndices 0] 
    if ![string length $fileChosen] {
        setStatusText "Display cancelled."
        cd $origDir
        return
    }
    cd $origDir
    DisplayData -fileName $archiveDir/dataFiles/$fileChosen 
}

proc DisplayData {args} {
    set fileName ""
    APSStrictParseArguments {fileName}

    global dataSelected familySelected
    set displayedSomething 0
    foreach controlName {MeasCurrentM VoltageM DCCT SetCurrentC} \
      item {CurrentReadback VoltageReadback DCCTReadback CurrentSetpoint} \
      suffix {PS:MeasCurrentM PS:VoltageM DCCT:CurrentM PS:SetCurrentC} \
      binsize {0.1 0.05 0.1 0.1} {
          if !$dataSelected($controlName) continue
          set fileList ""
          foreach family {Q1 Q2 Q3 Q4 Q5 Q6 Q7 Q8 S1 S2 S3 SQ1 SQ2} {
              if !$familySelected($family) continue
              setStatusText "Processing $controlName for $family"
              set tmpFile /tmp/[APSTmpString]
              APSAddToTempFileList $tmpFile
              if [catch {exec sddsprocess $fileName -pipe=out \
                           -match=column,ControlName=S*:${family}:$suffix \
                           "-print=parameter,LabelString1,$item for $family" \
                           | sddsconvert -pipe -rename=column,Value=$item \
                           | sddshist -pipe=in $tmpFile \
                           -data=$item -sizeOfBins=$binsize} result] {
                  setStatusText "Problem for $controlName ($item) and $family: $result"
                  return
              }
              lappend fileList $tmpFile
          }
          if [llength $fileList] {
              eval exec sddsplot -column=$item,frequency -graph=impulse $fileList -separate \
                    -topline=@LabelString1 -unsuppress=y &
              after 4000 "eval file delete $fileList"
              set displayedSomething 1
          }
      }
    if !$displayedSomething {
        setStatusText "Choose something to display"
    } else {
        setStatusText "Done."
    }
}

set last10HzDcctDataFile ""
set tmpMon /tmp/[APSTmpString].mon
APSAddToTempFileList $tmpMon
exec sddsprocess $archiveDir/inputFiles/QuadSextSkewQuadCurrentVoltageTemp.mon $tmpMon -match=col,ControlName=*DCCT:CurrentM
    
proc Acquire10HzDcctData {} {
    global last10HzDcctDataFile archiveDir tmpMon nDcctSamples
    
    set last10HzDcctDataFile $archiveDir/dataFiles/QS-10HzDcct-[clock format [clock seconds] -format %Y-%m%d-%H%M%S]

    setStatusText "Taking data..."
    if [catch {eval exec sddslogger $tmpMon $last10HzDcctDataFile -sampleInterval=0.1 -steps=$nDcctSamples \
                    -flushInterval=$nDcctSamples} result] {
       setStatusText "Problem taking data: $result"
       return
    }  
    setStatusText "Data taken."
}        

proc ChooseAndDisplay10HzDcctData {args} {
    set mode plot
    APSStrictParseArguments {mode}
    global archiveDir
    set origDir [pwd]
    cd $archiveDir/dataFiles
    set fileList [lsort -decreasing [glob -nocomplain QS-10HzDcct-????-????-??????]]
    if ![llength $fileList] {
        setStatusText "No files found."
        cd $origDir
        return
    }
    set fileChosen [APSChooseItemFromList -itemList $fileList -returnIndices 0] 
    if ![string length $fileChosen] {
        setStatusText "Display cancelled."
        cd $origDir
        return
    }
    cd $origDir
    Display10HzDcctData -fileName $archiveDir/dataFiles/$fileChosen -mode $mode
}

proc Display10HzDcctData {args} {
    set fileName ""
    set mode plot
    APSStrictParseArguments {fileName mode}

    global dataSelected familySelected
    set displayedSomething 0
    set suffix DCCT:CurrentM
    set plotOptionList [list]
    set fileList [list]
    foreach family {Q1 Q2 Q3 Q4 Q5 Q6 Q7 Q8 S1 S2 S3 SQ1 SQ2} {
        if !$familySelected($family) continue
        setStatusText "Processing DCCT data for $family"
        set tmpFile /tmp/[APSTmpString]
        APSAddToTempFileList $tmpFile
        if [catch {exec sddsconvert $fileName -pipe=out -retain=col,S???:$family:* \
                     | sddsprocess -pipe -process=*$suffix,ave,%sAve -process=*$suffix,stand,%sStDev \
                     | sddscollapse -pipe \
                     | sddscollect -pipe=in -collect=suffix=:${suffix}Ave,column=Average -collect=suffix=:${suffix}StDev,column=StDev \
                     $tmpFile } result] {
            return -code error "$result"
        }
        lappend plotOptionList -column=Rootname,Average $tmpFile "-title=$family Averages"
        lappend plotOptionList -column=Rootname,StDev $tmpFile "-title=$family Standard Deviations"
        lappend fileList $tmpFile
    }
    switch $mode {
        plot {
            if [llength $plotOptionList] {
                   eval exec sddsplot -graph=sym,fill -separate=1 $plotOptionList &
                   setStatusText "Done."
               } else {
                   setStatusText "Choose something to display"
               }
        }
        list {
            set tailName [file tail $fileName]
            if [llength $fileList] {
                if [catch {eval exec sddscombine $fileList -pipe=out \
                             | sddsprocess -pipe -process=StDev,ave,%sAve \
                             | sddssort -pipe -column=StDev,decr \
                             | sddsprocess -pipe "{-test=column,StDev StDevAve >}" -nowarning \
                             | sddsprintout -pipe "{-column=Rootname,label=PS Name}" -column=Average -column=StDev \
                             "{-title=High standard deviations from 10 Hz DCCT for $tailName}" -parameter=StDevAve -postPage=2 \
                             > $tmpFile.txt} result] {
                    return -code error "$result"
                }
                APSFileDisplayWindow .list -width 80 -fileName $tmpFile.txt -deleteOnClose 1 -modal 0
            } else {
                setStatusText "Choose something to display"
            }
        }
    }
}

setStatusText Ready.
MakeMainMenu 

