;+
;
; Project   : s3drs reconstruction software
;                   
; Name      : make_tpxn_h
;               
; Purpose   : memory tools and Pixon 'syntax sugar' helper routines
;               
; Explanation: 
;               
; Use       : 
;    
; Inputs    : 
;               
; Outputs   : 
;
; Keywords  : 
;               
; Common    : 
;               
; Restrictions: none
;               
; Side effects: 
;               
; Category    : 
;               
; Prev. Hist. : None.
;
; Written     : Sandy Antunes, NRC, March-April 2009
;               
;-            
; $Id: make_tpxn_h.pro,v 1.1 2009/04/22 18:32:33 antunes Exp $
;+
; <p> The first sentence summarizes the documentation.
;
; <p> It is followed by a more detailed description.  Paragraphs should be
;    hung-indented as in this example.
;
; <p> Modify the author tag as appropriate.  Other tags follow the author tag.
;    See IDLDOC_FILES.HTML for a complete list of tags.
;
; @copyright
;    Copyright © Pixon LLC, 1999-2004.  All rights reserved.
;    Unauthorized reproduction prohibited.
; @author
;    <a href="mailto:Amos.Yahil\@Pixon.com">Amos Yahil, Pixon LLC.</a>
;-

                                ; Compilation options
   COMPILE_OPT IDL2, HIDDEN, STRICTARRSUBS
                                ; Initialization
   IF N_ELEMENTS(dim) EQ 0 THEN			dim = 32
   IF N_ELEMENTS(display) EQ 0 THEN		display = 1
   IF N_ELEMENTS(mxit) EQ 0 THEN		mxit = 30
   IF N_ELEMENTS(ndata) EQ 0 THEN		ndata = 2	; frames
   IF N_ELEMENTS(npersp) EQ 0 THEN		npersp = 5	; 
   IF N_ELEMENTS(npol) EQ 0 THEN		npol = 2	; # polarizations
   IF N_ELEMENTS(nview) EQ 0 THEN		nview = 2	; # satellites
   IF N_ELEMENTS(reltol) EQ 0 THEN		reltol = 1e-4	; 
   IF N_ELEMENTS(seed0) EQ 0 THEN		seed0 = LONG(SYSTIME(1))	;
   IF N_ELEMENTS(snr) EQ 0 THEN			snr = 30.0 			; snr for constant gaussian noise
   IF N_ELEMENTS(theta) EQ 0 THEN		theta = [-40,55]		; satellite angles
   IF N_ELEMENTS(tiff) EQ 0 THEN		tiff = 0			; tiff output
   IF N_ELEMENTS(wait) EQ 0 THEN		wait = 1.0/30			; wait between movie frames
                                ; Derived parameters
   IF KEYWORD_SET(cpu) THEN BEGIN	; timing debug
      display = 0
      seed0 = 1235711
   ENDIF
   ddim = REPLICATE(dim, 2)
   idim = REPLICATE(dim, 3)
   seed = seed0
                                ; Truth image, full resolution

   shmmap,DIMENSION=idim,get_name=segname,/DOUBLE
   r=shmvar(segname)
   shmmap,DIMENSION=idim,get_name=segname,/DOUBLE
   true=shmvar(segname);

   r = SQRT(NDQF(idim))

   true = snr*(r GT 0.25*dim AND r LT 0.375*dim)
   true[*,0:ddim[0]/2-1,*] = 0
   vrtx = Coord(idim) - dim/2	; vertex positions
   nvrtx = N_ELEMENTS(vrtx)/3	; # vertices
                                ; Pointer arrays
   cpol = PTRARR(nview)		; polarization coefficients
   data = PTRARR(ndata,nview)	; input data 
   ihat = PTRARR(nview)
;   jhat = PTRARR(nview)
   khat = PTRARR(nview)
   persp = FLTARR(nview)
   pos = PTRARR(nview)
                                ; Loop on views
   FOR iv=0,nview-1 DO BEGIN
                                ; Tomographic parameters
      dtor = !DPI/180
      ihat[iv] = PTR_NEW([- SIN(dtor*theta[iv]), COS(dtor*theta[iv]), 0], $
                         /NO_COPY)
