#! /bin/csh -f
#jhz 2015-10-20 create
#jhz 2016-01-12 modify
#jhz 2016-01-27 edited for CO(2-1)
#jhz 2016-01-29 finalize and document
#jhz 2016-03-28 implemented for H30alpha line
#Imaging-proces: for H30alpha line with a calibrated spectral line data
#                produced from SWARM and ASIC, SMA hybrid correlator
#                with Miriad4GHz software -
#                <a href="https://www.cfa.harvard.edu/sma/miriad/miriad4GHz/SMAMiriad4GHz.html">(SMA-Miriad 1.5.1)</a>
#                The default spectral line for the example data
#                was observed towards CO(2-1). Therefore, the rest frequency
#                for an alternative target line (e.g. H30alpha) must be reset
#                by users, the relevant lines 91-98 and 232-233 in
#                this script. 
echo "                                                                      "
echo "######################################################################"
echo "# imagingln_H30a_mosaic.csh: script to image H30alpha spectral line   "
echo "# extracted from a calibrated subset of SMA data produced from        "
echo "# Pre-process 2.  Users are required to set up the line parameters    "
echo "# concerning the target line and target sources (fields). The spectral"
echo "# line imaging process are recommended to be carried out in Miriad.   "
echo "# The spectral line uv data set should be compatiable with any        "
echo "# reliable versions distributed by CARMA, ATNF, and SAO concerning    "
echo "# imaging. And FITS outputs are produced for the spectral line cube   "
echo "# in the end of the imaging process.                                  "
echo "# It is option if users choose to make UVFITS output for the specific "
echo "# line uv data and image elsewhere (CASA, Miriad, AIPS and etc.).     "
echo "######################################################################"
#
#Target                (font) - 
#Bandpass calibrator   (bcal) -
#Gain calibrator       (gcal, or gcal1, gcal2) -
#Flux scale calibrator (fcal) -
#
echo "                                                                      "
echo "######################################################################"
echo "# Users need to carefully review the following project-depended setup "
echo "# from lines 37 - 134 prior to executing this script                   "
echo "######################################################################"
echo "                                                                      "
#
#
##set the name of the SMA raw data
#
set file = 160115_03:45:40
#
echo $file   
#
set dt          = 160106
echo ' '
echo 'prefix of data files = ' $dt
echo ' '
#
set hour        = 03:45:40 
set sb          = usb
set nn          = 1 
set rxid        = 0
set rx          = rx${rxid}
set adge        =  7 
set edge        = 500
set nchan_as    = 6130
set maxtsys     = 500
set fname       = "$dt""_""$rx".$sb
set oname       = "$dt""_""$rx"
set fcal        = uranus 
set gcal1       = 0721+713
set gcal2       = 0841+708 
set gcal        = 0721+713  
set bcal        = 3C84
set blcal       = $bcal 
set font        = N2403 
set refant      = 1 
set avetime     = 5
set source1      = ${font}dc1
set source2      = ${font}fd2
set source3      = ${font}fd3
set source4      = ${font}fd4
set source5      = ${font}fd5
#set twogcal    = F    % T two gain calibrators' scheme
set twogcal     = T
set DATPATH     = ../../../ucla-pp2 
                # 
                # The data path contains the calibrated output data in pre-process 2,
                # 160115_rx0.usb.asic.tsys.bp.a                      
                #                     
set fname = ${DATPATH}/${fname}
###########################################
#set spectral line parameters
###########################################
#
#sline is the name of the line transition
#
set sline = H30a 
#
#rfreq is the H30 alpha rest frequency in GHz
#
set rfreq = 231.901 
#
#input calibrated uv file contains the line
#
set uvin = $fname.asic.tsys.bp.a
#
#target sources
#
set targets = $source1,$source2,$source3,$source4,$source5
#
#output calibrated uv file contains the line
#
set uvout = ${dt}.${sline}.uv
#
#line-free windows 
#
set lfwin = 1,3000,3200,4700,5200,6144
#
#mosaic fields
#
set mosaic  = $targets
set mosaicA = $source1,$source2,$source3
set mosaicB = $source4,$source5
#
#image cube name
#
set imname = ${font}.${sline}.fd12345
set imnameA = ${font}.${sline}.fd123
set imnameB = ${font}.${sline}.fd45
#
#linetyp for imaging line cube
#
set linetype = vel,50,-250,15
#
#imaging size and cell size
#
set ims   = 512
set cells = 0.5
#
#clean iter, and fwhm
#
set niter = 2500
set fwhm  = 4.5,4.5
set rms   = 0.025
#
############################################################################
#Imaging-process handles -
############################################################################
#goto INSPECT         # inspect the data calibrated in pre-processing 2
#goto UVSPC-ASIC      # inspect calibrated uv spectra for ASIC data
#goto UVLIN           # separate the line from the vis data
                      # cut the specific line data from the calibrated data set
#goto BLFLAG          # flag bad data points for ASIC chunks
                      #######################################################
                      # below are special for the SMA project 2015B-S041 
