Subs::UvotCoords (version $)


package Subs::UvotCoords;
##############################################################################
#
# DESCRIPTION: This subroutine runs the XRT tools delivered in build 1
# Currently just does the coordinate transforms by calling
# Coordinates::event_transforms.  No longer sets ATTFLAG in the unfiltered
# *po files, let SW0WrapUp take care of that.
#
# HISTORY:
# HISTORY: $Log: UvotCoords.pm,v $
# HISTORY: Revision 1.14  2014/02/28 11:09:43  apsop
# HISTORY: No longer sets ATTFLAG keywords (leaves that for SW0WrapUp).
# HISTORY: Chooses appropriate attitude file and passes it to event_transforms.
# HISTORY:
# HISTORY: Revision 1.13  2011/01/20 18:02:38  apsop
# HISTORY: Added code to use UVIT attitude file if available
# HISTORY:
# HISTORY: Revision 1.12  2007/09/28 17:14:48  apsop
# HISTORY: Change writing of ATTFLAG keyword so that it is a string rather than an integer.
# HISTORY:
# HISTORY: Revision 1.11  2007/09/19 15:03:56  apsop
# HISTORY: Check if jump corrected attitude file really exist before using it.
# HISTORY:
# HISTORY: Revision 1.10  2007/09/11 18:11:30  apsop
# HISTORY: Use jump corrected attitude file for uvot event data processing.
# HISTORY:
# HISTORY: Revision 1.9  2005/11/14 15:34:03  apsop
# HISTORY: Move the event splitting into a separate subroutine, which is not being called for now.
# HISTORY:
# HISTORY: Revision 1.8  2005/11/08 19:58:40  apsop
# HISTORY: <Previous comment bogus>Calculate start, stop, and ontimes for GTIs when the uvot event lists get split by s/c mode.
# HISTORY:
# HISTORY: Revision 1.7  2005/11/08 19:22:28  apsop
# HISTORY: Populate the TIMELIST and DATALIST hashes. Used to be an SWCheckInput.
# HISTORY:
# HISTORY: Revision 1.6  2005/09/26 21:00:30  apsop
# HISTORY: split UVOT event lists into pointing and slewing.
# HISTORY:
# HISTORY: Revision 1.5  2004/05/06 20:02:34  dah
# HISTORY: Add version number back into the header comments.
# HISTORY:
# HISTORY: Revision 1.4  2004/04/16 20:21:18  dah
# HISTORY: Begin using embedded history records
# HISTORY:
#
# VERSION: $Revision: 1.14 $
#
##############################################################################


use Subs::Sub;
use Subs::Coordinates;

@ISA = ("Subs::Coordinates");
use strict;

sub new {
    my $proto=shift;
    my $self=$proto->SUPER::new();

    $self->{DESCRIPTION}="Doing UVOT coordinate transforms";

    return $self;
}

##################
# METHODS:
##################

sub body {
    my $self=shift;

    my $log     =$self->log();
    my $filename=$self->filename();
    my $procpar =$self->procpar();
    my $jobpar  =$self->jobpar();

    my $coordParams;

    ##########################################################################
    # Look for attitude file.  uat if have it, else pat, else sat, else "NONE"
    ##########################################################################
    my $attfile = $filename->get('attcorr', 'u');
    if (-e $attfile) {
	$log->entry("Got uat attitude file $attfile");

    } else {
	$log->error(1, "$attfile uat attitude file does not exist, trying pat file");
	$attfile = $filename->get('attcorr', 'p');

	if (-e $attfile) {
	    $log->entry("Got pat attitude file $attfile");

	} else {
	    $log->error(1, "$attfile pat attitude file does not exist, trying sat file");
	    $attfile = $filename->get('attitude', 's');

	    if (-e $attfile) {
		$log->entry("Got sat attitude file $attfile");
	    } else {
		$log->error(1, "Unable to find attitude file, using NONE");
		$attfile="NONE";
	    }
	}
    }
    $coordParams = {attfile => $attfile};

    ############
    # Got milk?
    ############
    $self->event_transforms('uvot', ['*'], $coordParams);

} # end of body method