;       jhat[iv] = PTR_NEW([0, 0, 1], /NO_COPY)
      khat[iv] = PTR_NEW([COS(dtor*theta[iv]), SIN(dtor*theta[iv]), 0], $
                         /NO_COPY)
      persp[iv] = npersp*dim
      pos[iv] = PTR_NEW( -persp[iv]*(*khat[iv]), /NO_COPY)
                                ; Polarization coefficients
      cpol[iv] = PTR_NEW([[1.0,0.0],[0.0,1.0]]^2)
                                ; Polarization emissivities
                                ; Data frames
      FOR n=0,ndata-1 DO BEGIN
                                ; Noise introduced as initial data
         data[n,iv] = PTR_NEW(RANDOMN(seed, ddim), /NO_COPY)	;
      ENDFOR
   ENDFOR
                                ; TPixon object
   tmake = SYSTIME(1)
   oTPixon = OBJ_NEW('TPixon', cpol=cpol, data=data, ihat=ihat, image=true, $
                     jhat=jhat, khat=khat, mxit=mxit, npol=npol, persp=persp, $
                     pos=pos, reltol=reltol, sigma=1.0, vrtx=vrtx)
                                ; Compute the data model inside the TPIXON
                                ; object and add it to the data
   dm = oTPixon -> Get(/DM)	; data model
   FOR iv=0,nview-1 DO BEGIN
      FOR n=0,ndata-1 DO BEGIN
         *data[n,iv] = (*data[n,iv]) + (*dm[n,iv])	; to be sure we calculate same as code
      ENDFOR
   ENDFOR
   PRINT, 'OTPIXON CREATION CPU', SYSTIME(1) - tmake
                                ; Check for consistency
   oTPixon -> Check
                                ; Residuals and chi^2
   chi2 = oTPixon -> Chi2(/TOTAL)
   dof = oTPixon -> Get(/DOF)
   PRINT, 'CHI2, Q', chi2, (chi2 - dof)/SQRT(2*dof)
   oTPixon -> Replace, image=PTR_NEW(FLTARR(nvrtx), /NO_COPY)	; replace image with  zeroes
   oTPixon -> DM
   chi2 = oTPixon -> Chi2(/TOTAL)	; bad chi2
   dof = oTPixon -> Get(/DOF)
   PRINT, 'CHI2, Q', chi2, (chi2 - dof)/SQRT(2*dof)
                                ; 3-D visualization of the truth model
   IF KEYWORD_SET(display) THEN BEGIN
      start = MIN(vrtx, max=delta) - 2.0
      delta = (delta - start + 2.0)/(dim - 1)
      ph = oTPixon -> Get(/PH, /NOPOINTER)
      ttrue = QGRID3(vrtx, true, ph, delta=delta, dimension=dim, start=start)
      PXNdisp, ttrue, $
               title='Input_Electron_Density_X-Y', wait=wait, $
               /BAR, /DW, /FREE, TIFF=tiff
      PXNdisp, ttrue, 1, 3, ll=[0,dim/2-3,0], $
               title='Input_Electron_Density_X-Z', wait=wait, $
               /BAR, TIFF=tiff
      XVOLUME, BYTSCL(ttrue)
   ENDIF
   STOP
                                ; Run Pseudo with the full grid
   oTPixon -> Pseudo
   STOP
                                ; Delete the truth image and vertex structure
   oTpixon -> Free, /BOUNDS, /CONNECT, /FDX, /FPMT, /IMAGE, /JPOL, /PH, /SDX, $
                    /SPMT, /VRTX
                                ; Save the OTPIXON object for use with run_tpxn
   SAVE, oTPixon, file='otpixon_' + STRTRIM(dim, 2) + '.idl'
                                ; Done
END
