! p_plot_tip.mira
! revised by CK 13-Mar-2013, 20-Feb-2013
!
on error return
!
var scan r
var mon r
var gains r
var reduce r
var febe r
!
define integer ifb ipix jpix k1 k2 npix nrecords nsample nsubscan
define real    bxmax bxmin bymax bymin dx dy
define double  aux azimuth mfitSum chisq tau Feff Beff bestTau sum
define double  tauGuess
define logical doHera
define real feff1 feff2 tau1 tau2 feff21 feff22 is sta xsta aguess bguess
define real chisq1 chisq2
!
let aEarth 6378.135 /new double
let bEarth 6356.750 /new double
let hDry   8.4      /new double
let hWet   2.0      /new double
define double am1 am2 gamma h rEarth
!
pen 0
!
let rEarth aEarth*bEarth/sqrt(aEarth**2-(aEarth**2-bEarth**2)-
*(cos(scan%header%sitelat*pi/180.))**2)+scan%header%siteelev*1.d-3
!
clear 
g\set tick 0.1
g\set plot landscape
!
let ifb  &1
let jpix &2
!
let tauGuess gains'ifb'%tauzen[1,jpix,1]
!
if reduce'ifb'%calibration_done[1].eq.0.or.reduce'ifb'%calibration_done[2].eq.0 then
   say "E-SOLVE: please first calibrate these data."
   return
endif
!
Beff = nint(1000*febe'ifb'%data%beameff[1,1])/1000.
Feff = nint(1000*febe'ifb'%data%etafss[1,1])/1000.
!
if Beff.ne.Feff then
   say "E-SOLVE: please calibrate in antenna temperature."
   say  "Enter:" 
   say " "
   say "OVERRIDE EFF "'Feff' 'Feff' "/FEBE "'ifb'
   say " "
   say "and read in the skydip again, and calibrate it."
   return
endif
!
var prim   r
var array  r
var reduce r
var data   r
!
if jpix.ne.0 then
   npix = 1
else
   npix = febe'ifb'%header%febefeed
endif
!
define real raux /like data'ifb'%data%integnum
let raux data'ifb'%data%integnum
compute aux max raux 
let nrecords int(aux)
let nsubscan data'ifb'%data%subscan[nrecords]
define double mfitRes2[nsubscan]
!
define integer iStart[nsubscan] iEnd[nsubscan]
define double amDry[nsubscan] amWet[nsubscan]
define double xdata[nsubscan] ydata[nsubscan] yerr[nsubscan] 
define double dd /like ydata
define double tauDry tauWet
define double gi tcmb trx tatm tatms tatmi trss
!
let cEff 0.8 /new real
!
@ plotHeader "TIP" 'ifb'
!
dy = (mira_ymax-mira_ymin)/sqrt(npix)
dx = dy
!
let doHera = scan%data%fe[ifb].eq.50.or.scan%data%fe[ifb].eq.60
!
if doHera.and.npix.gt.1 then
   g\set expand 0.6
else
   g\set expand 0.8
endif
!
@ computeOffsets 'ifb' 0 'doHera'
!
!
define double rx /like data'ifb'%data%elevatio
define double ry[npix,nrecords] w[nrecords]
let rx data'ifb'%data%elevatio
!
if npix.ne.1 then
   for j 1 to npix           
       let ry[j,] = array'ifb'%data1%data[j,1,,1]
   next
else
   let ry[1,] array'ifb'%data1%data[jpix,1,,1]
endif
!
let calFlag reduce'ifb'%calibration_done[1]+reduce'ifb'%calibration_done[2] -
    /new integer
if calFlag.lt.2 then
   let ry ry*1.e-4
endif
!
for i 1 to nsubscan
    for j 1 to nrecords
        if data'ifb'%data%subscan[j].eq.i then
           let iStart[i] j
           break
        endif
    next
    for j nrecords to 1 by -1
        if data'ifb'%data%subscan[j].eq.i then
           let iEnd[i] j
           break
        endif
    next
    let k1 iStart[i] 
    let k2 iEnd[i]
    compute aux median data'ifb'%data%elevatio[k1:k2]
    let xdata[i] = aux ! Median elevation per subscan
next

