#---------------------------------------------------------------------------------
#	Obtain image statistics
#---------------------------------------------------------------------------------
#
# in the viewer:
# - Open image source2.continuum.fits, as a raster map
# - Select a region
# - use the "region panel" to obtain flux densities around the image
# - use the "polygon icon" to obtain flux density for the whole galaxy
# - obtain the rms: region outside the emitting region
#
#------------------
# in the command line: imstat

# flux density of the whole image

imstat(imagename = 'NGC1614_continuum.image')

# flux density in a region (the most intense clump)

imstat(imagename = 'NGC1614_continuum.fits', box='182,190,189,195')

# Results are shown in the CASA log and returned as a dictionary in the terminal
# these can be stored as variables and use later

mystats=imstat(imagename = 'source2.continuum.fits', box='182,190,189,195')
mystats['flux'][0]

# obtain rms in a signal-free region

mystats=imstat(imagename = 'source2.continuum.fits', box='25,25,100,100')
mystats['rms'][0]


#---------------------------------------------------------------------------------
#	Source fitting
#---------------------------------------------------------------------------------
#
# in the viewer: 
# - select a region
# - use the interactive 2D fitting icon
#   Results are shown in the CASA log
#   an output file can be created to save results
# 
#------------------
# in the command line: imfit

#  Using similar region as before for imstat

imfit(imagename = 'NGC1614_continuum.image', region='circle [ [ 185pix , 193pix] ,8pix ]')

# Results shown in the CASA log and also in the terminal
# Store the results in variables:

myfit=imfit(imagename = 'source2.continuum.fits', 
           region='circle [ [ 185pix , 193pix] ,8pix ]')

myfit['results']['component0']['flux']

# NOTE: 'results' show the source sizes convolved with the beam:
myfit['results']['component0']['shape']['majoraxis']
myfit['results']['component0']['shape']['minoraxis']

# while 'deconvolved' can show smaller "physical" sizes
myfit['deconvolved']['component0']['shape']['majoraxis']
myfit['deconvolved']['component0']['shape']['minoraxis']

# save results information from the CASA log in a logfile
imfit(imagename = 'source2.continuum.fits', 
      region='circle [ [ 185pix , 193pix] ,8pix ]', 
      logfile = 'myfit.txt')


#---------------------------------------------------------------------------------
#	Contour level maps
#---------------------------------------------------------------------------------
#
# in the viewer: 
# - use the "manage images" icon to change the view to contour
# - open "display options"
#   Note the default values correspond to a fraction of the maximum peak in the image
# - change the basic settings to show contours as a multiple of the rms (unit), with 
#   first two contour levels to be -3 and +3 sigma (rms)
# - with that contour continuum map, open the CO 6-5 image as a colour map (raster)
#
#------------------
# in the command line: imview
# this is a useful command to create and save raster and contour maps
# we use an example to obtain the same contour image:

imview(contour={'file': 'NGC1614_continuum.image', 
       'levels': [-3, 3, 5, 10, 15, 20], 'unit': 0.0008}, 
       zoom=3, out='ngc1614-continuum.png')


imview(raster={'file': 'NGC1614_CO6-5.image', 
       'range': [-0.05, 0.35], 'colormap': 'Rainbow 2'}, 
       zoom={'channel': 25, 'blc': [110,125], 'trc': [260,260]})


imview(contour={'file': 'NGC1614_continuum.image', 
       'levels': [-3, 3, 5, 10, 15, 20], 'unit': 0.0008}, 
       raster={'file': 'NGC1614_continuum.image', 
       'range': [-0.0035, 0.018], 'colormap': 'Rainbow 2', 'colorwedge': True}, 
       zoom={'blc': [110,125], 'trc': [260,260]})


#---------------------------------------------------------------------------------
#	Image header: imhead
#---------------------------------------------------------------------------------
#
# Obtain basic information about the image

# mode='summary' (default) will print out a summary of the image properties in the log

imhead('NGC1614_continuum.image')

imhead('NGC1614_CO6-5.image')

# Note the frequency axis has shape between the continuum and line images

# mode='list' prints out a list of the header keywords and values to the terminal