goto LNMAP-MOSAIC     # do mosaic-imaging for fields 1 2 3 4 5
goto CDISP-MOSAIC     # display images of fields 1 2 3 4 5
#goto STATS-MOSAIC     # do statistics for the image line cube of fields 1 2 3 4 5
#goto LNMAP-FD123     # do mosaic-imaging for fields 1 2 3
#goto CDISP-FD123     # display images of fields 1 2 3
#goto STATS-FD123     # do statistics for the image line cube of fields 1 2 3
#goto LNMAP-FD45      # do mosaic-imaging for fields 4 5
#goto CDISP-FD45      # display images of fields 4 5
#goto STATS-FD45      # do statistics for the image line cube of fields 4 5
                      #######################################################
#goto UVFITS          # export UVFITS from the calibrated specific line uvdata
#goto FITS            # export FITS from the image line cube
#goto TAR             # make tarballs for the miriad uv files and line image cubes
#goto ZAP             # clean up the working files
#
$<
INSPECT:
echo 'Inspect: ASIC'
uvindex  vis=$fname.asic.tsys.bp.a

$<
UVSPC-ASIC:
$<
echo 'Check spectra: ASIC -' $bcal
smauvspec vis=$fname.asic.tsys.bp.a \
        select='source('$bcal')' \
        interval=1000 hann=5 options=nobase,avall \
        axis=freq,both device=/xs nxy=1,1
$<
echo 'Check spectra: ASIC -' $gcal
smauvspec vis=$fname.asic.tsys.bp.a \
        select='source('$gcal')' \
        interval=1000 hann=5 options=nobase,avall \
        axis=freq,both device=/xs nxy=1,1
$<
echo 'Check spectra: ASIC -' $fcal
smauvspec vis=$fname.asic.tsys.bp.a \
        select='source('$fcal')' \
        interval=1000 hann=5 \
        axis=freq,both device=/xs nxy=1,1 options=nobase,avall
$<
echo 'Check spectra: ASIC -' $targets
smauvspec vis=$fname.asic.tsys.bp.a \
        select='source('$targets')' \
        interval=1000 hann=5 \
        axis=freq,both device=/xs nxy=1,1 options=nobase,avall

$<
UVLIN:
echo 'Check spectra of uvdata: ' $uvin
echo 'Reurn for fringe amp&pha vs sky-frequnecy -'
$<
smauvspec vis=$uvin \
        select='source('$targets')' \
        interval=1000 hann=5 options=nobase,avall \
        axis=freq,both device=/xs nxy=1,1

echo 'Reurn for fringe amp&pha vs LSR-velocity -'
$<
smauvspec vis=$uvin \
        select='source('$targets')' \
        interval=1000 hann=5 options=nobase,avall \
        axis=vel,both device=/xs nxy=1,1

echo 'Reurn for fringe amp&pha channel number -'
$<
smauvspec vis=$uvin \
        select='source('$targets')' \
        interval=1000 hann=5 options=nobase,avall \
        axis=chan,both device=/xs nxy=1,1
$<
\rm -r $uvout 
echo 'line-free windows -' $lfwin
echo 'Make sure the line-free windows are correct'
echo 'Reurn for continuum subtraction -'
$<   
uvlin vis=$uvin chans=$lfwin order=1 \
       mode=line select='source('$targets')' \
       out=$uvout options=nowin
$<
echo 'reset the rest frequency to ' $rfreq
puthd in=$uvout/restfreq value=$rfreq type=double
$<
echo 'check spectra of continuum-subtracted uvdata: ' $uvout
echo 'Reurn for fringe amp&pha vs sky-frequnecy -'
$<
smauvspec vis=$uvout \
        select='source('$targets')' \
        interval=1000 hann=5 options=nobase,avall \
        axis=freq,both device=/xs nxy=1,1
echo 'Reurn for fringe amp&pha vs LSR-velocity -'
$<
smauvspec vis=$uvout \
        select='source('$targets')' \
        interval=1000 hann=5 options=nobase,avall \
        axis=vel,both device=/xs nxy=1,1
echo 'Reurn for fringe amp&pha channel number -'
$<
smauvspec vis=$uvout \
        select='source('$targets')' \
        interval=1000 hann=5 options=nobase,avall \
        axis=chan,both device=/xs nxy=1,1
$<
BLFLAG:
echo 'Baseline-based flagging -' $uvout
smablflag vis=$uvout axis=time,ampl device=/xs

echo 'Reurn for fringe amp&pha vs LSR-velocity '
echo 'with a larger size of hanning smoothing window -'
$<
smauvspec vis=$uvout \
        select='source('$targets')' \
        interval=1000 hann=15 options=nobase,avall \
        axis=vel,both device=/xs nxy=1,1