!
g\set marker 32 3 .2
!
for k 1 to nsubscan
    let gamma pi/2.+xdata[k]*pi/180.
    let AM1 rEarth*cos(gamma)+sqrt((rEarth+hDry)**2-rEarth**2*(sin(gamma))**2)
    let AM2 rEarth*cos(gamma)-sqrt((rEarth+hDry)**2-rEarth**2*(sin(gamma))**2)
    let amDry[k] MAX(AM1,AM2)/hDry
    let amDry[k] = 1|sin(xdata[k]*pi|180) ! this is sufficiently accurate, CK
    let AM1 rEarth*cos(gamma)+sqrt((rEarth+hWet)**2-rEarth**2*(sin(gamma))**2)
    let AM2 rEarth*cos(gamma)-sqrt((rEarth+hWet)**2-rEarth**2*(sin(gamma))**2)
    let amWet[k] MAX(AM1,AM2)/hWet
next
!
!  This is a patch for Juan, to get an ASCII table of data pairs (amDry, ydata).
!
sic output tipData.dat
say "! scan "'scan%header%scannum'
say "! "'scan%header%date_obs'
say "! Column 1: airmass (dry atmosphere)."
say "! Column 2: skytip subscan mean values (as plotted)."
say "!"
!
let ipix 0 
!
for i 1 to npix
    ipix = ipix+1
    if npix.gt.1 then
       jpix = ipix
    endif
    say "!"
    say "! pixel "'jpix'
    say "!"
    for k 1 to nsubscan 
        let k1 iStart[k]
        let k2 iEnd[k]
        let w 0
        let w[k1:k2] 1. -
	            /where ry[ipix,k1:k2].ne.-1.e10.and.ry[ipix,k1:k2].ne.-1000.
        compute aux sum w
        let nsample aux
        mfit ry[ipix,]=&A /weight w /quiet
        let ydata[k] mfit%par[1] ! unchanged for sic output
        say 'amDry[k]' 'ydata[k]'
    next

    if i.eq.1 then
       limits 1 * * * /var amDry ydata /blanking blankingRaw 0. /xl /yl
    else
       limits 1 = < > /var amDry ydata /blanking blankingRaw 0. /xl /yl
    endif
next
!
sic output
!
let ipix 0

let tipScan scan%header%scannum /new integer

for i 1 to sqrt(npix)
    bxmin = mira_ymin+(i-1)*dx
    bxmax = bxmin+dx
    for j 1 to sqrt(npix) 
        ipix = ipix+1
        if npix.gt.1 then
           jpix = ipix
        endif
        bymin = mira_ymin+(j-1)*dy
	bymax = bymin+dy
        g\set box bxmin bxmax bymin bymax
        draw relocate 0.2 -0.5 /box 7 
        if doHera then
           label 'jpix' /center 6
           draw relocate 0.5 -0.5 /box 7 
        endif
        if exist(offset%off) then
	   if (offset%off%x[jpix].ge.0) then
	      label "Sky offset: ( " /center 6
	   else
	      label "Sky offset: (" /center 6
	   endif
	   label 'offset%off%x[jpix]' /center 6
	   if (offset%off%y[jpix].ge.0) then
	      label "\r`, " /center 6
	   else
	      label "\r`," /center 6
	   endif
	   label 'offset%off%y[jpix]' /center 6
	   label "\r`)" /center 6
	endif

        for k 1 to nsubscan 
            let k1 iStart[k]
            let k2 iEnd[k]
            let w 0
            let w[k1:k2] 1. /where ry[ipix,k1:k2].ne.-1.e10.and.ry[ipix,k1:k2].ne.-1000.
            compute aux sum w
            let nsample aux
            mfit ry[ipix,]=&A /weight w /quiet
            let ydata[k] mfit%par[1]

            let raux mfit%res^2
            compute aux sum raux[k1:k2]
            let yerr[k] sqrt(aux/(nsample-1))
        next
        if i.eq.1.and.j.eq.1 then
           box p o in 
           label "Airmass" /x
           g\set orient 90
           draw relocate -1.8 0 /box 4
	   label "T\dA [K]" /y ! /center 5 ! CK
           g\set orient 0
        else
	   box n n
        endif
        for k 1 to nsubscan
            g\draw marker amDry[k] ydata[k] /user
            g\errorbar y amDry[k] ydata[k] yerr[k]
        next
        
        let gi   febe'ifb'%data%gainimag[jpix,1]
!!        let trx  gains'ifb'%trx[1,jpix] AS 2015.05.04
        let trx  gains'ifb'%trx[jpix,1]
	let tcmb 2.73
	let trss = cEff*mon'ifb'%data%thotcold[1,1]+(1.-cEff)*(mon'ifb'%data%tamb_p_humid[1,1]+273.15)
        let tatms gains'ifb'%tatms[jpix,1] ! it is unclear how tatms and tatmi are calculated, ck
        let tatmi gains'ifb'%tatmi[jpix,1]
	let tatm = (tatms+gi*tatmi)/(1.+gi)