sub split_events {
    my $self=shift;

    my $log     =$self->log();
    my $filename=$self->filename();
    my $procpar =$self->procpar();
    my $jobpar  =$self->jobpar();

    #####################################################################
    # Seperate out events in s/c pointing mode and s/c settling mode
    # into seperate files.  In this context, everything not in pointing
    # mode is considered in settling mode.
    #####################################################################
    my $point_gti = $filename->get('gti', 's', 'po', '*');
    my $point_start = Util::FITSfile->new($point_gti, 1)->keyword('TSTART');
    my $not_gti = $filename->get('gti', 's', 'np', '*');
    my $tmp = 'uvot_uf.tmp';
    my $tmpgti = 'uvot_gti.tmp';
    unlink $tmp, $tmpgti;

    foreach my $file ($filename->get('unfiltered', 'uvot', '*po', '*')) {
      $log->entry("Checking $file for settling exposures.");

      my $fits = Util::FITSfile->new($file, 'WINDOW');
      my @starts = $fits->cols("START")->table();
      my @refs = $fits->cols("EXPREF")->table();
      my @strefs;
      for(my $ngti=0; $ngti < @starts; $ngti++){
	push @strefs, $refs[$ngti]
	  if $starts[$ngti] < $point_start;
      }

      if(@strefs){
	my ($inst, $mode, $index) = $filename->parse($file, 'unfiltered');
	$mode =~ s/po$/st/;
	my $stfile = $filename->get('unfiltered', 'uvot', $mode, $index);

	if( @strefs == @refs ){
	  $log->entry("All exposures during settling.  Rename file to $stfile.");
	  rename $file, $stfile;
	  next;
	}

	$log->entry("Extracting settling exposures ". join(',', @strefs)
		    ." to $stfile.");
	my @filt_refs = @strefs;
	map $_= 'gtifilter(\'[GTI'. $_ .']\')' , @filt_refs;
	my $spec = '['. join('&&', @filt_refs) .']';
	$fits->ext('EVENTS');
	$fits->specs($spec);
	$fits->copy($stfile);

	my $deldhu = Util::HEAdas->new('ftdelhdu')
	                         ->params({outfile => 'none',
					   confirm => 'yes',
					   clobber => 'yes'});

	my (@st_rows, @po_rows);
	my $nrow=0;
	foreach my $ref (@refs){
	  $nrow++;
	  if( grep($_==$ref, @strefs) ){
	    $deldhu->params({infile => $file ."[GTI$ref]"})
	           ->run();
	    push @st_rows, $nrow;
	  }else{
	    $deldhu->params({infile => $stfile ."[GTI$ref]"})
	           ->run();
	    push @po_rows, $nrow;
	  }
	}

	my $delrow = Util::HEAdas->new('ftdelrow')
	                         ->params({outfile => 'none',
					   confirm => 'yes',
					   clobber => 'yes'});

	$delrow->({infile => $stfile .'[WINDOW]',
		   rows => join(',', @po_rows)})
	       ->run();

	$delrow->({infile => $file .'[WINDOW]',
		   rows => join(',', @st_rows)})
	       ->run();
      }
##      $fits->specs('[gtifilter(\''. $point_gti .'\')]');
##      $fits->copy($tmp);
##      my $tmpfits = Util::FITSfile->new($tmp, 'EVENTS');
##      my $nevents_point = $tmpfits->nrows();
##
##      if($nevents_point == $nevents){
##        unlink $tmp;
##        next;
##      }
##      if($nevents_point == 0){
##        unlink $tmp;
##        rename $file, $stfile;
##        next;
##      }
##
##      $fits->specs('[gtifilter(\''. $not_gti .'\')]');
##      $fits->copy($stfile);
##
##      $fits->specs('');
##      #######################################
##      # Update GTIs for newly filtered files
##      #######################################
##      my $delhdu = Util::Ftool->new('fdelhdu')
##                              ->params({confirm => 'no',
##					proceed => 'yes'});
##     my $mgtime = Util::Ftool->new('mgtime')
##	                      ->params({outgti => $tmpgti,
##					merge => 'AND'});
##
##      my $append = Util::HEAdas->new('ftappend');
##
##      my $hdu=2;
##      while($hdu < $tmpfits->nhdus()){
##	$tmpfits->ext($hdu);
##	my $name = $tmpfits->keyword('EXTNAME');
##	if($name =~ /^GTI/){
##	  $delhdu->params({infile => $tmp."[$name]"})->run();
##	  $delhdu->params({infile => $stfile."[$name]"})->run();
##	}else{
##	  $hdu++;
##	}
##      }
##
##      my $nhdus = $fits->nhdus();
##      for($hdu=2; $hdu<$nhdus; $hdu++){
##	$fits->ext($hdu);
##	my $name = $fits->keyword('EXTNAME');
##	if($name =~ /^GTI/){
##	  $mgtime->params({ingtis => $file."[$name] ".$point_gti})
##	         ->run();
##	  $append->params({infile => $tmpgti."[STDGTI][col #EXTNAME = '$name']",
##			   outfile => $tmp})
##	         ->run();
##         unlink $tmpgti;
##
##	  $mgtime->params({ingtis => $file."[$name] ".$not_gti})
##	         ->run();
##	  $append->params({infile => $tmpgti."[STDGTI][col #EXTNAME = '$name']",
##			   outfile => $stfile})
##	         ->run();
##          unlink $tmpgti;
##
##	  for my $gtifile ($stfile, $tmp){
##	    my $gtifits = Util::FITSfile->new($gtifile);
##	    my $lasthdu = $gtifits->nhdus()-1;
##	    $gtifits->ext($lasthdu);
##	    my ($ontime, $start, $stop) = (0, 1E10, 0);
##	    my %intervals = $gtifits->cols("START", "STOP")->table();
##	    foreach (keys %intervals ) {
##	      $start = $_ if $_ < $start;
##	      $stop = $intervals{$_} if $intervals{$_} > $stop;
##	      $ontime += $intervals{$_} - $_;
##	    }
##	    $start = $stop = $point_start unless ($ontime);
##	    $gtifits->keyword('TSTART', $start);
##	    $gtifits->keyword('TSTOP', $stop);
##	    $gtifits->keyword('ONTIME', $ontime);
##	  }
##	}
##      }
##
##      unlink $file;
##      rename $tmp, $file;
    }

}

1;