#!/usr/bin/perl
#
# $Name:  $
#
# $Log: welch.pl,v $
# Revision 1.5  2003/06/07 23:27:57  robert
# Fix a really odd implementation...
#
# Revision 1.4  2003/05/09 04:15:27  robert
# Minor changes before it gets fixed...
#
# Revision 1.3  2002/06/12 14:44:59  robert
# Update to work with new DB schema
#
# Revision 1.2  2001/11/23 16:23:57  robc
# Make work correctly and speed optimize.
#

use warnings;
use strict;

use DBI;
use IO;

STDOUT->autoflush;

use constant MAG_STEP => .1;

sub done;
$SIG{ INT } = \&done;

my $ID = q$Id: welch.pl,v 1.5 2003/06/07 23:27:57 robert Exp $;
my $version = join (' ', (split (' ', $ID))[1..3]);
$version =~ s/,v\b//;
$version =~ s/(\S+)$/($1)/;

my $dbh =
   DBI->connect( "DBI:Pg:dbname=tassiv", "", "",
                 { RaiseError => 1, AutoCommit => 0 } );

my $sth_welch_data_select =
   $dbh->prepare( "SELECT star_id FROM welch_data" );

print "\n";
{
   $dbh->{ PrintError } = 0;
   $dbh->do( "CREATE TEMP TABLE welch_data( id INT4, star_id INT4,"
             . " mag1 float, smag1 float,"
             . " mag2 float, smag2 float )" );
}
print "Gathering paired observational data... ";
my $sql = <<__END_SQL__;
INSERT INTO welch_data( star_id,
       mag1, smag1, mag2, smag2
       )
SELECT i.star_id, i.mag, i.smag, v.mag, v.smag
FROM (SELECT star_id, mag, smag, pair_id, date
      FROM obs_i NATURAL JOIN files
      WHERE  use = true
     ) AS i,
     (SELECT star_id, mag, smag, pair_id
      FROM obs_v NATURAL JOIN files
      WHERE  use = true
     ) AS v
WHERE  i.pair_id = v.pair_id
   AND i.star_id = v.star_id
__END_SQL__

$dbh->do( $sql );
$dbh->do(
  "CREATE INDEX welch_data_star_id_index ON welch_data USING btree( star_id )" );

$sth_welch_data_select->execute;
printf " %d pairs\n", $sth_welch_data_select->rows;
$sth_welch_data_select->finish;

print "Calculating averages...";
$sql = <<__END_SQL__;
SELECT star_id,
       count( star_id ),
         sum( mag1 / (smag1^2+0.01^2) )
       / sum(    1 / (smag1^2+0.01^2) )
       AS v_avg,
         sum( mag2 / (smag2^2+0.01^2) )
       / sum(    1 / (smag2^2+0.01^2) )
       AS i_avg
INTO TEMP TABLE welch_avg
FROM welch_data
GROUP BY star_id
__END_SQL__
$dbh->do( $sql );

$dbh->do( "DELETE FROM welch_index" );

print "\nCalculating W-S index...";
$sql = <<__END_SQL__;
INSERT INTO welch_index( star_id, index, updated )
SELECT star_id,
         sum(  (mag1 - v_avg) / sqrt( smag1^2 + 0.01^2 )
             * (mag2 - v_avg) / sqrt( smag2^2 + 0.01^2 ) )
         / sqrt( count( star_id ) * (count( star_id ) - 1) ) AS ws,
         TRUE
FROM welch_data NATURAL JOIN welch_avg
WHERE welch_avg.count > 10
GROUP BY star_id
__END_SQL__
$dbh->do( $sql );

# INTO TEMP TABLE welch_residuals

print "\nUpdating welch_index table...";
$sql = <<__END_SQL__;
INSERT welch_index
SET updated = TRUE,
    index = ws
FROM welch_residuals AS wr
WHERE welch_index.star_id = wr.star_id
__END_SQL__
#$dbh->do( $sql );
print "\n";

$dbh->commit;
$dbh->disconnect;