! Changes by CK:
        !pause " Plot of data done "
	say " Trx = "'trx'" Trss = "'trss'" Tatm = "'tatm'" Tcmb = "'tcmb' ! CK
        define real dum
        let dum = trss-tatm+(tatm-tcmb)      
        say " "'dum' ! 287K
        say " tauGuess = "'tauGuess'
! Original version of mfit:
   	  mfit ydata=trx+trss-&A*(trss-tatm+(tatm-tcmb)*exp(-&B*amDry))-
          /method r /eps 1e-9 /quiet /start 0.9,tauGuess /step 0.01,0.001

  	  let dd mfit%res^2 
	  compute sum sum dd
!	  let chisq1 sqrt(sum/(nsubscan-1.))
	  let chisq1 (sum/(nsubscan-2.))
          let dd mfit%fit
          pen 1; g\curve amDry dd; pen 0

          let feff1 = mfit%par[1]
          let tau1 = mfit%par[2]

! simple, new exponential fit of opacity ! cf. Chamberlin et al. 1997
!	  mfit ydata=&A-&B*exp(-&C*amDry)-
!          /method r /eps 1e-9 /quiet /start 200,150,tauGuess /step 0.01,0.001
          !aguess = trx+trss-0.9*trss+0.9*tatm
          !bguess = 0.9*(tatm-tcmb)
          aguess = 200. ! fits depend strongly on input guesses
          bguess = 150. ! this is *not* read into mfit !?!
	  mfit ydata=&A-&B*exp(-&C*amDry) /method r /start 200,150,tauGuess 

  	  let dd mfit%res^2 
	  compute sum sum dd
!	  let chisq2 sqrt(sum/(nsubscan-1.))
	  let chisq2 sum/(nsubscan-3.)
          let dd mfit%fit
          pen 3; g\curve amDry dd; pen 0

          say " Fit results: A, B, tau = "
          exa mfit%par
          let tau2 = mfit%par[3]
          let dum = mfit%par[1] ! A = Trx + (1-Feff) Trss + Feff Tatm
          let feff21 = (dum-trx-trss)|(tatm-trss)
          say " Feff21 = "'feff21'" (1st estimate) "
          let dum = mfit%par[2] ! B = Feff (Trss-Tcmb)
          let feff22 = dum|(tatm-tcmb)
          say " Feff22 = "'feff22'" (2nd estimate) "

! ---------------------------


        g\set coord user ! CK
        let xsta = -8
        let sta = 6.5
        let is = 1
        g\set expand 1
        g\draw text xsta+2.5 sta+1*is -
            "\gt\\dZ,guess\\u = "'nint(100.*tauGuess)/100.' /box 3
        for sel 1 to 2 by 1
          if (sel.eq.1) then
            pen 1
            g\draw text xsta sta-0*is "Full fit:" /box 3
            g\draw text xsta sta-1*is -
              "\gt\\dZ,fit\\u = "'nint(100.*tau1)/100.' /box 3
            g\draw text xsta sta-2*is -
              "F\de\df\df= "'nint(100.*feff1)/100.' /box 3
            g\draw text xsta sta-4*is -
              "\gc\u2 = "'nint(1000*chisq1)/1000' /box 3
            pen 0
          else if (sel.eq.2) then
            pen 3
            g\draw text xsta+5 sta-0*is "Simple fit:" /box 3
            g\draw text xsta+5 sta-1*is -
              "\gt\\dZ,fit\\u = "'nint(100.*tau2)/100.' /box 3
            !! All the Feff calculated with the 2nd method, are
            !! pretty wrong. It doesn't make much sense to show them
            !! other for checking and investigating.
            !g\draw text xsta+5 sta-2*is -
            !  "F\\deff,21\\u= "'nint(100.*feff21)/100.' /box 3
            !g\draw text xsta+5 sta-3*is -
            !  "F\\deff,22\\u= "'nint(100.*feff22)/100.' /box 3
            g\draw text xsta+5 sta-4*is -
              "\gc\u2 = "'nint(1000*chisq2)/1000' /box 3
            pen 0
          endif
	  compute azimuth mean mon'ifb'%data%encoder_az_el[,1]
          g\draw text xsta+2.5 sta-5*is -
              "Azimuth = "'nint(azimuth*10)/10.'"\uo" /box 3
        next ! sel

        if doHera.and.npix.gt.1 then
           g\set expand 0.6
        else
           g\set expand 0.8
        endif

    next ! sqrt(npix)
next ! sqrt(npix)
!
