; Computes and optionally applys alignment parameters
;
; SOURCE: apshgrp.spi   New                               Nov 2004 ArDean Leith
;                       Rewritten                         Feb 2005 ArDean Leith
;                       Added alignment option & stack op Nov 2006 ArDean Leith
;                       SET MP location                   Feb 2008 ArDean Leith
;
; PURPOSE: Multi-reference alignment of an image series. 
;          Sample images are aligned with reference projections via
;          shifts (translations) and rotations.  
;          FOR PROJECTS WITH MULTIPLE GROUPS- WITH OR WITHOUT PUBSUB.
;
; MASTER COPY: /net/bali/usr1/spider/docs/techs/recon/newprogs/
;
;------------ Edit next 6 Input parameters ------------------------------ 

[pubsub]  = 0   ; If >0 use PubSub
[doalign] = 1   ; If >0 apply alignment to images

[range]   = 8   ; Translation search range (must be divisible by step size)
[step]    = 2   ; Translation step size

[diam]    = 276 ; Diameter of object (Angstroms) for alignment search.
                ;   (EDIT as needed!) Used to find last alignment radius.

[r1]      = 5   ; First rotation alignment ring, only radii > this will be analyzed
[r2]      = 0   ; Last rotation ring (If zero, compute from object diameter)

; ----------------- Input files --------------------------------------------

FR G
[parameters]../params                    ; Parameter setting file

FR G                                     
[defgrps]../Reconstruction/sel_group     ; List of groups (group selection doc file)

FR G
[ref_images]projs/prj_{***[grp]}@        ; Reference image name  

FR G
[ref_images_angles]refangles             ; Reference images angles doc. file

FR G
[unaligned_images]data{***[grp]}@        ; Unaligned particles stacks

; ----------------- Output files ------------------------------------------------

FR G
[align_parameters]align_01_{***[grp]}    ; Alignment parameters doc. file 

FR G
[aligned_images]dala01_{***[grp]}@       ; Rotated, shifted (aligned) particles

; ----------------- END BATCH HEADER ------------------------------------------- 

MD
TR OFF                                ; Decrease results file output
MD
VB OFF                                ; Decrease results file output

; DO NOT WORRY IF [grp] IS UNDEFINED HERE, IT IS TAKEN CARE OF BY PUBSUB
IF ([grp] .GT. 0) [pubsub] = 0        ; Secondary PubSub run 

UD N [numgrps]                        ; Get number of groups 
[defgrps]                             ; Groups selection file           (input)

IF ([pubsub] .EQ. 0) THEN             ; Main loop runs 'AP SH'
                                      ; Used for Non-PubSub and PubSub runs 
  
   MD                 
   SET MP                             ; Use all processors (needed here for secondary runs)
   0

   IF ([r2].LE.0) THEN                ; Compute alignment radius from object size  
      UD 5,[pxsz]                     ; Get pixel size (A) from this file
      [parameters]
 
      UD 17,[winsz]                   ; Get window size (pixels) from this file
      [parameters]

      [r2] = INT([diam]/(2.0*[pxsz])) ; Compute object radius (pixels) for last alignment ring
      [tp] = [r2] + [range]           ; Compute last ring + translation range
      [t]  = INT([winsz]/2) - 1       ; Compute max. radius of object within window

      IF ([tp] .GE. [t]) THEN
         [r2] = [t] - [range] - 1     ; Reduce radius of last alignment ring to fit window
      ENDIF
   ENDIF

   IF ([grp] .GT. 0) [numgrps] = 1    ; Group listed on command line, overides list        

   DO LB2 [numgrp]=1,[numgrps]        ; Loop over all group(s)

      IF ([grp] .LT. 1) THEN          ; Group not on command line, use list from selection file        
         UD [numgrp],[grp]            ; Get current group number 
         [defgrps]                    ; Group selection file                  (input)
      ENDIF

      DE                              ; Delete existing  output doc. files.
      [align_parameters]
 
      FI X [numpart]                  ; Get number of particles 
      [unaligned_images]              ; Unaligned particles name template      (input)
      (26)                            ; Max. image number in stack      

      FI X [numproj]                  ; Get number of projections 
      [ref_images]                    ; Unaligned particles name template      (input)
      (26)                            ; Max. image number in stack      

      VM
      echo ' 'Aligning group: {****[grp]} with: {******[numpart]} particles  

      AP SH                           ; Find Alignment using multiple references  
      [ref_images]*****               ; Reference image file name template     (input)
      (1-[numproj])                   ; List of reference images       
      [range],[step]                  ; Search range, step size  
      [r1],[r2]                       ; First and last ring      
      [ref_images_angles]             ; Ref. angles doc file                   (input)
      [unaligned_images]*****         ; Unaligned particles file name template (input)
      (1-[numpart])                   ; Number of particles  
      *                               ; No unaligned particles align. doc file        
      (0)                             ; No restriction on angular proj. search 
      (1)                             ; Check mirrored positions
      [align_parameters]              ; Alignment angles doc. file            (output)

      IF ([doalign] .GT. 0) THEN
         ; Apply alignment parameters to unaligned particles
         ; Order in doc file: PHI,THETA,PSI, REF#,IMG#,  ROT,SX,SY

         RT SQ                        ; Rotate & shift whole stack operation
         [unaligned_images]           ; Unaligned particles stack             (input) 
         [aligned_images]             ; Aligned particles stack               (output)
         (6,0,7,8)                    ; Reg. numbers for angle, scale,& shifts
         [align_parameters]           ; Alignment angles doc. file            (input)
      ENDIF

      MY FL                           ; Flush results file
      [grp] = 0                       ; Reset default group for next group
   LB2                                ; End loop for multiple groups
    
ELSE                                  ; Used only to intiate master PubSub run 
   DO LB3 [numgrp]=1,[numgrps]        ; Loop over all groups
   
       UD [numgrp],[grp]              ; Get current group number 
       [defgrps]                      ; Group selection file                   (input)
   
       ; Create parallel PubSub run for each group
       VM                             ; Use PubSub to create parallel processes   
       publish './spider spi/$DATEXT @apshgrp {***[grp]} grp={***[grp]}'
    LB3
ENDIF

EN                              

;