LNMAP-MOSAIC:
echo 'Reurn for mosaic imaging group A of pointing fields for linetype -' $linetype
$<
\rm -r $imname.map $imname.beam $imname.icmp
invert vis=$uvout map=$imname.map beam=$imname.beam \
        imsize=$ims,$ims cell=$cells sup=0 options=systemp,mosaic \
        line=$linetype select='source('$mosaic')'
echo 'Reurn for examing dirty image line cube -'
$<
cgdisp in=$imname.map type=pixel region=arcsec,'boxes(-100,-100,150,150)(2,50)' \
        xybin=1,1 device=/xs nxy=7,7 options=full,beambr,wedge,trlab,3val \
        labtyp=arcsec,arcsec range=0,0,lin,2 cols1=7 csize=0.5,0.5,0.5
echo 'Reurn to clean dirty image line cube -'
$<
clean map=$imname.map beam=$imname.beam out=$imname.icmp gain=0.08 \
        cutoff=$rms niters=$niter \
        region=arcsec,'boxes(-75,-75,125,125)(1,50)'
echo 'Reurn to restore image cube with a circular beam=' $fwhm
$<
\rm -r $imname.icln
restor model=$imname.icmp beam=$imname.beam map=$imname.map  \
        out=$imname.icln fwhm=$fwhm
$<
CDISP-MOSAIC:
echo 'Reurn to exam the cleaned  line cube -'
$<
cgdisp in=$imname.icln type=pixel \
        region=arcsec,'boxes(-75,-75,125,125)(2,50)' \
        xybin=1,1 device=/xs \
        nxy=7,7 options=beambr,wedge,blacklab,3val \
        labtyp=arcsec,arcsec range=0,0.5,lin,2 cols1=7 csize=0.5,0.5,0.5
echo 'Reurn to exam the clouds 1 -'
$<
cgdisp in=$imname.icln type=pixel \
        region=arcsec,'boxes(-95,-5,0,90)(22,30)' \
        xybin=1,1 device=/xs \
        nxy=3,3 options=beambr,wedge,blacklab,3val \
        labtyp=hms,dms range=0,0.5,lin,2 cols1=7 csize=0.5,0.5,0.5
echo 'Reurn to exam the clouds 2 -'
$<
cgdisp in=$imname.icln type=pixel \
        region=arcsec,'boxes(-45,-50,50,45)(30,38)' \
        xybin=1,1 device=/xs \
        nxy=3,3 options=beambr,wedge,blacklab,3val \
        labtyp=hms,dms range=0,0.5,lin,2 cols1=7 csize=0.5,0.5,0.5
echo 'Reurn to exam the clouds 3 -'
$<
cgdisp in=$imname.icln type=pixel \
        region=arcsec,'boxes(-80,-105,50,5)(35,46)' \
        xybin=1,1 device=/xs \
        nxy=3,4 options=beambr,wedge,blacklab,3val \
        labtyp=hms,dms range=0,0.3,lin,2 cols1=7 csize=0.5,0.5,0.5
STATS-MOSAIC:
echo 'Reurn to do statistics for  the image cube -'
$<
imstat in=$imname.icln region='arcsec,box(-5,-5,5,5)'
$<
imstat in=$imname.icln region='arcsec,box(-55,-55,-70,-70)'
$<
imstat in=$imname.icln region='arcsec,box(-55,55,-70,70)'
exit
echo ''
echo 'Done with imaging process!'
echo ''
echo 'Congratulation if you detected the line that you proposed to observe!'
echo ''
echo 'You may need to go back the editing & calibration process to check'
echo 'your setup if the line has not been detected.'
echo ''
exit

UVFITS:
echo 'export uvfits from ' $uvout
\rm -r $uvout.uvfits
fits in=$uvout op='uvout' out=$uvout.uvfits
echo 'done with uvfits output file =' $uvout.uvfits
$<
FITS:
echo 'export fits from ' $imnameA.icln ' & ' $imnameB.icln
\rm -r $imnameA.icln.fits
fits in=$imnameA.icln op='xyout' out=$imnameA.icln.fits
$<
\rm -r $imnameB.icln.fits
fits in=$imnameB.icln op='xyout' out=$imnameB.icln.fits
echo 'done with fits output files;'
echo 'fits image cubes are ' $imnameA.icln.fits $imnameB.icln.fits
echo ''
echo 'You can continue do analysis with the fits data somewhere else.'
exit
TAR:
echo 'Make gzipped tarballs for the Miriad image cubes -'
\rm $uvout.tar.gz
tar -cvzf $uvout.tar.gz $uvout
\rm $imnameA.tar.gz
tar -cvzf $imnameA.tar.gz $imnameA.icln $imnameA.map $imnameA.beam $imnameA.icmp
\rm $imnameB.tar.gz
tar -cvzf $imnameB.tar.gz $imnameB.icln $imnameB.map $imnameB.beam $imnameB.icmp
echo 'done with tarballs!'
exit
ZAP:
\rm -r $imnameA.map $imnameA.beam $imnameA.icmp 
\rm -r $imnameB.map $imnameB.beam $imnameB.icmp
echo 'done with clean up the working files!'
exit