imhead('source2.continuum.fits', mode='list')

# which again, we can store in variable for latter use

myhead=imhead('NGC1614_continuum.image', mode='list')
myhead['beammajor']
myhead['beamminor']

# This can also be done by using mode='get'
 
mybmaj = imhead('source2.continuum.fits',mode='get',hdkey='beammajor')
mybmaj

# imhead can also be used to modify header parameters, with mode='put'
# This could be helpful to, e.g. modify the position center to overlay 
# with other images, etc..
# BUT use with caution: we *only* replace the current value of the header, 
# for any transformation on the image, e.g. modify coordinate system, 
# or velocity frame, etc, one needs to use other CASA tasks!
#


#---------------------------------------------------------------------------------
#	Spectral images: the spectral profile tool
#---------------------------------------------------------------------------------
#
# in the viewer: 
# - Open image
# - use the "animators panel" to explore the image in different channels
# - select a region and open the spectral profile tool, and 
#   explore panel options and line emission in different regions
# - Line identification: go to "line overlays"
#   * select a region of the spectra to search for lines in splatalogue
#   * include the source velocity!
#   * it is possible to search for an specific molecule and filter by kind of source.
# - Extract spectra: disk icon in the top panel
#   will create a txt file table with frequencies and intensities
#   NOTE the frequencies extracted are sky frequencies!
#        and that intensity scale may be wrong!
#
#------------------
# there are also tools for line identification in the command line:
# slsearch and splattotable
#
# slsearch: it searches in splatalogue (default), following the selection options, e.g.
slsearch(freqrange=[freq1,freq2], verbose=True)

# verbose=True will print the search results in the CASA log
# see other search options with inp slsearch
# we can also create a table
slsearch(outfile='mylines.tbl', freqrange=[freq1,freq2])

# This table can be explored with browsetable:
browsetable('mylines.tbl')

# shows more columns (energy levels, catalog source, etc.) not shown in the spectral
# viewer search table

# It is possible to search in an existing tbl, for an specific species, etc. e.g.
slsearch(tablename = 'mylines.tbl', freqrange = [freq1,freq2], 
         species = ['mymolecule'], verbose=True)


# splattotable: creates tables from splatalogue files (Export CASA fields)
splattotable(filenames = ['splatalogue.tsv'], table = 'splatalogue.tbl')

# which can be latter searched for using slsearch
# similar .tsv files can be prepared from other catalogues, 
# just be careful with the format!

#------------------
# extract spectra in the command line: imval

# simple example extracting spectra in one pixel

xval=imval(imagename='NGC1614_CO6-5.image', box='184,165', chans='0~40')

# type the following to see all the results
xval

# similar to other tasks, we can extract the quantity we are interested in
# peak is at:
xval['data'][17]

# and the corresponding freq is:
xval['coords'][17][3]

# to see it in MHz
xval['coords'][17][3]*1E-06

# NOTE it is still sky frequency!
# but from the source velocity we can compute the frequency shift and apply

# the imval command above can be scripted to extract the spectra for all 
# frequencies and different regions of the image


#---------------------------------------------------------------------------------
#	Focus on one line: data visualization
#---------------------------------------------------------------------------------
#
# multiple panels plot: 
#
# - Open image
# - open the "panel display options"
# - select 3x3 panels, adjust the margings, and character size, etc. as needed
# - move to select the best velocities to show using the channels animator, e.g. 
#   around the central velocity of the source
#
# Spectral viewer: 
# - go back to one panel
# - open the spectral profile tool
# - select one or two regions to explore the spectra in both sources
# NOTE: the higher angular and spectral resolution wrt the product images
#


#---------------------------------------------------------------------------------
#	Focus on one line: line fitting
#---------------------------------------------------------------------------------
#
# in the viewer: spectral profile tool
# - select a region and open the spectral profile tool
# - adjust the velocity range to consider
# - fit one gaussian --> check results in the opened window and the fitted profile
#   It is possible to save the output results checking the corresponding box 
#   before performing the fit
# - repeat, now selecting a region with a complex profile and try to fit two gaussians
#   Now in the viewer we see the fits for each and the total fit to the line
#   Note in the results window the different central velocities and widths
# - It is also possible to include initial guesses for the line fit: 
#   * double-click in the table and introduce by hand the numbers, or select 
#     graphycally on the line profile 
#   * or using the Estimates button 
#
#------------------
# in the command line: specfit
#
# two-gaussian fit example

specfit(imagename='NGC1614_CO6-5.image', box='178,159,191,172', 
        chans='5~40', ngauss=2, multifit=False)

# multifit=False, will average the axis pixels and do a single fit to that average profile
# Fit results are shown in the CASA log and in the terminal as a dictionary.
# it is also possible to save into a logfile

specfit(imagename='NGC1614_CO6-5.image', box='178,159,191,172', 
        chans='5~40', ngauss=2, multifit=False, logfile='myfit.txt')


# multifit=True, allows to fit a profile along the desired axis at each pixel in the region.
# NOTE that fitting a multiple gaussian could complicate the fitting, and initial estimates 
# might be necessary, even for one gaussian
# It allows to save images of the obtained fitting results that can be opened in the viewer

# Simple example: fit one gaussian in same box as previous, save velocity and width: 

specfit(imagename='NGC1614_CO6-5.image', box='178,159,191,172', chans='5~40', 
        ngauss=1, multifit=True, center = 'NGC1614_CO6-5-fit.velo', 
        fwhm = 'NGC1614_CO6-5-fit.width')

# Now open the images .velo and .width in the viewer
# there are many bad fits outside the emitting region, adjust the levels
# (using the wedge values) for a better image
# to solve this issue it might be necessary to include/exclude pixels (select a
# threshold for pixels to be included or not in the fit)
#


#---------------------------------------------------------------------------------
#	Focus on one line: position-velocity diagrams
#---------------------------------------------------------------------------------
#
# in the viewer:
# - select in the cursor panel: "P/V tool"
# - draw a line along the desired direction
# - open the "regions panel" and go to the pV tab
# - generate P/V will open a new viewer display with the pv diagram
# 
#------------------
# in the command line: impv
#
# Example for NGC1614_CO6-5
impv(imagename='NGC1614_CO6-5.image', outfile='NGC1614_CO6-5_pv.image', chans='', 
     mode='length', center= ['04h34m00.0s','-08d34m45.6s'], length='2.8arcsec', pa='90deg')

# center can be obtained from the cursor panel
# and length and pa from the pv tab in regions
# open the obtained pv images in the viewer
#

#---------------------------------------------------------------------------------
#	Focus on one line: moment maps
#---------------------------------------------------------------------------------
#
# in the viewer:
# - Open the image NGC1614_CO6-5.image
# - open the calculate moments/collapse tool
# - select a large region in the image including all the emission
# - in the collapse tool, select channels to collapse: 4450-4950
# - select moment to compute: moment 0 --> push collapse button
#   a new image will be created in the display
#
# Similarly, we can obtain the other moments...
# - do moments 1, without any threshold
#   * note we don't see anything in the obtained moment image
#     open the display tool: the data range is too large
#     --> we need to set a threshold using includepix/excludepix
#   * explore values to use in includepix: some multiple of the rms
# - do moment 2, 
#   * start with same pixel values above
#   * if it looks a noisy try higher values
#
#------------------
# in the command line: immoments
#
# moment 0 map, no threshold:

immoments(imagename = 'NGC1614_CO6-5.image', moments = [0], box = '130,135,235,240'
          chans = '5~55', outfile = 'NGC1614_CO6-5.mom0')

# moment 1 and 2, with threshold:
immoments(imagename = 'NGC1614_CO6-5.image', moments = [1,2], box = '130,135,235,240', 
          chans = '5~55', includepix = [0.080,1000], outfile = 'NGC1614_CO6-5.mom')

# outfile: If a single moment is chosen, the outfile specifies the exact name of the 
# output image. If multiple moments are chosen, then outfile will be used as the root 
# of the output filenames, which will get different suffixes for each moment. 

# open moment images in the viewer, move between them with the animators panel
# change the moment0 map to contours to overly to the higher moment maps

