IPP Software Navigation Tools IPP Links Communication Pan-STARRS Links

Changeset 23352


Ignore:
Timestamp:
Mar 17, 2009, 12:08:50 PM (17 years ago)
Author:
beaumont
Message:

merged with head

Location:
branches/cnb_branches/cnb_branch_20090301
Files:
27 deleted
298 edited
60 copied

Legend:

Unmodified
Added
Removed
  • branches/cnb_branches/cnb_branch_20090301

  • branches/cnb_branches/cnb_branch_20090301/Nebulous-Server/MANIFEST

    r20990 r23352  
    1010bin/neb-voladd
    1111bin/nebdiskd
    12 docs/c_api.h
    1312docs/database_setup.txt
    1413docs/design.txt
     14docs/install.txt
    1515docs/requirements.txt
    16 docs/setup.txt
    17 docs/tmp.txt
    1816examples/Makefile
    1917examples/nebexample.c
  • branches/cnb_branches/cnb_branch_20090301/Nebulous-Server/bin/neb-admin

    r20202 r23352  
    2323    $dbpass,
    2424    $dbuser,
     25    $so_id_start,
     26    $so_id_range,
    2527    $limit,
    2628    $pending,
     
    4143    'pendingreplicate|r'    => \$pending,
    4244    'pendingremoval'        => \$removal,
     45    'so_id_start=i'         => \$so_id_start,
     46    'so_id_range=i'         => \$so_id_range,
    4347    'limit|l=i'             => \$limit,
    4448    'verbose|v'             => \$verbose,
     
    5862
    5963# check to make sure that only one instance of neb-admin is running
     64# XXX this implies we should move pending replicate elsewhere
    6065my $pidfile = '/var/tmp/neb-admin';
    6166# abort if an instance is already running
     
    9196    $dbh->do("INSERT INTO myvolume SELECT * FROM volume");
    9297
     98    if (not defined $so_id_start) { $so_id_start = 0; }
     99    if (not defined $so_id_range) { $so_id_range = 100000; }
     100    my $so_id_end = $so_id_start + $so_id_range;
     101
     102    # XXX check if so_id_start is beyond MAX(so_id): if so, exit with exit status 10
     103    {
     104        my $query = $dbh->prepare("SELECT MAX(so_id) from storage_object");
     105        $query->execute;
     106        my $answer = $query->fetchrow_arrayref;
     107        my $max_so_id = $$answer[0];
     108        $query->finish;
     109
     110        if ($so_id_start > $max_so_id) {
     111            print STDERR "at end of so_id range, reset please\n";
     112            exit 10;
     113        }
     114    }
     115       
    93116    my $query = $dbh->prepare(
    94117    "        SELECT
     
    111134                USING(vol_id)
    112135            WHERE mymountedvol.available = 1
    113     --        WHERE storage_object_xattr.name = 'user.copies'
     136            AND storage_object_xattr.name = 'user.copies'
     137            AND storage_object.so_id >= $so_id_start
     138            AND storage_object.so_id <  $so_id_end
    114139            GROUP BY so_id
    115140            HAVING available_instances < instances OR instances < copies
  • branches/cnb_branches/cnb_branch_20090301/Nebulous-Server/bin/neb-voladd

    r19797 r23352  
    7979=head1 SYNOPSIS
    8080
    81     neb-voladd --volume <volume name> --uri <volume uri>
     81    neb-voladd --vname <volume name> --vhost <host name> --uri <volume uri>
    8282    [--db <database>] [--user <username>] [--pass <password>] [--host <hostname]
    8383
     
    9292=over 4
    9393
    94 =item * --volume <volume name>
     94=item * --vname <volume name>
    9595
    9696Symbolic name of volume being added.
     97
     98=item * --vhost <host name>
     99
     100Name of the host that containes the C<URI> of the volume being added.
    97101
    98102=item * --uri|-u <volume uri>
  • branches/cnb_branches/cnb_branch_20090301/Nebulous/Build.PL

    r20131 r23352  
    1111my $pkg_dir = "./nebclient";
    1212
    13 sub ACTION_code {
    14     my $self = shift;
    15 
    16     $self->SUPER::ACTION_code(@_);
    17 
    18     my $old_pwd = getcwd();
    19     chdir $pkg_dir;
    20 
    21     unless (-e "configure") {
    22         system("./autogen.sh") == 0 or die "install failed: $?";
    23     }
    24 
    25     chdir $old_pwd;
    26 }
    27 
    28 sub ACTION_build {
    29     my $self = shift;
    30 
    31     $self->SUPER::ACTION_build(@_);
    32 
    33     my $old_pwd = getcwd();
    34     chdir $pkg_dir;
    35 
    36     unless (-e "Makefile") {
    37         system("sh ./configure") == 0 or die "build failed: $?";
    38     }
    39 
    40     system("make") == 0 or die "build failed: $?";
    41 
    42     chdir $old_pwd;
    43 }
    44 
    45 # Do not attempt to install nebclient.  It is bundled in this package for
    46 # testing only.
    47 #
     13# sub ACTION_code {
     14#     my $self = shift;
     15#
     16#     $self->SUPER::ACTION_code(@_);
     17#
     18#     my $old_pwd = getcwd();
     19#     chdir $pkg_dir;
     20#
     21#     unless (-e "configure") {
     22#         system("./autogen.sh") == 0 or die "install failed: $?";
     23#     }
     24#
     25#     chdir $old_pwd;
     26# }
     27#
     28# sub ACTION_build {
     29#     my $self = shift;
     30#
     31#     $self->SUPER::ACTION_build(@_);
     32#
     33#     my $old_pwd = getcwd();
     34#     chdir $pkg_dir;
     35#
     36#     unless (-e "Makefile") {
     37#         system("sh ./configure") == 0 or die "build failed: $?";
     38#     }
     39#
     40#     system("make") == 0 or die "build failed: $?";
     41#
     42#     chdir $old_pwd;
     43# }
     44#
    4845# sub ACTION_install {
    4946#     my $self = shift;
     
    5855#     chdir $old_pwd;
    5956# }
    60 
    61 sub ACTION_clean {
    62     my $self = shift;
    63 
    64     $self->SUPER::ACTION_clean(@_);
    65 
    66     my $old_pwd = getcwd();
    67     chdir $pkg_dir;
    68 
    69     system("make clean") == 0 or die "install failed: $?";
    70 
    71     chdir $old_pwd;
    72 }
     57#
     58# sub ACTION_clean {
     59#     my $self = shift;
     60#
     61#     $self->SUPER::ACTION_clean(@_);
     62#
     63#     my $old_pwd = getcwd();
     64#     chdir $pkg_dir;
     65#
     66#     system("make clean") == 0 or die "install failed: $?";
     67#
     68#     chdir $old_pwd;
     69# }
    7370EOF
    7471
  • branches/cnb_branches/cnb_branch_20090301/Nebulous/MANIFEST

    r20131 r23352  
    2020bin/neb-touch
    2121bin/neb-xattr
    22 docs/c_api.h
    23 docs/database_setup.txt
    24 docs/design.txt
    25 docs/requirements.txt
    26 docs/setup.txt
    27 docs/tmp.txt
    2822examples/Makefile
    2923examples/nebexample.c
  • branches/cnb_branches/cnb_branch_20090301/Nebulous/nebclient/src

    • Property svn:ignore
      •  

        old new  
         1Makefile.in
        12.deps
         3Makefile
         4soapClientLib.c
         5nebulous.h
         6soapClient.c
         7soapStub.h
         8soapC.c
         9soapH.h
         10soapServerLib.c
         11soapServer.c
        212.libs
        3 Makefile
        4 Makefile.in
        5 SOAP.nsmap
        6 libnebclient.la
        7 nebclient.lo
        8 nebulous.h
        9 soapC.c
        10 soapC.lo
        11 soapClient.c
        12 soapClient.lo
        13 soapClientLib.c
        14 soapH.h
        15 soapServer.c
        16 soapServerLib.c
        17 soapStub.h
        18 stdsoap2.lo
        19 xmalloc.lo
  • branches/cnb_branches/cnb_branch_20090301/Nebulous/nebclient/tests/tap/src

    • Property svn:ignore
      •  

        old new  
        66.deps
        77Makefile
         8.libs
  • branches/cnb_branches/cnb_branch_20090301/Nebulous/scripts/ptest.pl

    r21545 r23352  
    55
    66use lib "./lib";
     7package main;
    78
    8 use Nebulous::Client;
     9#use Nebulous::Client;
    910use IO::Select;
    1011use IO::Socket;
     12use POSIX qw(:DEFAULT :sys_wait_h);
     13use Hook::LexWrap;
     14use Sys::Hostname;
    1115
    12 my $neb = Nebulous::Client->new(
    13 #    proxy   => 'http://localhost:80/nebulous'
    14     proxy   => 'http://alala:80/nebulous'
    15 );
     16my $print_stdout = undef;
     17
     18$| = 1;
    1619
    1720my $key = shift || 'foobar';
    1821my $kids = shift || 1;
    1922
    20 my $s = IO::Select->new();
     23$key = "/tmp/" . $key;
     24
     25#my $s = IO::Select->new();
    2126
    2227foreach my $id ( 1..$kids ) {
    23     my ($sock_parent, $sock_child) = IO::Socket->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
    24     $s->add($sock_parent);
     28#    my ($sock_parent, $sock_child) = IO::Socket->socketpair(AF_UNIX, SOCK_STREAM, PF_UNSPEC);
     29#    $s->add($sock_parent);
    2530
    2631    my $pid = fork;
    2732
    2833    unless ( $pid )  {
     34        # child
     35        my $sock_child = \*STDOUT;
    2936        child($sock_child, $id);
     37        shutdown($sock_child, 2);
    3038        exit 0;
    3139    }
     
    3341}
    3442
    35 while ($kids) {
    36     foreach my $child ($s->can_read(1)) {
    37         my $string = <$child>;
    38         my @events = split(/\n/, $string) if $string;
    39         print join("\n", @events), "\n" if scalar @events;
     43$SIG{CHLD} = \&REAPER;
     44
     45sub REAPER {
     46    while ((my $pid = waitpid(-1,WNOHANG)) > 0) {
     47        $kids--;
     48#        delete $children{$pid};
    4049    }
     50    $SIG{CHLD} = \&REAPER;
    4151}
    4252
    43 #while ( $kids ) {
    44 #    wait();
    45 #    $kids --;
    46 #}
    4753
    48 our $my_sock;
     54while ($kids) {
     55#    foreach my $child ($s->can_read(0)) {
     56#        my $string = do { local $/; <$child>};
     57#        my @events = split(/\n/, $string) if $string;
     58#        print join("\n", @events), "\n" if scalar @events;
     59#    }
     60}
    4961
    5062sub child
    5163{
    52     my ($sock_child, $id) = @_;
     64    my ($sock, $id) = @_;
    5365
    54     $my_sock = $sock_child;
     66    unless ($print_stdout) {
     67        my $filename = hostname() . "." . $$ . ".txt";
     68        open my $fh, ">$filename" or die "can't open $filename: $!";
     69
     70        open STDOUT, ">&", $fh or die "can't reopen STDOUT: $!";
     71        autoflush STDOUT 1;
     72    }
     73
     74#    select $sock;
     75#    $| = 1;
    5576
    5677    # child
    5778    my $fname = "${key}_$id";
    58     print $sock_child "$$ : i'm a little tea pot using key: $fname\n";
    59     my $fh = $neb->open_create( $fname );
    60     child_die("can't create file $fname") unless $fh;
    6179
    62     print $fh "fooby\n";
     80    my $neb = Nebulous::Client::Bench->new(
     81#    proxy   => 'http://localhost:80/nebulous'
     82        proxy   => 'http://alala:80/nebulous',
     83#        sock    => \*STDOUT,
     84    );
    6385
    64     close $fh;
    6586
    66     $fh = $neb->open( $fname, 'read' ) or child_die("can't open file");
    67     close $fh;
     87    while (1) {
     88#    print $sock "$$ : i'm a little tea pot using key: $fname\n";
     89        my $fh = $neb->open_create( $fname )
     90            or child_die($sock, "can't create file $fname");
     91        close $fh;
    6892
    69     $neb->lock( $fname, 'read' );
    70     $neb->unlock( $fname, 'read' );
    71     $neb->replicate( $fname );
    72     $neb->cull( $fname );
     93        $fh = $neb->open( $fname, 'read' )
     94            or child_die("can't open file");
     95        close $fh;
    7396
    74     print $sock_child "$$ : half way\n";
     97        $neb->lock( $fname, 'read' );
     98        $neb->unlock( $fname, 'read' );
     99        $neb->replicate( $fname );
     100        $neb->cull( $fname );
     101        $neb->find( $fname );
     102        $neb->copy( $fname, $fname . "_copy" );
     103        $neb->move( $fname, $fname . "_move" );
     104        $neb->delete( $fname . "_copy" );
     105        $neb->delete( $fname . "_move" );
    75106
    76     $neb->find( $fname );
    77     $neb->copy( $fname, $fname . "_copy" );
    78     $neb->move( $fname, $fname . "_move" );
    79     $neb->delete( $fname . "_copy" );
    80     $neb->delete( $fname . "_move" );
    81 
    82     print $sock_child "$$ : all done!\n";
    83 
    84     $sock_child->flush;
    85     sleep 10;
     107#    print $sock "$$ : all done!\n";
     108    }
    86109
    87110    return 1;
     
    90113sub child_die
    91114{
    92     print $my_sock $@;
    93     shutdown($my_sock, 2);
     115    my $sock = shift;
     116    print $sock @_;
     117    shutdown($sock, 2);
    94118    exit 1;
    95119}
     120
     121package Nebulous::Client::Bench;
     122
     123use base qw( Nebulous::Client );
     124
     125#sub new
     126#{
     127#    my $class = shift;
     128#    my %p = @_;
     129#
     130#    my $sock = delete $p{sock};
     131#    my $self = $class->SUPER::new(%p);
     132#    $self->{sock} = $sock;
     133#
     134#    return $self;
     135#}
     136
     137BEGIN {
     138sub make_wrapper
     139{
     140    my $method = shift;
     141
     142eval "sub $method {"
     143.'    my $self = shift;'
     144.'    my $smark = Time::HiRes::time();'
     145.'    my $ret = $self->SUPER::' . "$method" .'(@_);'
     146.'    my $emark = Time::HiRes::time();'
     147.'    printf "%-17s %-17s %s\n", $emark, " ' . "$method" . ' ", ($emark - $smark), "\n";'
     148.'    return $ret;'
     149.'}';
     150
     151}
     152
     153make_wrapper("create");
     154make_wrapper("open_create");
     155make_wrapper("replicate");
     156make_wrapper("cull");
     157make_wrapper("lock");
     158make_wrapper("unlock");
     159make_wrapper("setxattr");
     160make_wrapper("getxattr");
     161make_wrapper("listxattr");
     162make_wrapper("removexattr");
     163make_wrapper("find_objects");
     164make_wrapper("find_instances");
     165#make_wrapper("find");
     166#make_wrapper("open");
     167#make_wrapper("delete");
     168#make_wrapper("copy");
     169make_wrapper("move");
     170make_wrapper("swap");
     171make_wrapper("delete_instance");
     172make_wrapper("stat");
     173make_wrapper("mounts");
     174
     175}
     176
     1771;
  • branches/cnb_branches/cnb_branch_20090301/Ohana

  • branches/cnb_branches/cnb_branch_20090301/Ohana/Makefile.in

    r19682 r23352  
    7575        mkdir -p $(DESTLIB)
    7676        mkdir -p $(DESTBIN)
    77         for i in $(LIBS); do make $$i.install || exit; done
     77        for i in $(LIBS); do make $$i.install || exit 1; done
    7878        chmod +x ohana-config
    7979        cp -f ohana-config $(DESTBIN)/
     
    8383
    8484all:
    85         make libs || exit
    86         for i in $(PROGRAM); do make $$i || exit; done
     85        make libs || exit 1
     86        for i in $(PROGRAM); do make $$i || exit 1; done
    8787
    8888extras:
    89         for i in $(EXTRAS); do make $$i || exit; done
     89        for i in $(EXTRAS); do make $$i || exit 1; done
    9090
    9191pantasks:
    92         make libs || exit
    93         cd src/opihi; make pclient.install && exit
    94         cd src/opihi; make pcontrol.install && exit
    95         cd src/opihi; make pantasks.install && exit
     92        make libs || exit 1
     93        cd src/opihi; make pclient.install && exit 1
     94        cd src/opihi; make pcontrol.install && exit 1
     95        cd src/opihi; make pantasks.install && exit 1
    9696
    9797mana:
    9898        make libs
    9999        make kapa2.install
    100         cd src/opihi; make mana.install && exit
     100        cd src/opihi; make mana.install && exit 1
    101101
    102102dvoshell:
    103103        make libs
    104104        make kapa2.install
    105         cd src/opihi; make dvo.install && exit
     105        cd src/opihi; make dvo.install && exit 1
    106106
    107107clean:
    108108        @if [ "$(ARCH)" = "" ]; then echo ""; echo " *** please define ARCH ***"; echo; exit 1; fi
    109         for i in $(LIBS); do make $$i.clean || exit; done
    110         for i in $(PROGRAM); do make $$i.clean || exit; done
    111         for i in $(EXTRAS); do make $$i.clean || exit; done
     109        for i in $(LIBS); do make $$i.clean || exit 1; done
     110        for i in $(PROGRAM); do make $$i.clean || exit 1; done
     111        for i in $(EXTRAS); do make $$i.clean || exit 1; done
    112112        @rm -f `find . -name .mana`
    113113        @rm -f `find . -name .dvo`
     
    116116dist:
    117117        @if [ "$(ARCH)" = "" ]; then echo ""; echo " *** please define ARCH ***"; echo; exit 1; fi
    118         for i in $(LIBS); do make $$i.dist || exit; done
    119         for i in $(PROGRAM); do make $$i.dist || exit; done
     118        for i in $(LIBS); do make $$i.dist || exit 1; done
     119        for i in $(PROGRAM); do make $$i.dist || exit 1; done
    120120        @echo -n -e "\0033]0; *** Ohana: done $@ *** \0007" \
    121121
    122122install:
    123123        @if [ "$(ARCH)" = "" ]; then echo ""; echo " *** please define ARCH ***"; echo; exit 1; fi
    124         for i in $(LIBS); do make $$i.install || exit; done
    125         for i in $(PROGRAM); do make $$i.install || exit; done
     124        for i in $(LIBS); do make $$i.install || exit 1; done
     125        for i in $(PROGRAM); do make $$i.install || exit 1; done
    126126        @echo -n -e "\0033]0; *** Ohana: done $@ *** \0007" \
    127127
    128128install.extras:
    129         for i in $(EXTRAS); do make $$i.install || exit; done
     129        for i in $(EXTRAS); do make $$i.install || exit 1; done
    130130        @echo -n -e "\0033]0; *** Ohana: done $@ *** \0007" \
    131131
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/addstar/include/skycells.h

    r21508 r23352  
    1212# include <glob.h>
    1313
    14 enum {SQUARES, TRIANGLES, LOCAL};
     14enum {SQUARES, TRIANGLES, LOCAL, RINGS};
    1515enum {TETRAHEDRON, CUBE, OCTOHEDRON, DODECAHEDRON, ICOSAHEDRON};
    1616
     
    6767double SCALE;
    6868double PADDING;
     69double CELLSIZE;
    6970int    LEVEL;
    7071
     
    8485int          sky_tessellation               PROTO((FITS_DB *db, int level, int Nmax, int mode, double scale));
    8586int          sky_tessellation_init          PROTO((double scale));
     87
    8688int          sky_tessellation_local         PROTO((FITS_DB *db, int level, int Nmax));
    8789int          sky_tessellation_triangles     PROTO((FITS_DB *db, int level, int Nmax));
    8890int          sky_tessellation_squares       PROTO((FITS_DB *db, int level, int Nmax));
     91int          sky_tessellation_rings         PROTO((FITS_DB *db, int level, int Nmax));
     92
    8993int          sky_triangle_to_image          PROTO((Image *image, SkyTriangle *triangle));
    9094int          sky_triangle_to_rectangle      PROTO((SkyRectangle *image, SkyTriangle *triangle));
     95
    9196int          sky_rectangle_local            PROTO((SkyRectangle *rectangle));
    9297int          sky_subdivide_image            PROTO((Image *output, SkyRectangle *input, int Nx, int Ny));
    9398int          sky_triangle_coords            PROTO((SkyTriangle *triangle));
     99
     100SkyRectangle *sky_rectangle_ring            PROTO((float dec, float dDEC, int *nring));
     101
    94102SkyTriangle *sky_divide_triangles           PROTO((SkyTriangle *in, int *ntriangles));
    95103SkyTriangle *sky_base_triangles             PROTO((int *ntriangles));
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/addstar/src/args_skycells.c

    r21048 r23352  
    3535      MODE = LOCAL;
    3636    }
     37    if (!strcasecmp (argv[N], "rings")) {
     38      MODE = RINGS;
     39    }
    3740    remove_argument (N, &argc, argv);
    3841  }
     
    140143
    141144  LEVEL = 8;
    142   if ((MODE != LOCAL) && (N = get_argument (argc, argv, "-level"))) {
    143     remove_argument (N, &argc, argv);
    144     LEVEL = strtol (argv[N], &ptr, 10);
    145     remove_argument (N, &argc, argv);
    146     if ((*ptr != 0) || (LEVEL < 0)) {
    147       fprintf (stderr, "-level requires an integer (>= 0) argument\n");
     145  if ((MODE == SQUARES) || (MODE == TRIANGLES)) {
     146    if ((N = get_argument (argc, argv, "-level"))) {
     147      remove_argument (N, &argc, argv);
     148      LEVEL = strtol (argv[N], &ptr, 10);
     149      remove_argument (N, &argc, argv);
     150      if ((*ptr != 0) || (LEVEL < 0)) {
     151        fprintf (stderr, "-level requires an integer (>= 0) argument\n");
     152        help ();
     153      } 
     154    }
     155  }
     156
     157  CELLSIZE = 4.0;
     158  if ((MODE == RINGS) && (N = get_argument (argc, argv, "-cellsize"))) {
     159    remove_argument (N, &argc, argv);
     160    CELLSIZE = strtod (argv[N], &ptr);
     161    if ((*ptr != 0) || (CELLSIZE < 0.0)) {
     162      fprintf (stderr, "-level requires a floating-point argument\n");
    148163      help ();
    149164    } 
     165    remove_argument (N, &argc, argv);
    150166  }
    151167
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/addstar/src/get2mass_full.c

    r21508 r23352  
    11# include "addstar.h"
    22# include "2mass.h"
     3
     4// XXX check to see if desired output format is PS1_V1 or later?  (use 16bit version if not?)
    35
    46// fill in the data for a JHK triplet star.  takes a pointer to the start of the line the
     
    171173
    172174  switch (qual) {
    173     case 'X': star[0].measure.photFlags |= 0x0000; break;
    174     case 'U': star[0].measure.photFlags |= 0x0001; break;
    175     case 'F': star[0].measure.photFlags |= 0x0002; break;
    176     case 'E': star[0].measure.photFlags |= 0x0003; break;
    177     case 'A': star[0].measure.photFlags |= 0x0004; break;
    178     case 'B': star[0].measure.photFlags |= 0x0005; break;
    179     case 'C': star[0].measure.photFlags |= 0x0006; break;
    180     case 'D': star[0].measure.photFlags |= 0x0007; break;
     175    case 'A': star[0].measure.photFlags |= 0x00000001; break; // was: 0x0004
     176    case 'B': star[0].measure.photFlags |= 0x00000002; break; // was: 0x0005
     177    case 'C': star[0].measure.photFlags |= 0x00000004; break; // was: 0x0006
     178    case 'D': star[0].measure.photFlags |= 0x00000008; break; // was: 0x0007
     179    case 'E': star[0].measure.photFlags |= 0x00000010; break; // was: 0x0003
     180    case 'F': star[0].measure.photFlags |= 0x00000020; break; // was: 0x0002
     181    case 'U': star[0].measure.photFlags |= 0x00000040; break; // was: 0x0001
     182    case 'X': star[0].measure.photFlags |= 0x00000080; break; // was: 0x0000
    181183    default:
    182184      fprintf (stderr, "error!\n");
     
    189191
    190192  switch (qual) {
    191     case '0': star[0].measure.photFlags |= 0x0000; break;
    192     case '1': star[0].measure.photFlags |= 0x0010; break;
    193     case '2': star[0].measure.photFlags |= 0x0020; break;
    194     case '3': star[0].measure.photFlags |= 0x0030; break;
    195     case '4': star[0].measure.photFlags |= 0x0040; break;
    196     case '6': star[0].measure.photFlags |= 0x0050; break;
    197     case '9': star[0].measure.photFlags |= 0x0060; break;
     193    case '0': star[0].measure.photFlags |= 0x00000100; break; // was: 0x0000
     194    case '1': star[0].measure.photFlags |= 0x00000200; break; // was: 0x0010
     195    case '2': star[0].measure.photFlags |= 0x00000400; break; // was: 0x0020
     196    case '3': star[0].measure.photFlags |= 0x00000800; break; // was: 0x0030
     197    case '4': star[0].measure.photFlags |= 0x00001000; break; // was: 0x0040
     198    case '6': star[0].measure.photFlags |= 0x00002000; break; // was: 0x0050
     199    case '9': star[0].measure.photFlags |= 0x00004000; break; // was: 0x0060
    198200    default:
    199201      fprintf (stderr, "error!\n");
     
    206208
    207209  switch (qual) {
    208     case 'p': star[0].measure.photFlags |= 0x0000; break;
    209     case 'c': star[0].measure.photFlags |= 0x0100; break;
    210     case 'd': star[0].measure.photFlags |= 0x0200; break;
    211     case 's': star[0].measure.photFlags |= 0x0300; break;
    212     case 'b': star[0].measure.photFlags |= 0x0400; break;
    213     case '0': star[0].measure.photFlags |= 0x0500; break;
     210    case 'p': star[0].measure.photFlags |= 0x00010000; break; // was: 0x0000
     211    case 'c': star[0].measure.photFlags |= 0x00020000; break; // was: 0x0100
     212    case 'd': star[0].measure.photFlags |= 0x00040000; break; // was: 0x0200
     213    case 's': star[0].measure.photFlags |= 0x00080000; break; // was: 0x0300
     214    case 'b': star[0].measure.photFlags |= 0x00010000; break; // was: 0x0400
     215    case '0': star[0].measure.photFlags |= 0x00020000; break; // was: 0x0500
    214216    default:
    215217      fprintf (stderr, "error!\n");
     
    222224
    223225  switch (qual) {
    224     case '0': star[0].measure.photFlags &= ~0x0008; break;
    225     case '1': star[0].measure.photFlags &= ~0x0008; break;
    226     default:  star[0].measure.photFlags |=  0x0008; break;
     226    case '0': star[0].measure.photFlags &= ~0x00300000; break; // was: ~0x0008
     227    case '1': star[0].measure.photFlags |=  0x00100000; break; // was: ~0x0008
     228    default:  star[0].measure.photFlags |=  0x00200000; break; // was:  0x0008
    227229  }     
    228230  return (TRUE);
     
    232234
    233235  switch (qual) {
    234     case '0': star[0].measure.photFlags &= ~0x0080; break;
    235     case '1': star[0].measure.photFlags &= ~0x0080; break;
    236     default: 
    237       star[0].measure.photFlags |= 0x0080;
     236    case '0': star[0].measure.photFlags &= ~0x00c00000; break; // was: ~0x0080
     237    case '1': star[0].measure.photFlags |=  0x00400000; break; // was: ~0x0080
     238    default:  star[0].measure.photFlags |=  0x00800000;        // was:  0x0080
    238239      star[0].measure.extNsigma = 100.0;
    239240      break;
     
    245246
    246247  switch (qual) {
    247     case '0': star[0].measure.photFlags &= ~0x0800; break;
    248     case '1': star[0].measure.photFlags &= ~0x0800; break;
    249     default:  star[0].measure.photFlags |=  0x0800; break;
     248    case '0': star[0].measure.photFlags &= ~0x03000000; break; // was: ~0x0800
     249    case '1': star[0].measure.photFlags |=  0x01000000; break; // was: ~0x0800
     250    default:  star[0].measure.photFlags |=  0x02000000; break; // was:  0x0800
    250251  }     
    251252  return (TRUE);
     
    255256
    256257  switch (qual) {
    257     case '0': star[0].measure.photFlags &= ~0x1000; break;
    258     case '1': star[0].measure.photFlags &= ~0x1000; break;
    259     default:  star[0].measure.photFlags |=  0x1000; break;
     258    case '0': star[0].measure.photFlags &= ~0x0c000000; break; // was: ~0x1000
     259    case '1': star[0].measure.photFlags |=  0x04000000; break; // was: ~0x1000
     260    default:  star[0].measure.photFlags |=  0x08000000; break; // was:  0x1000
    260261  }     
    261262  return (TRUE);
     
    265266
    266267  switch (qual) {
    267     case '0': star[0].measure.photFlags &= ~0x2000; break;
    268     case '1': star[0].measure.photFlags |=  0x2000; break;
     268    case '0': star[0].measure.photFlags &= ~0x10000000; break; // was: ~0x2000
     269    case '1': star[0].measure.photFlags |=  0x10000000; break; // was:  0x2000
    269270    default:  abort();
    270271  }     
     
    272273}
    273274
     275// unused photFlags:
     276// 0x0000.8000
     277// 0x0004.0000
     278// 0x0008.0000
     279// 0x2000.0000
     280// 0x4000.0000
     281// 0x8000.0000
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/addstar/src/sky_tessalation.c

    r21508 r23352  
    1111  sky_tessellation_init (scale);
    1212
    13   if (mode == SQUARES) {
    14     sky_tessellation_squares (db, level, Nmax);
    15     return TRUE;
    16   }
    17 
    18   if (mode == TRIANGLES) {
    19     sky_tessellation_triangles (db, level, Nmax);
    20     return TRUE;
    21   }
    22 
    23   if (mode == LOCAL) {
    24     sky_tessellation_local (db, level, Nmax);
    25     return TRUE;
     13  switch (mode) {
     14    case SQUARES:
     15      sky_tessellation_squares (db, level, Nmax);
     16      return TRUE;
     17    case TRIANGLES:
     18      sky_tessellation_triangles (db, level, Nmax);
     19      return TRUE;
     20    case LOCAL:
     21      sky_tessellation_local (db, level, Nmax);
     22      return TRUE;
     23    case RINGS:
     24      sky_tessellation_rings (db, level, Nmax);
     25      return TRUE;
     26    default:
     27      break;
    2628  }
    2729
     
    222224
    223225  free (image);
     226  return (TRUE);
     227}
     228
     229// the RINGS tessellation uses the declination zones proposed by Tamas Budavari
     230// we generate projects on uniform rings of constant dec height
     231int sky_tessellation_rings (FITS_DB *db, int level, int Nmax) {
     232
     233  int j, nDEC, Nimage, Nring;
     234  float dec, dDEC;
     235  SkyRectangle *ring;
     236  Image *image;
     237
     238  // The tessellation has one input parameter: the approximate cell size.  Starting with
     239  // the cell size, determine the optimal projection cell height (dDEC) that results in an
     240  // integer number of dec zones between -90 and +90
     241
     242  // in fact, we place a single image on each pole, so the real range of dec is 180.0 - CELLSIZE:
     243
     244  nDEC = (180.0 - CELLSIZE) / CELLSIZE;
     245  dDEC = (180.0 - CELLSIZE) / nDEC;
     246  nDEC += 2;
     247
     248  // a test
     249  // for (dec = 0.0 + 0.5*dDEC; dec < +90.0; dec += dDEC) {
     250
     251  // generate the a collection of rectangles for each ring
     252  for (dec = -90.0; dec < +90.0 + 0.5*dDEC; dec += dDEC) {
     253
     254    ring = sky_rectangle_ring (dec, dDEC, &Nring);
     255    if (!ring) continue;
     256
     257    // subdivide each image (Nx x Ny subcells)
     258    Nimage = NX_SUB*NY_SUB*Nring;
     259    ALLOCATE (image, Image, Nimage);
     260    for (j = 0; j < Nring; j++) {
     261      // convert the SkyRectangles to Images for output
     262      sky_subdivide_image (&image[j*NX_SUB*NY_SUB], &ring[j], NX_SUB, NY_SUB);
     263    }
     264
     265    /* add the new images and save */
     266    dvo_image_addrows (db, image, Nimage);
     267    SetProtect (TRUE);
     268    dvo_image_update (db, VERBOSE);
     269    SetProtect (FALSE);
     270    dvo_image_clear_vtable (db);
     271   
     272    free (ring);
     273    free (image);
     274  }   
    224275  return (TRUE);
    225276}
     
    480531
    481532  return (TRUE);
     533}
     534
     535// define the parameters of a single sky projection center
     536SkyRectangle *sky_rectangle_ring (float dec, float dDEC, int *nring) {
     537
     538  int i, NX, NY, nRA;
     539  SkyRectangle *ring;
     540  float theta, dRA;
     541
     542  // 'dec' is a guess at the center of the cell; in fact, we need to choose decLower and
     543  // decUpper to ensure complete overlap of the cells
     544
     545  // we can determine the 'lower' bound (bound closest to the equator):
     546  float decLower = (dec > 0.0) ? dec - 0.5*dDEC : dec + 0.5*dDEC;
     547
     548  // solve for actual cellsize (\theta):  tan(\delta_{n+1} - \theta/2) = tan(\delta_n + \theta/2)cos(\alpha_n / 2)
     549  float decUpper = (dec > 0.0) ? dec + dDEC : dec - dDEC;
     550
     551  if (fabs(dec) + 0.5*dDEC > 90.0) {
     552    // onPole = TRUE;
     553    theta = dDEC;
     554    nRA = 1;
     555    dRA = theta / cos(decLower*RAD_DEG); // make a square at the pole
     556  } else {
     557    // onPole = FALSE;
     558    // Subdivide the 'lower' bound into an integer number of segments:
     559    nRA = cos(RAD_DEG*decLower) * 360.0 / CELLSIZE; // CELLSIZE is a projection size
     560    dRA = 360.0 / nRA;                         // dRA is a size in RA degrees == \alpha_n
     561
     562    // tan(decUpper - theta/2) = tan(dec + theta/2) cos(dRA / 2);
     563
     564    // we solve this equation for theta (fairly ugly: expand the tangents into sin/cos, expand the
     565    // sum-of-angle sine and cosine, multiply through, convert via half-angle formulae and write
     566    // as a quadratic expression in sine(theta/2)
     567 
     568    float sd1 = sin(RAD_DEG*decUpper);
     569    float cd1 = cos(RAD_DEG*decUpper);
     570    float sd2 = sin(RAD_DEG*dec);
     571    float cd2 = cos(RAD_DEG*dec);
     572    float   k = cos(RAD_DEG*dRA/2.0);
     573
     574    float c1 =  (sd1*cd2 + sd2*cd1)*(1.0 - k);
     575    float c2 =  (sd1*cd2 - sd2*cd1)*(1.0 + k);
     576    float c3 = -(sd1*sd2 + cd1*cd2)*(1.0 + k);
     577
     578    float A = SQ(c3) + SQ(c2);
     579    float B = 2*c1*c3;
     580    float C = SQ(c1) - SQ(c2);
     581
     582    float arg = SQ(B) - 4.0*A*C;
     583
     584    float root;
     585
     586    if (dec >= 0.0) {
     587      root = (-B + sqrt (arg)) / (2.0*A);
     588      theta = +DEG_RAD*asin(root);
     589    } else {
     590      root = (-B - sqrt (arg)) / (2.0*A);
     591      theta = -DEG_RAD*asin(root);
     592    }
     593
     594    // the negative solution yields a negative cellsize
     595    // float root2 = (-B - sqrt (arg)) / (2.0*A);
     596    // float theta2 = DEG_RAD*asin(root2);
     597
     598    // test lines:
     599    // float r1 = tan(RAD_DEG*(decUpper - 0.5*theta1));
     600    // float r2 = tan(RAD_DEG*(dec + 0.5*theta1));
     601    // fprintf (stdout, "%f %f  %f  %f  %f %f  %f %f  %f %f %f\n", dec, decUpper, dRA, arg, root1, root2, theta1, theta2, r1, r2, k*r2);
     602  }
     603  fprintf (stdout, "%f %f  %f x %f (%d)\n", dec, decUpper, dRA, theta, nRA);
     604
     605  // I think we need to return the value of dec for the next ring, but I am not sure...
     606
     607  ALLOCATE (ring, SkyRectangle, nRA);
     608
     609  for (i = 0; i < nRA; i++) {
     610    memset (&ring[i], 0, sizeof(SkyRectangle));
     611    memset (&ring[i].coords, 0, sizeof(Coords));
     612    ring[i].coords.crval1 = i*dRA;
     613    ring[i].coords.crval2 = dec;
     614
     615    ring[i].coords.pc1_1 = +1.0;
     616    ring[i].coords.pc1_2 = +0.0;
     617    ring[i].coords.pc2_1 = -0.0;
     618    ring[i].coords.pc2_2 = +1.0;
     619 
     620    // range values are in projected degrees
     621    NX = cos(decLower*RAD_DEG) * dRA   * 3600.0 / SCALE;
     622    NY =                         theta * 3600.0 / SCALE;
     623
     624    // crpix1,crpix2 is the projection center
     625    ring[i].coords.crpix1 = 0.5*NX;
     626    ring[i].coords.crpix2 = 0.5*NY;
     627
     628    ring[i].coords.cdelt1 = SCALE / 3600.0;
     629    ring[i].coords.cdelt2 = SCALE / 3600.0;
     630
     631    strcpy (ring[i].coords.ctype, "DEC--TAN");
     632
     633    ring[i].NX = NX;
     634    ring[i].NY = NY;
     635    ring[i].photcode = 1; // this needs to be set more sensibly
     636
     637
     638    // fprintf (stderr, "%f %f  : %f %f\n",
     639    // ring[i].coords.crval1, ring[i].coords.crval2,
     640    // ring[i].coords.crpix1, ring[i].coords.crpix2);
     641  }
     642
     643  *nring = nRA;
     644  return (ring);
    482645}
    483646
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/libdvo

    • Property svn:ignore
      •  

        old new  
        1 lib
         1
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/libdvo/lib

    • Property svn:ignore
      •  

        old new  
        1 *.linux
        2 *.lin64
        3 *.sol
        4 *.sun
        5 *.sid
        6 *.hp
        7 *.irix
        8 *.darwin.dylib
        9 *.darwin_x86.dylib
         1*.a
         2*.so
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/libfits/lib

    • Property svn:ignore
      •  

        old new  
        1 *.linux
        2 *.lin64
        3 *.sol
        4 *.sun
        5 *.sid
        6 *.hp
        7 *.irix
        8 *.darwin.dylib
        9 *.darwin_x86.dylib
         1*.a
         2*.so
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/libkapa/lib

    • Property svn:ignore
      •  

        old new  
        1 *.linux
        2 *.lin64
        3 *.sol
        4 *.sun
        5 *.sid
        6 *.hp
        7 *.irix
        8 *.darwin.dylib
        9 *.darwin_x86.dylib
         1*.a
         2*.so
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/libohana/lib

    • Property svn:ignore
      •  

        old new  
        1 *.linux
        2 *.lin64
        3 *.sol
        4 *.sun
        5 *.sid
        6 *.hp
        7 *.irix
        8 *.darwin.dylib
        9 *.darwin_x86.dylib
         1*.a
         2*.so
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/libohana/src/CommOps.c

    r8385 r23352  
    1414    return (status);
    1515  }
     16  // fprintf (stderr, "resp: %s\n", command.buffer);
    1617
    1718  /* buffer contains an EOL NULL, we can just sscan it */
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/libtap/lib

    • Property svn:ignore
      •  

        old new  
        1 *.linux
        2 *.lin64
        3 *.sol
        4 *.sun
        5 *.sid
        6 *.hp
        7 *.irix
        8 *.darwin.dylib
        9 *.darwin_x86.dylib
         1*.a
         2*.so
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/dimm/Analysis.c

    r2598 r23352  
    8686        }
    8787
     88/* find contiguous trigger pixels in row from starting point */
     89
     90int fillrow (float *buffer, int Nx, int offset, int sx, int *xs, int *xe) {
     91
     92  trigger = FALSE;
     93  for (i = sx, pix = offset + i; buffer[pix] && (i < Nx); i++, pix++) {
     94    addpix (pix);
     95    buffer[pix] = 0;
     96    trigger = TRUE;
     97    *xe = i;
     98  }
     99  for (i = sx - 1, pix = offset + i; (i >= 0) && buffer[pix]; i--, pix--) {
     100    addpix (pix);
     101    buffer[pix] = 0;
     102    trigger = TRUE;
     103    *xs = i;
     104  }
     105  return (trigger);
     106}
     107
     108static int Npix = 0;
     109static int *Pix = (int *) NULL;
     110
     111addpix (int pix) {
     112  Npix ++;
     113  if (Pix == (int *) NULL) {
     114    ALLOCATE (Pix, int, MAX (1, Npix));
     115  } else {
     116    REALLOCATE (Pix, int, MAX (1, Npix));
     117  }   
     118  Pix[Npix - 1] = pix;
     119}
     120
     121clearpix () {
     122  Npix = 0;
     123  REALLOCATE (Pix, int, 1);
     124}
     125
     126statpix (double *x, double *y, float *buffer, int Nx) {
     127
     128  int X, Y;
     129  double Sx, Sy, So;
     130
     131  So = Sx = Sy = 0;
     132  for (i = 0; i < Npix; i++) {
     133    Y = pix / Nx;
     134    X = pix % Nx;
     135    So += buffer[pix];
     136    Sx += X * buffer[pix];
     137    Sy += Y * buffer[pix];
     138  }
     139  *x = Sx / So;
     140  *y = Sy / So;
     141}
     142
     143/* find stars:
     144   - binarize @ threshold
     145   - find all contiguous blobs
     146   - find geom center of each blob
     147*/
     148
     149
     150
     151/*
     152
     153.....................
     154....x................
     155...xxx...............
     156..........xxx..........
     157.........xx..........
     158.....................
     159.....................
     160.....................
     161.....................
     162.....................
     163
     164
     165 */
     166
    88167# endif
    89168
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/dimm/Makefile

    r17283 r23352  
    2626$(SRC)/init.$(ARCH).o                   \
    2727$(SRC)/dimm.$(ARCH).o                   \
    28 $(SRC)/camera.$(ARCH).o         \
     28$(SRC)/camera_cmds.$(ARCH).o            \
    2929$(SRC)/findstars.$(ARCH).o              \
    30 $(SRC)/telescope.$(ARCH).o   \
     30$(SRC)/telescope_cmds.$(ARCH).o   \
    3131$(SRC)/version.$(ARCH).o
    3232
     
    6464.PHONY: dimm
    6565
    66 # are these used or replaced?
    67 # $(SRC)/analysis.$(ARCH).o             \
     66# these have not been finished: should be used for analysis of the extracted images
    6867# $(SRC)/Analysis.$(ARCH).o            \
    6968# $(SRC)/Image.$(ARCH).o                \
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/dimm/camera_cmds.c

  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/dimm/telescope_cmds.c

  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/lib

    • Property svn:ignore set to
      *.a
      *.so
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/CheckTasks.c

    r15872 r23352  
    4848    // add random offset between 0 and 5% of exec_period
    4949    // XXX this should be optional
    50     fuzz = 0.05*task[0].exec_period*drand48() + 1e-6*task[0].last.tv_usec;
     50    fuzz = 0.1*task[0].exec_period*drand48();
    5151    task[0].last.tv_usec = 1e6*(fuzz - (int)fuzz);
    5252    task[0].last.tv_sec += (int) fuzz;
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/task_threads.c

    r15791 r23352  
    22
    33/** things related to CheckTasks **/
     4void ResetTaskTimers ();
    45
    56static int CheckTasksRun = FALSE;
    67
    78void CheckTasksSetState (int state) {
     9  if (state && !CheckTasksRun) {
     10    ResetTaskTimers ();
     11  }
    812  CheckTasksRun = state;
    913}
     
    5155// timeout.  this enforces a certain granularity in the task creation, but prevents the task
    5256// thread from driving the load up to silly levels.
     57
     58// reset all of the task timers, with a bit of fuzz.  this is called
     59// whenever we transition from 'stop' to 'run'
     60void ResetTaskTimers () {
     61
     62  Task *task;
     63  struct timeval now;
     64  float fuzz;
     65
     66  // get the current time
     67  gettimeofday (&now, NULL);
     68
     69  // check all tasks
     70  while ((task = NextTask ()) != NULL) {
     71    task[0].last.tv_usec = now.tv_usec;
     72    task[0].last.tv_sec  = now.tv_sec;
     73
     74    // add random offset between 0 and 10% of exec_period
     75    // XXX this should be optional
     76    fuzz = task[0].exec_period*drand48();
     77    task[0].last.tv_usec += 1e6*(fuzz - (int)fuzz);
     78    task[0].last.tv_sec += (int) fuzz;
     79
     80    // gprint (GP_LOG, "fuzz: %f, last: %d %d\n", fuzz, task[0].last.tv_sec, task[0].last.tv_usec);
     81  }
     82  return;
     83}
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pcontrol/CheckIdleHost.c

    r22675 r23352  
    4040    host[0].job = (struct Job *) job;
    4141
    42     if (logfile) fprintf (logfile, "start needhost %s (job host %s) : %s\n", host[0].hostname, job[0].hostname, job[0].argv[0]);
     42    // if (logfile) fprintf (logfile, "start needhost %s (job host %s) : %s\n", host[0].hostname, job[0].hostname, job[0].argv[0]);
    4343
    4444    /* take the job off the stack and unlock the stack */
     
    6060    host[0].job = (struct Job *) job;
    6161
    62     if (logfile) fprintf (logfile, "start wanthost %s (job host %s) : %s\n", host[0].hostname, job[0].hostname, job[0].argv[0]);
     62    // if (logfile) fprintf (logfile, "start wanthost %s (job host %s) : %s\n", host[0].hostname, job[0].hostname, job[0].argv[0]);
    6363
    6464    /* take the job off the stack and unlock the stack */
     
    7878    host[0].job = (struct Job *) job;
    7979
    80     if (logfile) fprintf (logfile, "start  anyhost %s (job host %s) : %s\n", host[0].hostname, job[0].hostname, job[0].argv[0]);
     80    // if (logfile) fprintf (logfile, "start  anyhost %s (job host %s) : %s\n", host[0].hostname, job[0].hostname, job[0].argv[0]);
    8181
    8282    /* take the job off the stack and unlock the stack */
  • branches/cnb_branches/cnb_branch_20090301/PS-IPP-Config/lib/PS/IPP/Config.pm

    r21320 r23352  
    7171    unless (defined $class) {
    7272        carp "Programming error";
    73         exit($PS_EXIT_PROG_ERROR);
     73        return undef;
    7474    }
    7575
     
    8585    unless (open $file, $name) {
    8686        carp "Unable to open ipprc file $name: $!";
    87         exit($PS_EXIT_CONFIG_ERROR);
     87        return undef;
    8888    }
    8989    my @contents = <$file>;        # Contents of the ipprc file
     
    9595    unless (defined $path) {
    9696        carp "PATH is not set in $name\n";
    97         exit($PS_EXIT_CONFIG_ERROR);
     97        return undef;
    9898    }
    9999
     
    112112    bless $self, $class;
    113113
    114     $self->load_site();
    115     $self->load_system();
    116 
    117     $self->define_camera($camera) if defined $camera;
     114    $self->load_site() or return undef;
     115    $self->load_system() or return undef;
     116
     117    ( $self->define_camera($camera) or return undef ) if defined $camera;
    118118
    119119    return $self;
     
    148148                unless ($found) {
    149149                    carp "Unable to find camera configuration file $filename\n";
    150                     exit($PS_EXIT_CONFIG_ERROR);
     150                    return undef;
    151151                }
    152152            }
     
    158158
    159159    carp "Unable to find configuration file: $filename";
    160     exit($PS_EXIT_CONFIG_ERROR);
     160    return undef;
    161161}
    162162
     
    170170    unless (defined $self) {
    171171        carp "Programming error";
    172         exit($PS_EXIT_PROG_ERROR);
     172        return undef;
    173173    }
    174174
     
    176176    unless (defined $filename) {
    177177        carp "Unable to find site configuration file\n";
    178         exit($PS_EXIT_CONFIG_ERROR);
     178        return undef;
    179179    }
    180180
    181181    my $realfile = $self->_find_config($filename); # Resolved filename, after hunting the PATH
     182    ( carp "Unable to find site configuration" and return undef ) unless defined $realfile;
    182183
    183184    # Read the file
     
    185186    unless (open $file, $realfile) {
    186187        carp "Unable to open site configuration file $realfile: $!";
    187         exit($PS_EXIT_CONFIG_ERROR);
     188        return undef;
    188189    }
    189190
     
    194195    unless (defined $self->{_siteConfig}) {
    195196        carp "Failure to parse the site configuration file $realfile";
    196         exit($PS_EXIT_CONFIG_ERROR);
     197        return undef;
    197198    }
    198199
     
    207208    unless (defined $self) {
    208209        carp "Programming error";
    209         exit($PS_EXIT_PROG_ERROR);
     210        return undef;
    210211    }
    211212
     
    213214    unless (defined $filename) {
    214215        carp "Unable to find system configuration file\n";
    215         exit($PS_EXIT_CONFIG_ERROR);
     216        return undef;
    216217    }
    217218
    218219    my $realfile = $self->_find_config($filename); # Resolved filename, after hunting the PATH
     220    ( carp "Unable to find system configuration" and return undef ) unless defined $realfile;
    219221
    220222    # Read the file
     
    222224    unless (open $file, $realfile) {
    223225        carp "Unable to open system configuration file $realfile: $!";
    224         exit($PS_EXIT_CONFIG_ERROR);
     226        return undef;
    225227    }
    226228    my @contents = <$file>;
     
    230232    unless (defined $self->{_systemConfig}) {
    231233        carp "Failure to define system configuration";
    232         exit($PS_EXIT_CONFIG_ERROR);
     234        return undef;
    233235    }
    234236
     
    244246    unless (defined $self and defined $name) {
    245247        carp "Programming error";
    246         exit($PS_EXIT_PROG_ERROR);
     248        return undef;
    247249    }
    248250
     
    251253    unless (defined $filename) {
    252254        carp "Unable to find configuration file for camera $name\n";
    253         exit($PS_EXIT_CONFIG_ERROR);
     255        return undef;
    254256    }
    255257
    256258    my $realfile = $self->_find_config($filename); # Resolved filename, after hunting the PATH
     259    ( carp "Unable to find camera configuration" and return undef ) unless defined $realfile;
    257260
    258261    # Read the file
     
    260263    unless (open $file, $realfile) {
    261264        carp "Unable to open camera configuration file $realfile: $!";
    262         exit($PS_EXIT_CONFIG_ERROR);
     265        return undef;
    263266    }
    264267    my @contents = <$file>;
     
    269272    unless (defined $self->{camera}) {
    270273        carp "Failure to define camera";
    271         exit($PS_EXIT_CONFIG_ERROR);
     274        return undef;
    272275    }
    273276
     
    326329    unless (defined $self and defined $name) {
    327330        carp "Programming error";
    328         exit($PS_EXIT_PROG_ERROR);
     331        return undef;
    329332    }
    330333
     
    333336    unless (defined $pathname) {
    334337        carp "Unable to find datapath $name\n" ;
    335         exit($PS_EXIT_CONFIG_ERROR);
     338        return undef;
    336339    }
    337340
     
    340343
    341344# convert the database name and the table ID to a image source id
    342 sub source_id 
     345sub source_id
    343346{
    344347    my $self = shift;
     
    351354    my $admindb = "ippadmin";
    352355
    353     die "dbserver not defined in configuration" unless defined($dbserver);
    354     die "dbuser not defined in configuration" unless defined($dbuser);
    355     die "dbpassword not defined in configuration" unless defined($dbpassword);
    356     die "dbname not defined in configuration" unless defined($dbname);
     356    ( carp "dbserver not defined in configuration"  and return undef ) unless defined($dbserver);
     357    ( carp "dbuser not defined in configuration"  and return undef ) unless defined($dbuser);
     358    ( carp "dbpassword not defined in configuration"  and return undef ) unless defined($dbpassword);
     359    ( carp "dbname not defined in configuration"  and return undef ) unless defined($dbname);
    357360
    358361    my $dsn = "DBI:mysql:host=$dbserver;database=$admindb";
     
    363366    $stmt->execute();
    364367    my $ref = $stmt->fetchrow_hashref();
    365     die "ippdb $dbname not found" unless ($ref);
     368    ( carp "ippdb $dbname not found" and return undef ) unless ($ref);
    366369
    367370    my $proj_id = $ref->{proj_id};
     
    382385    if ($@) {
    383386        carp "Can't find Nebulous::Client.";
    384         exit($PS_EXIT_PROG_ERROR);
     387        return undef;
    385388    }
    386389
     
    390393    unless (defined $server) {
    391394        carp "Unable to find NEB_SERVER in camera configuration file.";
    392         exit($PS_EXIT_CONFIG_ERROR);
    393     }
    394 
    395     my $neb = Nebulous::Client->new( proxy => $server );
    396     unless (defined $neb) {
     395        return undef;
     396    }
     397
     398    my $neb = eval { Nebulous::Client->new( proxy => $server ); };
     399    if ($@ or not defined $neb) {
    397400        carp "Unable to find NEB_SERVER in camera configuration file.";
    398         exit($PS_EXIT_CONFIG_ERROR);
     401        return undef;
    399402    }
    400403
     
    415418    if ($scheme) {
    416419        $scheme = lc($scheme);
    417         # print "scheme: $scheme\n";
     420        # print "scheme: $scheme\n";
    418421
    419422        if ($scheme eq 'neb') {
    420             $self->_neb_start();
     423            $self->_neb_start() or ( carp "Can't start Nebulous" and return undef );
    421424            my $neb = $self->{nebulous}; # Nebulous handle
    422425            if ($create_if_doesnt_exist) {
    423                 unless ($neb->stat( $name )) {
    424                     # print "entry $name not found, creating...\n";
    425                     my $uri = $neb->create( $name );
    426                     unless(defined $uri) {
     426                my $status = eval { $neb->stat( $name ); };
     427                ( carp "Unable to stat Nebulous handle $name" and return undef ) if $@;
     428                unless ($status) {
     429                    # print "entry $name not found, creating...\n";
     430                    my $uri = eval { $neb->create( $name ); };
     431                    if ($@ or not defined $uri) {
    427432                        carp "unable to instantiate $name.";
    428                         exit($PS_EXIT_DATA_ERROR);
     433                        return undef;
    429434                    }
    430435                    my $path = URI->new( $uri )->path;
    431                     # print "created path: $path\n";
     436                    # print "created path: $path\n";
    432437                    return $path;
    433438                }
    434439            }
    435             my $path = $neb->find( $name );
    436             if (not defined $path) {
    437                 carp "neb entry $name not found, not created\n";
    438                 exit($PS_EXIT_DATA_ERROR);
    439             }
    440             # print "found path: $path\n";
     440            my $path = eval { $neb->find( $name ); };
     441            if ($@ or not defined $path) {
     442                carp "neb entry $name not found, not created\n";
     443                return undef;
     444            }
     445            # print "found path: $path\n";
    441446            return $path;
    442447        }
     
    444449        if ($scheme eq 'path' or $scheme eq 'file') {
    445450            # guaranteed to have a scheme (path:// or file://)
    446             $name = $self->convert_filename_absolute( $name );
    447             # print "resolved path to $name\n";
     451            $name = $self->convert_filename_absolute( $name ) or return undef;
     452            # print "resolved path to $name\n";
    448453        }
    449454    }
     
    454459        if (! -e $dir) {
    455460            my $rc = system "mkdir -p $dir";
    456             die "failed to create directory for $name" unless (!$rc);
     461            ( carp "failed to create directory for $name" and return undef ) unless (!$rc);
    457462        } elsif (! -d $dir ) {
    458             die "parent for $name exists and is not a directory";
    459         }
    460 
    461         open F, ">$name" or die "failed to create $name";
     463            carp "parent for $name exists and is not a directory";
     464            return undef;
     465        }
     466
     467        open F, ">$name" or ( carp "failed to create $name" and return undef );
    462468        close F;
    463         # print "created target $name\n";
     469        # print "created target $name\n";
    464470    }
    465471
     
    473479    my $name = shift;                # File name to check
    474480
    475     $self->file_prepare( $name );
     481    $self->file_prepare( $name ) or return undef;
    476482
    477483    my $scheme = file_scheme($name); # The scheme, e.g., file://, path://
     
    479485        $scheme = lc($scheme);
    480486        if ($scheme eq 'neb') {
    481             $self->_neb_start();
    482             return $self->{nebulous}->open_create( $name );
     487            $self->_neb_start() or ( carp "Unable to start Nebulous" and return undef );
     488            my $fh = eval { $self->{nebulous}->open_create( $name ); };
     489            if ($@ or not defined $fh) {
     490                carp "Unable to open/create Nebulous handle $name";
     491                return undef;
     492            }
     493            return $fh;
    483494        }
    484495        if ($scheme eq 'path' or $scheme eq 'file') {
    485496            # guaranteed to have a scheme (path:// or file://)
    486             $name = $self->convert_filename_absolute( $name );
     497            $name = $self->convert_filename_absolute( $name ) or return undef;
    487498        }
    488499    }
     
    490501    if (-f $name) {
    491502        carp "Unable to create file $name --- file exists.";
    492         exit($PS_EXIT_SYS_ERROR);
     503        return undef;
    493504    }
    494505
     
    496507    unless (open $fh, '>', $name) {
    497508        carp "Unable to create file $name --- $!";
    498         exit($PS_EXIT_SYS_ERROR);
     509        return undef;
    499510    }
    500511    return $fh;
     
    507518    my $name = shift;                # File name to check
    508519
    509     $self->file_prepare( $name );
     520    $self->file_prepare( $name ) or return undef;
    510521
    511522    my $scheme = file_scheme($name); # The scheme, e.g., file://, path://
     
    513524        $scheme = lc($scheme);
    514525        if ($scheme eq 'neb') {
    515             $self->_neb_start();
    516             return $self->{nebulous}->open_create( $name );
     526            $self->_neb_start() or ( carp "Unable to start Nebulous" and return undef );
     527            my $fh = eval { $self->{nebulous}->open_create( $name ) };
     528            if ($@ or not defined $fh) {
     529                carp "Unable to open/create Nebulous handle $name";
     530                return undef;
     531            }
     532            return $fh;
    517533        }
    518534        if ($scheme eq 'path' or $scheme eq 'file') {
    519535            # guaranteed to have a scheme (path:// or file://)
    520             $name = $self->convert_filename_absolute( $name );
     536            $name = $self->convert_filename_absolute( $name ) or return undef;
    521537        }
    522538    }
     
    525541    unless (open $fh, '>>', $name) {
    526542        carp "Unable to create file $name --- $!";
    527         exit($PS_EXIT_SYS_ERROR);
     543        return undef;
    528544    }
    529545    return $fh;
     
    536552    my $name = shift;                # File name to check
    537553
    538     $self->file_prepare( $name );
     554    $self->file_prepare( $name ) or return undef;
    539555
    540556    my $scheme = file_scheme($name); # The scheme, e.g., file://, path://
    541557    if (defined $scheme and lc($scheme) eq 'neb') {
    542         $self->_neb_start();
    543         $name = $self->{nebulous}->create( $name );
     558        $self->_neb_start() or ( carp "Unable to start Nebulous" and return undef );
     559        $name = eval { $self->{nebulous}->create( $name ) };
     560        if ($@ or not defined $name) {
     561            carp "Unable to create Nebulous handle $name";
     562            return undef;
     563        }
    544564    }
    545565
     
    555575    my $scheme = file_scheme($name); # The scheme, e.g., file://, path://
    556576    if (defined $scheme and lc($scheme) eq 'neb') {
    557         $self->_neb_start();
    558         return (defined $self->{nebulous}->find_instances( $name ) ? 1 : 0);
     577        $self->_neb_start() or ( carp "Unable to start Nebulous" and return undef );
     578        my $found = eval { $self->{nebulous}->find_instances( $name ); };
     579        ( carp "Unable to find instances of Nebulous handle $name" and return undef ) if $@;
     580        return (defined $found ? 1 : 0);
    559581    }
    560582
     
    569591    my $target = shift;                # Name of target file
    570592
    571     $self->file_prepare( $target );
     593    $self->file_prepare( $target ) or return undef;
    572594
    573595    my $scheme = file_scheme($target); # The scheme, e.g., file://, path://
    574596    if (defined $scheme and lc($scheme) eq 'neb') {
    575         $self->_neb_start();
    576         $target = $self->{nebulous}->create( $target );
     597        $self->_neb_start() or ( carp "Unable to start Nebulous" and return undef );
     598        $target = eval { $self->{nebulous}->create( $target ); };
     599        if ($@ or not defined $target) {
     600            carp "Unable to create Nebulous handle";
     601            return undef;
     602        }
    577603    }
    578604    $target = $self->file_resolve( $target );
    579605    $source = $self->file_resolve( $source );
    580606
    581     system("cp $source $target") == 0 or (carp "Can't copy file $source to $target." and
    582                                           exit($PS_EXIT_DATA_ERROR));
     607    system("cp $source $target") == 0 or ( carp "Can't copy file $source to $target." and return undef );
    583608    return 1;
    584609}
     
    593618    my $preserve = shift;
    594619
    595     die "pathname must be defined" unless ($pathname);
     620    ( carp "pathname must be defined" and return undef ) unless ($pathname);
    596621
    597622    my $fileRef;
     
    602627
    603628    if ($preserve) {
    604         # we want to keep the file just create it in the current directory 
     629        # we want to keep the file just create it in the current directory
    605630        $fileName = "./$base";
    606         open $fileRef, ">$fileName" or die "can't open $fileName for output";
     631        open $fileRef, ">$fileName" or ( carp "can't open $fileName for output" and return undef );
    607632    } else {
    608633        #  we really want a tempfile, so put it in /tmp
     
    621646    my $scheme = file_scheme($name); # The scheme, e.g., file://, path://
    622647    if (defined $scheme and lc($scheme) eq 'neb') {
    623         $self->_neb_start();
    624         $status = $self->{nebulous}->delete( $name );
     648        $self->_neb_start() or ( carp "Unable to start Nebulous" and return undef );
     649        $status = eval { $self->{nebulous}->delete( $name ); };
     650        ( carp "Unable to delete Nebulous handle $name" and return undef ) if $@;
    625651    } else {
    626         my $resolved = $self->file_resolve($name);
    627         if ($resolved && -e $resolved) {
     652        my $resolved = $self->file_resolve($name) or return undef;
     653        if (defined $resolved and -e $resolved) {
    628654            $status = unlink($resolved);
    629655        }
     
    638664    my $name = shift;
    639665
    640     die "need name" unless $name;
     666    ( carp "need redirection target" and return undef ) unless $name;
    641667
    642668    my $filename = $self->file_resolve($name, 1);
    643669
    644     die "cannot resolve $name" unless $filename;
     670    ( carp "cannot resolve $name" and return undef ) unless $filename;
    645671
    646672    if (! open(STDOUT, ">>$filename") ) {
     
    651677        while (! open STDOUT, ">>$filename" ) {
    652678            if ($try == $max_tries) {
    653                 die "failed to redirect stdout to $filename after trying $max_tries times";
     679                carp "failed to redirect stdout to $filename after trying $max_tries times";
     680                return undef;
    654681            }
    655682            sleep 5;
     
    658685        print STDERR "   redirect stdout to $filename succeded on try $try\n";
    659686    }
    660     open STDERR, ">>$filename" or die "failed to redirect stderr to $filename";
     687    open STDERR, ">>$filename" or ( carp "failed to redirect stderr to $filename" and return undef );
     688
     689    return 1;
    661690}
    662691
     
    676705    my $name = shift;                # File name for which to prepare
    677706    my $workdir = shift;        # Working directory
    678     my $template = shift;        # Template filename from which to get working directory if 
     707    my $template = shift;        # Template filename from which to get working directory if
    679708
    680709    if (defined $workdir) {
     
    692721    # not guaranteed to have a scheme (path:// or file://) - might be /PATH/foobar
    693722    # a relative path (PATH/foobar) is invalid here
    694     my $resolved = $self->convert_filename_absolute( $name );
     723    my $resolved = $self->convert_filename_absolute( $name ) or return undef;
    695724    my ( $vol, $dirs, $file ) = File::Spec->splitpath( $resolved );
    696725    unless (-d $dirs) {
    697         system("mkdir -p $dirs") == 0 or (carp "Can't create directory $dirs" and exit($PS_EXIT_DATA_ERROR));
     726        system("mkdir -p $dirs") == 0 or ( carp "Can't create directory $dirs" and return undef );
    698727    }
    699728
     
    716745    # not guaranteed to have a scheme (path:// or file://) - might be /PATH/foobar
    717746    # a relative path (PATH/foobar) is invalid here
    718     my $resolved = $self->convert_filename_absolute( $outroot );
     747    my $resolved = $self->convert_filename_absolute( $outroot ) or return undef;
    719748    my ( $vol, $dirs, $file ) = File::Spec->splitpath( $resolved );
    720749    unless (-d $dirs) {
    721         system("mkdir -p $dirs") == 0 or (carp "Can't create directory $dirs" and exit($PS_EXIT_DATA_ERROR));
     750        system("mkdir -p $dirs") == 0 or ( carp "Can't create directory $dirs" and return undef );
    722751    }
    723752
     
    734763    unless (defined $self and defined $name) {
    735764        carp "Programming error";
    736         exit($PS_EXIT_PROG_ERROR);
     765        return undef;
    737766    }
    738767
     
    741770
    742771    ## if this is already an absolute path (/PATH/file), just return the path
    743     unless (defined $scheme) { 
     772    unless (defined $scheme) {
    744773        if ($name =~ m|^/|) { return $name; }
    745774        # without a leading slash, this is an error
    746775        carp "Relative file name provided: relative paths are not permitted.";
    747         exit($PS_EXIT_SYS_ERROR);
     776        return undef;
    748777    }
    749778
     
    751780
    752781    if (lc($scheme) eq 'file') {
    753         # the above strips of the leading slash; replace it for file:// 
     782        # the above strips of the leading slash; replace it for file://
    754783        $name = '/' . $name;
    755784        return $name;
     
    764793    }
    765794
    766     # looks like we cannot reach here without an invalid scheme. 
    767     # programming error?
    768     # return $name;
    769 
    770     carp "Programming error";
    771     exit($PS_EXIT_PROG_ERROR);
     795    # It's already absolute
     796    return $name;
    772797}
    773798
     
    777802    my $self = shift;                # Configuration object
    778803    my $name = shift;                # raw name
    779    
     804
    780805    unless (defined $self and defined $name) {
    781806        carp "Programming error";
    782         exit($PS_EXIT_PROG_ERROR);
    783     }
    784    
     807        return undef;
     808    }
     809
    785810    # First, check to see if it's already in a relative form
    786811    my $scheme = file_scheme($name); # The scheme, e.g., file, path
     
    790815            # We may as well search for a 'better' path
    791816            # guaranteed to have a scheme (path:// or file://)
    792             $name = $self->convert_filename_absolute( $name );
     817            $name = $self->convert_filename_absolute( $name ) or return undef;
    793818        } elsif ($scheme eq 'neb') {
    794819            # No chance of changing anything --- move along
     
    796821        }
    797822    }
    798    
     823
    799824    $name = File::Spec->canonpath( $name); # Clean up
    800825    my @dirs = File::Spec->splitdir( $name );
    801    
     826
    802827    my $path_list = metadataLookupMD($self->{_siteConfig}, 'DATAPATH'); # List of paths
    803828    my $best_path;
     
    809834      $path =~ s|/*$||;
    810835      my @path_dirs = File::Spec->splitdir( $path );
    811      
     836
    812837      # Check if the path is suitable
    813838      next if scalar @path_dirs > scalar @dirs;
     
    823848      }
    824849  }
    825    
     850
    826851    $name =~ s|^/||;
    827852    $name =~ s|/$||;
     
    845870    unless (defined $self and defined $name and defined $type) {
    846871        carp "Programming error";
    847         exit($PS_EXIT_PROG_ERROR);
     872        return undef;
    848873    }
    849874
     
    854879            return undef;
    855880        }
    856        
     881
    857882        # rejections are saved as a recipe: REJECTIONS
    858883        my @rejContents = `ppConfigDump -dump-recipe REJECTIONS -camera $camera -`;
    859        
     884
    860885        # load from resulting psMetadataConfig
    861886        $self->{rejection} = $parser->parse( join '', @rejContents); # The rejection metadata
    862887        unless (defined $self->{rejection}) {
    863888            carp "Unable to parse REJECTION recipe for $camera.";
    864             exit($PS_EXIT_CONFIG_ERROR);
     889            return undef;
    865890        }
    866891    }
     
    873898          unless ($item->{class} eq "metadata") {
    874899              carp "$name within REJECTIONS is not of type METADATA";
    875               exit($PS_EXIT_PROG_ERROR);
     900              return undef;
    876901          }
    877902          my $limits = $item->{value}; # List of rejection limits
     
    880905          foreach my $limit (@$limits) {
    881906              if ($limit->{name} eq 'FILTER') {
    882                   if ($limit->{value} eq '*' or
    883                       (defined $filter and
    884                        $limit->{value} eq $filter)) {
     907                  if ($limit->{value} eq '*' or (defined $filter and $limit->{value} eq $filter)) {
    885908                      last;
    886909                  }
     
    888911              }
    889912          }
    890          
     913
    891914          foreach my $limit (@$limits) {
    892915              return $limit->{value} if $limit->{name} eq $name;
     
    915938    unless (defined $self and defined $name and defined $output) {
    916939        carp "Programming error: required inputs left undefined";
    917         exit($PS_EXIT_PROG_ERROR);
     940        return undef;
    918941    }
    919942
     
    929952            return undef;
    930953        }
    931        
     954
    932955        $filerules = metadataLookup($camera, 'FILERULES');        # File rules
    933956        unless (defined $filerules) {
     
    935958            return undef;
    936959        }
    937        
     960
    938961        if ($filerules->{class} eq "scalar" and $filerules->{type} eq "STR") {
    939962            # Allow indirection to a file
    940963            my $filename = $self->_find_config($filerules->{value}); # Resolved filename
     964            ( carp "Unable to find file rules file" and return undef ) unless defined $filename;
     965
    941966            # Read the file
    942967            my $file;                # File handle
    943968            unless (open $file, $filename) {
    944969                carp "Unable to open filerules file $filename: $!";
    945                 exit($PS_EXIT_CONFIG_ERROR);
     970                return undef;
    946971            }
    947972            my @contents = <$file>;
     
    973998        unless (defined $component) {
    974999            carp "Programming error";
    975             exit($PS_EXIT_PROG_ERROR);
     1000            return undef;
    9761001        }
    9771002        $filename =~ s/\{CHIP\.NAME\}/$component/;
     
    9801005
    9811006    return $filename;
    982 }   
     1007}
    9831008
    9841009# Return an EXTNAME From the EXTNAME.RULE table in the camera configuration
     
    9911016    unless (defined $self and defined $name) {
    9921017        carp "Programming error";
    993         exit($PS_EXIT_PROG_ERROR);
     1018        return undef;
    9941019    }
    9951020
     
    10151040        unless (defined $component) {
    10161041            carp "Programming error";
    1017             exit($PS_EXIT_PROG_ERROR);
     1042            return undef;
    10181043        }
    10191044        $extname =~ s/\{CHIP\.NAME\}/$component/;
     
    10211046
    10221047    return $extname;
    1023 }   
     1048}
    10241049
    10251050# Return catdir for tessellation, from TESSELLATIONS within the site configuration
     
    10311056    unless (defined $self and defined $self->{_siteConfig} and defined $tess_id) {
    10321057        carp "Programming error";
    1033         exit($PS_EXIT_PROG_ERROR);
     1058        return undef;
    10341059    }
    10351060
     
    10371062    unless (defined $tessellations) {
    10381063        carp "Can't find TESSELLATIONS in site configuration.\n";
    1039         exit($PS_EXIT_CONFIG_ERROR);
     1064        return undef;
    10401065    }
    10411066
     
    10501075    if (defined $scheme and lc($scheme) eq 'neb') {
    10511076        carp "Tessellation $tess_id refers to a Nebulous path: $catdir\n";
    1052         exit($PS_EXIT_CONFIG_ERROR);
     1077        return undef;
    10531078    }
    10541079
     
    10651090    unless (defined $self and defined $self->{_siteConfig} and defined $dvodb) {
    10661091        carp "Programming error";
    1067         exit($PS_EXIT_PROG_ERROR);
     1092        return undef;
    10681093    }
    10691094
     
    10711096    unless (defined $catdirs) {
    10721097        carp "Can't find DVO.CATDIRS in site configuration.\n";
    1073         exit($PS_EXIT_CONFIG_ERROR);
     1098        return undef;
    10741099    }
    10751100
     
    10841109    if (defined $scheme and lc($scheme) eq 'neb') {
    10851110        carp "DVO catdir $dvodb refers to a Nebulous path: $catdir\n";
    1086         exit($PS_EXIT_CONFIG_ERROR);
     1111        return undef;
    10871112    }
    10881113
     
    10981123    unless (defined $self and defined $self->{_siteConfig} and defined $dvodb) {
    10991124        carp "Programming error";
    1100         exit($PS_EXIT_PROG_ERROR);
     1125        return undef;
    11011126    }
    11021127
     
    11041129    unless (defined $catdirs) {
    11051130        carp "Can't find PSASTRO.CATDIRS in site configuration.\n";
    1106         exit($PS_EXIT_CONFIG_ERROR);
     1131        return undef;
    11071132    }
    11081133
     
    11171142    if (defined $scheme and lc($scheme) eq 'neb') {
    11181143        carp "PSASTRO catdir $dvodb refers to a Nebulous path: $catdir\n";
    1119         exit($PS_EXIT_CONFIG_ERROR);
     1144        return undef;
    11201145    }
    11211146
     
    11301155    unless (defined $self) {
    11311156        carp "Programming error";
    1132         exit($PS_EXIT_PROG_ERROR);
     1157        return undef;
    11331158    }
    11341159
     
    11581183    unless (defined $self and defined $reduction and defined $name) {
    11591184        carp "Programming error --- inputs undefined";
    1160         exit($PS_EXIT_PROG_ERROR);
     1185        return undef;
    11611186    }
    11621187
     
    11801205            return undef;
    11811206        }
    1182        
     1207
    11831208        if ($reductionClasses->{class} eq "scalar" and $reductionClasses->{type} eq "STR") {
    11841209            # Allow indirection to a file
    11851210            my $filename = $self->_find_config($reductionClasses->{value}); # Resolved filename
     1211            ( carp "Unable to find reduction classes file" and return undef ) unless defined $filename;
    11861212            # Read the file
    11871213            my $file;                # File handle
    11881214            unless (open $file, $filename) {
    11891215                carp "Unable to open reductionClasses file $filename: $!";
    1190                 exit($PS_EXIT_CONFIG_ERROR);
     1216                return undef;
    11911217            }
    11921218            my @contents = <$file>;
     
    12031229
    12041230    my $class = metadataLookupMD($reductionClasses, $reduction) or # Class of interest
    1205         (carp "Can't find $reduction in REDUCTION in camera configuration.\n" and
    1206          exit($PS_EXIT_CONFIG_ERROR));
     1231        ( carp "Can't find $reduction in REDUCTION in camera configuration.\n" and return undef );
    12071232
    12081233    my $actual = metadataLookupStr($class, $name) or # The actual recipe name of interest
    1209         (carp "Can't find $name in $class in REDUCTION in camera configuration.\n" and
    1210          exit($PS_EXIT_CONFIG_ERROR));
     1234        (carp "Can't find $name in $class in REDUCTION in camera configuration.\n" and return undef );
    12111235
    12121236    return $actual;
     
    12261250    }
    12271251
    1228     my $dvoImageExtract = can_run('dvoImageExtract') or die "Can't find dvoImageExtract";
    1229    
     1252    my $dvoImageExtract = can_run('dvoImageExtract') or ( carp "Can't find dvoImageExtract" and return undef );
     1253
    12301254    my $tess_dir = $self->tessellation_catdir( $tess_id ); # Tessellation catdir for DVO
    12311255    unless (defined $tess_dir) {
    12321256        carp "Can't get list of tessellations.";
    1233         return 0;
    1234     }
    1235     $tess_dir = $self->convert_filename_absolute( $tess_dir );
     1257        return undef;
     1258    }
     1259    $tess_dir = $self->convert_filename_absolute( $tess_dir ) or return undef;
    12361260
    12371261    unless ($self->file_exists( $outname )) {
    1238         my $outnameResolved = $self->file_create( $outname ); # Resolved filename, for Nebulous
     1262        my $outnameResolved = $self->file_create( $outname ) or return undef; # Resolved filename, for Nebulous
    12391263        my $command = "$dvoImageExtract -D CATDIR $tess_dir $skycell_id -o $outnameResolved";
    12401264        my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    12411265            run(command => $command, verbose => $verbose);
    1242         die "Unable to perform dvoImageExtract for $tess_id $skycell_id\n" unless ($success and $self->file_exists( $outname ));
     1266        ( carp "Unable to perform dvoImageExtract for $tess_id $skycell_id\n" and return undef ) unless ($success and $self->file_exists( $outname ));
    12431267    }
    12441268
     
    12581282        unless (defined $value) {
    12591283            carp "Unable to find environment variable $name";
    1260             exit($PS_EXIT_SYS_ERROR);
     1284            return undef;
    12611285        }
    12621286        $dir =~ s/\$\{?$name\}?/$value\//;
     
    12721296    unless (defined $mdc and defined $name) {
    12731297        carp "Programming error";
    1274         exit($PS_EXIT_PROG_ERROR);
     1298        return undef;
    12751299    }
    12761300
     
    12851309    return undef;
    12861310}
    1287    
     1311
    12881312
    12891313# Lookup the metadata, checking the type is STR
     
    13251349    unless (defined $mdc and defined $name) {
    13261350        carp "Programming error";
    1327         exit($PS_EXIT_PROG_ERROR);
     1351        return undef;
    13281352    }
    13291353
  • branches/cnb_branches/cnb_branch_20090301/archive/conv_variance/fake.c

    r20210 r23352  
    4747    psFree(weight);
    4848
    49     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 0);
     49    psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS);
    5050
    5151    psImage *bright = psImageAlloc(IMAGE_SIZE, IMAGE_SIZE, PS_TYPE_F32);
  • branches/cnb_branches/cnb_branch_20090301/archive/conv_variance/phot.c

    r20210 r23352  
    5252
    5353    psStats *bgStats = psStatsAlloc(PS_STAT_ROBUST_MEDIAN);
    54     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 0);
     54    psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS);
    5555    psImageBackground(bgStats, NULL, image, mask, maskVal, rng);
    5656    double bg = bgStats->robustMedian;
  • branches/cnb_branches/cnb_branch_20090301/dbconfig/changes.txt

    r21434 r23352  
    795795ALTER TABLE magicInputSkyfile DROP PRIMARY KEY, ADD PRIMARY KEY(magic_id, diff_id, node);
    796796
    797 
    798 
    799797-- Version: 1.1.48
    800798
     
    834832    WHERE warpImfile.skycell_id IS NULL;
    835833
    836 
    837 
     834-- Version: 1.1.49 (change detrend sequence)
     835
     836show create table detResidImfile;
     837alter table detResidImfile drop foreign key detResidImfile_ibfk_3;
  • branches/cnb_branches/cnb_branch_20090301/dbconfig/config.md

    r21310 r23352  
    22    pkg_name        STR     ippdb
    33    pkg_namespace   STR     ippdb
    4     pkg_version     STR     1.1.48
     4    pkg_version     STR     1.1.49
    55END
  • branches/cnb_branches/cnb_branch_20090301/dbconfig/det.md

    r19620 r23352  
    9090    class_id    STR         64      # Primary Key
    9191    uri         STR         255
    92     recipe      STR         64
    93     bg          F64         0.0
    94     bg_stdev    F64         0.0
    95     bg_mean_stdev   F64     0.0
    96     user_1      F64         0.0
    97     user_2      F64         0.0
    98     user_3      F64         0.0
    99     user_4      F64         0.0
    100     user_5      F64         0.0
    101 #   XXX does it make sense to 'clean' the stacked imfiled?
     92    # XXX missing path_base
     93    recipe      STR         64
     94    bg          F64         0.0
     95    bg_stdev    F64         0.0
     96    bg_mean_stdev   F64     0.0
     97    user_1      F64         0.0
     98    user_2      F64         0.0
     99    user_3      F64         0.0
     100    user_4      F64         0.0
     101    user_5      F64         0.0
     102    #   XXX does it make sense to 'clean' the stacked imfiled? (EAM: yes)
    102103    data_state  STR         64      # full, cleaned, purged (only track end states; request states are in detRunSummary by iteration)
    103104    fault       S16         0       # Key NOT NULL
     
    148149    fault       S16         0       # Key NOT NULL
    149150END
    150 
    151 #detMasterFrame METADATA
    152 #    det_id      S64         0       # Primary Key
    153 #    iteration   S32         0       # Primary Key
    154 #    comment     STR         255
    155 #END
    156 #
    157 ## drop?
    158 #detMasterImfile METADATA
    159 #    det_id      S64         0       # Primary Key
    160 #    class_id    STR         64      # Primary Key
    161 #    uri         STR         255
    162 #    recipe      STR         64
    163 #END
    164151
    165152detResidImfile METADATA
  • branches/cnb_branches/cnb_branch_20090301/doc/pslib/psLibSDRS.tex

    r12382 r23352  
    11971197while returning the type involves descending through a case statement.
    11981198
     1199To compare the types of two pointers without knowing their types, the following function may be used:
     1200
     1201\begin{prototype}
     1202bool psMemTypeEqual (void *ptr1, ///< pointer to first psMemory object
     1203                     void *ptr2 ///< pointer to second psMemory object
     1204  );
     1205\end{prototype}
     1206
    11991207%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
    12001208
  • branches/cnb_branches/cnb_branch_20090301/ippMonitor/def/detNormalizedStatImfile_failure.d

    r19726 r23352  
    44MENU  ipp.detrend.dat
    55
    6 where fault > 0
     6WHERE fault > 0
    77
    88#     field    size  format  name   show   link to     extras
  • branches/cnb_branches/cnb_branch_20090301/ippMonitor/def/detStackedImfile.d

    r18193 r23352  
    1 TABLE detStackedImfile
     1TABLE detStackedImfile, detRun
    22TITLE detStackedImfile
    33FILE  detStackedImfile.php
    44MENU  ipp.imfiles.dat
    55
    6 #     field         size  format  name                   show  link to     extras
    7 FIELD det_id,         7,  %s,    det_id
    8 FIELD iteration,      5,  %s,    iteration
    9 FIELD class_id,       8,  %s,    class_id
    10 FIELD fault,          5,  %d,    fault
    11 FIELD bg,             8,  %f,    backgnd
    12 FIELD bg_stdev,       8,  %f,    stdev
    13 FIELD bg_mean_stdev,  8,  %f,    [stdev]
    14 FIELD uri,           20,  %s,    uri
     6WHERE detStackedImfile.det_id = detRun.det_id
     7
     8# XXX change uri to path_base in db
     9ARGS  ARG1 detStackedImfile.det_id=$det_id
     10ARGS  ARG1 detStackedImfile.iteration=$iteration
     11ARGS  ARG1 camera=$detRun.camera
     12ARGS  ARG1 basename=$detStackedImfile.uri
     13
     14#     field         size  format  name      show  link to     extras
     15FIELD detStackedImfile.det_id,         7,  %s,    det_id
     16FIELD detStackedImfile.iteration,      5,  %s,    iteration
     17FIELD detStackedImfile.class_id,       8,  %s,    class_id,   value, detStackedImfile.php, ARG1
     18FIELD detStackedImfile.fault,          5,  %d,    fault
     19FIELD detStackedImfile.bg,             8,  %f,    backgnd
     20FIELD detStackedImfile.bg_stdev,       8,  %f,    stdev
     21FIELD detStackedImfile.bg_mean_stdev,  8,  %f,    [stdev]
     22FIELD detStackedImfile.uri,           20,  %s,    uri
    1523# FIELD recipe, 20,   recipe
    1624
    1725TD_CLASS list_off $fault > 0
     26
     27TAIL PHP insert_log ('LOG.EXP');
  • branches/cnb_branches/cnb_branch_20090301/ippMonitor/raw/getimage.php

    r14128 r23352  
    2222putenv("PATH=$BINDIR:$PATH");
    2323
    24 # echo "args: $args<br>";
     24if ($debug) {
     25  echo "args: $args<br>";
     26  echo "path: $PATH<br>";
     27  echo "perl: $PERLLIB<br>";
     28}
    2529
    2630# $basename may contain filename@filerule
     
    3135
    3236# $filerule = strtok("@");
    33 # echo "basename: $basename<br>";
    34 # echo "filerule: $filerule<br>";
     37
     38if ($debug) {
     39  echo "basename: $basename<br>";
     40  echo "filerule: $filerule<br>";
     41}
    3542
    3643# need to supply the camera as well...
     
    4956$basename = escapeshellarg($basename);
    5057$basename = str_replace ('..','',$basename);
     58
     59if ($debug) {
     60  exec ("which ipp_filename.pl", $output, $status);
     61  echo "output:   $output[0]<br>";
     62  echo "status:   $status<br>";
     63
     64  exec ("whoami", $output, $status);
     65  echo "output:   $output[0]<br>";
     66  echo "status:   $status<br>";
     67}
    5168
    5269exec ("ipp_filename.pl --site=$SITE --basename $basename --filerule $filerule --camera $camera --class_id $class_id", $output, $status);
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/Build.PL

    r20931 r23352  
    8080        scripts/summit_copy.pl
    8181        scripts/ipp_image_path.pl
     82        scripts/dist_component.pl
     83        scripts/dist_advancerun.pl
    8284    )],
    8385    dist_abstract => 'Scripts for running the Pan-STARRS IPP',
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/calibrate_dvo.pl

    r20100 r23352  
    5252my $caltool  = can_run('caltool')  or (warn "Can't find caltool"  and $missing_tools = 1);
    5353
    54 if ($missing_tools) { 
     54if ($missing_tools) {
    5555    warn ("Can't find required tools");
    56     exit($PS_EXIT_CONFIG_ERROR); 
     56    exit($PS_EXIT_CONFIG_ERROR);
    5757}
    5858
     
    7474        cache_run(command => $command, verbose => 1);
    7575
    76     unless ($success) { 
     76    unless ($success) {
    7777        $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    7878        &my_die ("Unable to perform addstar -resort on region $region: $error_code", $cal_id, $region, "RESORT", $status, $dbname);
     
    8383{
    8484    foreach my $filter (@filters) {
    85         my $command = "$relphot $filter";
    86         $command .= "-D CATDIR $dvodb";
    87         $command .= "-region $RAs $RAe $DECs $DECe";
     85        my $command = "$relphot $filter";
     86        $command .= "-D CATDIR $dvodb";
     87        $command .= "-region $RAs $RAe $DECs $DECe";
    8888
    89         my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    90             cache_run(command => $command, verbose => 1);
     89        my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     90            cache_run(command => $command, verbose => 1);
    9191
    92         unless ($success) {
    93             $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    94             &my_die ("Unable to perform addstar -resort on region $region: $error_code", $cal_id, $region, "RELPHOT", $status, $dbname);
    95         }
     92        unless ($success) {
     93            $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     94            &my_die ("Unable to perform addstar -resort on region $region: $error_code", $cal_id, $region, "RELPHOT", $status, $dbname);
     95        }
    9696    }
    9797}
     
    101101if (0) {
    102102    foreach my $filter (@filters) {
    103         my $command = "$uniphot $filter";
    104         $command .= "-D CATDIR $dvodb";
    105         $command .= "-region $RAs $RAe $DECs $DECe";
     103        my $command = "$uniphot $filter";
     104        $command .= "-D CATDIR $dvodb";
     105        $command .= "-region $RAs $RAe $DECs $DECe";
    106106
    107         my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    108             cache_run(command => $command, verbose => 1);
     107        my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     108            cache_run(command => $command, verbose => 1);
    109109
    110         unless ($success) {
    111             $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    112             &my_die ("Unable to perform addstar -resort on region $region: $error_code", $cal_id, $region, "UNIPHOT", $status, $dbname);
    113         }
     110        unless ($success) {
     111            $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     112            &my_die ("Unable to perform addstar -resort on region $region: $error_code", $cal_id, $region, "UNIPHOT", $status, $dbname);
     113        }
    114114    }
    115115}
     
    121121
    122122    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    123         cache_run(command => $command, verbose => 1);
     123        cache_run(command => $command, verbose => 1);
    124124
    125     unless ($success) { 
    126         $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    127         &my_die ("Unable to perform addstar -resort on region $region: $error_code", $cal_id, $region, "RELASTRO.OBJECTS", $status, $dbname);
     125    unless ($success) {
     126        $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     127        &my_die ("Unable to perform addstar -resort on region $region: $error_code", $cal_id, $region, "RELASTRO.OBJECTS", $status, $dbname);
    128128    }
    129129}
     
    135135
    136136    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    137         cache_run(command => $command, verbose => 1);
     137        cache_run(command => $command, verbose => 1);
    138138
    139     unless ($success) { 
    140         $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    141         &my_die ("Unable to perform addstar -resort on region $region: $error_code", $cal_id, $region, "RELASTRO.IMAGES", $status, $dbname);
     139    unless ($success) {
     140        $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     141        &my_die ("Unable to perform addstar -resort on region $region: $error_code", $cal_id, $region, "RELASTRO.IMAGES", $status, $dbname);
    142142    }
    143143}
     
    169169    my $region    = shift;
    170170    my $last_step = shift;
    171     my $status    = shift;
    172     my $dbname    = shift;
     171    my $status    = shift;
     172    my $dbname    = shift;
    173173
    174174    carp($msg);
    175175    if (defined $cal_id && defined $region && defined $last_step && defined $status and not $no_update) {
    176176        my $command = "$caltool -addcalrun";
    177         $command .= " -cal_id $cal_id";
     177        $command .= " -cal_id $cal_id";
    178178        $command .= " -region $region";
    179         $command .= " -last_step $last_step";
    180         $command .= " -state $status";
     179        $command .= " -last_step $last_step";
     180        $command .= " -state $status";
    181181        $command .= " -dbname $dbname" if defined $dbname;
    182182        system ($command);
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/camera_exp.pl

    r22430 r23352  
    2222use PS::IPP::Config 1.01 qw( :standard );
    2323use File::Temp qw( tempfile );
    24 
    25 my $ipprc = PS::IPP::Config->new(); # IPP configuration
    2624
    2725use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
     
    7068    defined $camera;
    7169
    72 # Unhandled exceptions should be passed on to my_die so they get pushed into the database
    73 $SIG{__DIE__} = sub { die @_ if $^S;
    74                       my_die( $_[0], $cam_id, $PS_EXIT_UNKNOWN_ERROR ); };
    75 
    76 $ipprc->define_camera($camera);
     70my $ipprc = PS::IPP::Config->new( $camera ) or my_die( "Unable to set up", $cam_id, $PS_EXIT_CONFIG_ERROR ); # IPP configuration
    7771
    7872my $logDest = $ipprc->filename("LOG.EXP", $outroot) or &my_die("Missing entry from camera config", $cam_id, $PS_EXIT_CONFIG_ERROR);
     
    8478
    8579if ($redirect) {
    86     $ipprc->redirect_output($logDest);
     80    $ipprc->redirect_output($logDest) or my_die( "Unable to redirect output", $cam_id, $PS_EXIT_SYS_ERROR );
    8781    print "\n\n";
    8882    print "Starting script $0 on $host\n\n";
     
    372366    my $cam_id = shift; # Camtool identifier
    373367    my $exit_code = shift; # Exit code to add
     368
     369    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
    374370
    375371    carp($msg);
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/chip_imfile.pl

    r22430 r23352  
    2020use PS::IPP::Metadata::Config;
    2121use PS::IPP::Config 1.01 qw( :standard );
    22 
    23 my $ipprc = PS::IPP::Config->new(); # IPP configuration
    2422
    2523use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
     
    7068    defined $run_state;
    7169
    72 # Unhandled exceptions should be passed on to my_die so they get pushed into the database
    73 $SIG{__DIE__} = sub { die @_ if $^S;
    74                       my_die( $_[0], $exp_id, $chip_id, $class_id, $PS_EXIT_UNKNOWN_ERROR ); };
    75 
    76 $ipprc->define_camera($camera);
     70my $ipprc = PS::IPP::Config->new( $camera ) or my_die( "Unable to set up", $exp_id, $chip_id, $class_id, $PS_EXIT_CONFIG_ERROR ); # IPP configuration
    7771
    7872my $logDest = $ipprc->filename("LOG.IMFILE", $outroot, $class_id) or &my_die("Missing entry from camera config", $exp_id, $chip_id, $class_id, $PS_EXIT_CONFIG_ERROR);
     
    8074
    8175if ($redirect) {
    82     $ipprc->redirect_output($logDest);
     76    $ipprc->redirect_output($logDest) or my_die( "Unable to redirect output", $exp_id, $chip_id, $class_id, $PS_EXIT_SYS_ERROR );
    8377    print STDOUT "\n\n";
    8478    print STDOUT "Starting script $0 on $host\n\n";
     
    254248    # run_state, outputImage, and outroot are globals
    255249
     250    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
     251
    256252    carp($msg);
    257253    if (defined $chip_id and defined $class_id and not $no_update) {
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/detrend_correct_imfile.pl

    r22430 r23352  
    1818use PS::IPP::Metadata::Config;
    1919use PS::IPP::Config 1.01 qw( :standard );
    20 
    21 my $ipprc = PS::IPP::Config->new(); # IPP configuration
    2220
    2321use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
     
    6058    and defined $camera;
    6159
    62 # Unhandled exceptions should be passed on to my_die so they get pushed into the database
    63 $SIG{__DIE__} = sub { die @_ if $^S;
    64                       my_die( $_[0], $det_id, $class_id, $PS_EXIT_UNKNOWN_ERROR ); };
    65 
    66 # XXX this exits with status = 0 on failure
    67 $ipprc->define_camera($camera);
    68 
     60my $ipprc = PS::IPP::Config->new( $camera ) or my_die( "Unable to set up", $det_id, $class_id, $PS_EXIT_CONFIG_ERROR ); # IPP configuration
    6961if ($redirect) {
    7062    my $logDest = $ipprc->filename("LOG.IMFILE", $outroot, $class_id)
    7163       or &my_die("Missing entry from camera config", $det_id, $class_id, $PS_EXIT_CONFIG_ERROR);
    72     $ipprc->redirect_output($logDest);
     64    $ipprc->redirect_output($logDest) or my_die( "Unable to redirect output", $det_id, $class_id, $PS_EXIT_SYS_ERROR );
    7365}
    7466
     
    132124    my $exit_code = shift; # Exit code to add
    133125
     126    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
     127
    134128    carp($msg);
    135129    if (defined $det_id and defined $class_id and not $no_update) {
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/detrend_norm_apply.pl

    r22430 r23352  
    1717use PS::IPP::Metadata::Config;
    1818use PS::IPP::Config 1.01 qw( :standard );
    19 
    20 my $ipprc = PS::IPP::Config->new(); # IPP configuration
    2119
    2220use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
     
    4038    'iteration|n=s'     => \$iter,       # Iteration
    4139    'class_id|i=s'      => \$class_id,   # Class ID
    42     'value|v=s'         => \$value,      # Value to multiple (for normalisation)
     40    'value|v=s'         => \$value,      # Value to apply (for normalisation)
    4341    'input_uri|u=s'     => \$input_uri,  # Input file
    4442    'camera|c=s'        => \$camera,     # Camera
     
    6462    defined $outroot;
    6563
    66 # Unhandled exceptions should be passed on to my_die so they get pushed into the database
    67 $SIG{__DIE__} = sub { die @_ if $^S;
    68                       my_die( $_[0], $det_id, $iter, $class_id, $PS_EXIT_UNKNOWN_ERROR ); };
    69 
    70 $ipprc->define_camera($camera);
     64my $ipprc = PS::IPP::Config->new( $camera ) or my_die( "Unable to set up", $det_id, $iter, $class_id, $PS_EXIT_CONFIG_ERROR ); # IPP configuration
    7165
    7266my $logDest = $ipprc->filename("LOG.IMFILE", $outroot, $class_id)
    7367        or &my_die("Missing entry from camera config", $det_id, $iter, $class_id, $PS_EXIT_CONFIG_ERROR);
    74 $ipprc->redirect_output($logDest) if $redirect;
     68$ipprc->redirect_output($logDest) or my_die( "Unable to redirect output", $det_id, $iter, $class_id, $PS_EXIT_SYS_ERROR ) if $redirect;
    7569
    7670my $RECIPE_PPIMAGE = 'PPIMAGE_N'; # Recipe to use with ppImage
     
    202196    my $exit_code = shift;      # Exit code to add
    203197
     198    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
     199
    204200    carp($msg);
    205201    if (defined $det_id and defined $iter and defined $class_id and not $no_update) {
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/detrend_norm_calc.pl

    r22430 r23352  
    1919use PS::IPP::Metadata::List qw( parse_md_list );
    2020use PS::IPP::Config 1.01 qw( :standard );
    21 
    22 my $ipprc = PS::IPP::Config->new(); # IPP configuration
    2321
    2422use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
     
    5755    defined $outroot;
    5856
    59 # Unhandled exceptions should be passed on to my_die so they get pushed into the database
    60 $SIG{__DIE__} = sub { die @_ if $^S;
    61                       my_die( $_[0], $det_id, $iter, $PS_EXIT_UNKNOWN_ERROR ); };
     57my $ipprc = PS::IPP::Config->new() or my_die( "Unable to set up", $det_id, $iter, $PS_EXIT_CONFIG_ERROR ); # IPP configuration
    6258
    6359my $logfile = $outroot . ".log";
    64 
    65 $ipprc->redirect_output($logfile) if $redirect;
     60$ipprc->redirect_output($logfile) or my_die( "Unable to redirect output", $det_id, $iter, $PS_EXIT_SYS_ERROR ) if $redirect;
    6661
    6762use constant STATISTIC => 'bg'; # Background statistic to use from the database
     
    9590my @files;                      # The input files
    9691{
    97     my $command = "$dettool -processedimfile";
    98     $command .= " -det_id $det_id"; # Command to run
     92    my $command = "$dettool -residimfile";
     93    $command .= " -det_id $det_id";
     94    $command .= " -iteration $iter";
    9995    $command .= " -included"; # only use the inputs for this detrend run to calculate the norm
    10096    $command .= " -dbname $dbname" if defined $dbname;
     
    10399    print "Running [$command]...\n" if $verbose;
    104100    if (not run(\@command, \$stdin, \$stdout, \$stderr)) {
    105         &my_die("Unable to perform dettool -processedimfile on detrend $det_id/$iter: $?",
     101        &my_die("Unable to perform dettool -residimfile on detrend $det_id/$iter: $?",
    106102                $det_id, $iter, $PS_EXIT_SYS_ERROR);
    107103    }
     
    233229    my $iter = shift;           # Iteration
    234230    my $exit_code = shift;      # Exit code to add
     231
     232    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
    235233
    236234    carp($msg);
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/detrend_norm_exp.pl

    r22430 r23352  
    1919use PS::IPP::Metadata::List qw( parse_md_list );
    2020use File::Temp qw( tempfile );
    21 
    22 my $ipprc = PS::IPP::Config->new(); # IPP configuration
    2321
    2422use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
     
    6058    defined $outroot;
    6159
    62 # Unhandled exceptions should be passed on to my_die so they get pushed into the database
    63 $SIG{__DIE__} = sub { die @_ if $^S;
    64                       my_die( $_[0], $det_id, $iter, $PS_EXIT_UNKNOWN_ERROR ); };
    65 
     60my $ipprc = PS::IPP::Config->new( $camera ) or my_die( "Unable to set up", $det_id, $iter, $PS_EXIT_CONFIG_ERROR ); # IPP configuration
    6661my $logfile = $outroot . ".log";
    67 
    68 $ipprc->redirect_output($logfile) if $redirect;
    69 
    70 $ipprc->define_camera($camera);
     62$ipprc->redirect_output($logfile) or my_die( "Unable to redirect output", $det_id, $iter, $PS_EXIT_SYS_ERROR ) if $redirect;
    7163
    7264# Recipes to use based on reduction class
     
    190182    my $iter = shift;           # Iteration
    191183    my $exit_code = shift; # Exit code to add
     184
     185    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
    192186
    193187    carp($msg);
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/detrend_process_exp.pl

    r22430 r23352  
    1919use PS::IPP::Metadata::List qw( parse_md_list );
    2020use File::Temp qw( tempfile );
    21 
    22 my $ipprc = PS::IPP::Config->new(); # IPP configuration
    2321
    2422use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
     
    6361    defined $outroot;
    6462
    65 # Unhandled exceptions should be passed on to my_die so they get pushed into the database
    66 $SIG{__DIE__} = sub { die @_ if $^S;
    67                       my_die( $_[0], $det_id, $exp_id, $PS_EXIT_UNKNOWN_ERROR ); };
    68 
    69 $ipprc->define_camera($camera);
    70 
     63my $ipprc = PS::IPP::Config->new( $camera ) or my_die( "Unable to set up", $det_id, $exp_id, $PS_EXIT_CONFIG_ERROR ); # IPP configuration
    7164if ($redirect) {
    7265    my $logDest = $ipprc->filename("LOG.EXP", $outroot, "NONE")
    7366        or &my_die("Missing entry in file rules", $det_id, $exp_id, $PS_EXIT_CONFIG_ERROR);
    74     $ipprc->redirect_output($logDest);
     67    $ipprc->redirect_output($logDest) or my_die( "Unable to redirect output", $det_id, $exp_id, $PS_EXIT_SYS_ERROR );
    7568}
    7669
     
    204197    my $exp_id = shift; # Exposure tag
    205198    my $exit_code = shift; # Exit code to add
     199
     200    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
    206201
    207202    carp($msg);
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/detrend_process_imfile.pl

    r22430 r23352  
    1717use PS::IPP::Metadata::Config;
    1818use PS::IPP::Config 1.01 qw( :standard );
    19 
    20 my $ipprc = PS::IPP::Config->new(); # IPP configuration
    2119
    2220use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
     
    6563    defined $outroot;
    6664
    67 # Unhandled exceptions should be passed on to my_die so they get pushed into the database
    68 $SIG{__DIE__} = sub { die @_ if $^S;
    69                       my_die( $_[0], $det_id, $exp_id, $class_id, $PS_EXIT_UNKNOWN_ERROR ); };
    70 
    71 # XXX this exits with status = 0 on failure
    72 $ipprc->define_camera($camera);
    73 
     65my $ipprc = PS::IPP::Config->new( $camera ) or my_die( "Unable to set up", $det_id, $exp_id, $class_id, $PS_EXIT_CONFIG_ERROR ); # IPP configuration
    7466my $logDest = $ipprc->filename("LOG.IMFILE", $outroot, $class_id) or &my_die("Missing entry from camera config", $det_id, $exp_id, $class_id, $PS_EXIT_CONFIG_ERROR);
    75 
    76 $ipprc->redirect_output($logDest) if $redirect;
     67$ipprc->redirect_output($logDest) or my_die( "Unable to redirect output", $det_id, $exp_id, $class_id, $PS_EXIT_SYS_ERROR ) if $redirect;
    7768
    7869# Recipes to use as a function of detrend type
     
    8172my $jpeg_recipe = $ipprc->reduction($reduction, uc($det_type) . '_JPEG_IMAGE'); # Recipe name for JPEG
    8273
     74# The output file rule name depends on the detrend type
     75my $FILERULES = { 'FLATMASK'         => undef,
     76                  'DARKMASK'         => undef,
     77                  'MASK'             => undef,
     78                  'BIAS'             => undef,
     79                  'DARK'             => undef,
     80                  'DARK_PREMASK'     => undef,
     81                  'SHUTTER'          => 'PPIMAGE.OUTPUT.DETREND',
     82                  'FLAT_PREMASK'     => 'PPIMAGE.OUTPUT.DETREND',
     83                  'DOMEFLAT_PREMASK' => 'PPIMAGE.OUTPUT.DETREND',
     84                  'SKYFLAT_PREMASK'  => 'PPIMAGE.OUTPUT.DETREND',
     85                  'FLAT_RAW'         => 'PPIMAGE.OUTPUT.DETREND',
     86                  'DOMEFLAT_RAW'     => 'PPIMAGE.OUTPUT.DETREND',
     87                  'SKYFLAT_RAW'      => 'PPIMAGE.OUTPUT.DETREND',
     88                  'FLAT'             => 'PPIMAGE.OUTPUT.DETREND',
     89                  'DOMEFLAT'         => 'PPIMAGE.OUTPUT.DETREND',
     90                  'SKYFLAT'          => 'PPIMAGE.OUTPUT.DETREND',
     91                  'FRINGE'           => undef,
     92              };
     93
    8394&my_die("Couldn't find input file: $input_uri\n", $det_id, $exp_id, $class_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($input_uri);
    8495
     
    93104my $cmdflags;
    94105
    95 my $outputImage = $ipprc->filename("PPIMAGE.OUTPUT", $outroot, $class_id) or &my_die("Missing entry from camera config", $det_id, $exp_id, $class_id, $PS_EXIT_PROG_ERROR);
     106my $filerule = $FILERULES->{$det_type}; # File rule to use for output
     107$filerule =  "PPIMAGE.OUTPUT" unless defined $filerule;
     108
     109my $outputImage = $ipprc->filename($filerule,        $outroot, $class_id) or &my_die("Missing entry from camera config", $det_id, $exp_id, $class_id, $PS_EXIT_PROG_ERROR);
    96110my $outputBin1  = $ipprc->filename("PPIMAGE.BIN1",   $outroot, $class_id) or &my_die("Missing entry from camera config", $det_id, $exp_id, $class_id, $PS_EXIT_PROG_ERROR);
    97111my $outputBin2  = $ipprc->filename("PPIMAGE.BIN2",   $outroot, $class_id) or &my_die("Missing entry from camera config", $det_id, $exp_id, $class_id, $PS_EXIT_PROG_ERROR);
    98112my $outputStats = $ipprc->filename("PPIMAGE.STATS",  $outroot, $class_id) or &my_die("Missing entry from camera config", $det_id, $exp_id, $class_id, $PS_EXIT_PROG_ERROR);
    99113my $traceDest   = $ipprc->filename("TRACE.IMFILE",   $outroot, $class_id) or &my_die("Missing entry from camera config", $exp_id, $exp_id, $class_id, $PS_EXIT_CONFIG_ERROR);
     114
     115
    100116# Run ppImage
    101117unless ($no_op) {
     
    105121    $command .= " -recipe PPSTATS DETSTATS";
    106122    $command .= " -stats $outputStats";
     123    $command .= " -F PPIMAGE.OUTPUT $filerule" if $filerule ne "PPIMAGE.OUTPUT";
    107124    $command .= " -tracedest $traceDest -log $logDest";
    108125    $command .= " -threads $threads" if defined $threads;
     
    167184    my $class_id = shift; # Class identifier
    168185    my $exit_code = shift; # Exit code to add
     186
     187    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
    169188
    170189    carp($msg);
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/detrend_reject_exp.pl

    r22430 r23352  
    2020use PS::IPP::Metadata::List qw( parse_md_list );
    2121use Statistics::Descriptive;
    22 
    23 my $ipprc = PS::IPP::Config->new(); # IPP configuration
    2422
    2523my $ITER_LIMIT = 20;
     
    6058    defined $outroot;
    6159
    62 # Unhandled exceptions should be passed on to my_die so they get pushed into the database
    63 $SIG{__DIE__} = sub { die @_ if $^S;
    64                       my_die( $_[0], $det_id, $iter, $PS_EXIT_UNKNOWN_ERROR ); };
    65 
    66 # check for existing directory, generate if needed
    67 $ipprc->outroot_prepare($outroot);
    68 
     60my $ipprc = PS::IPP::Config->new() or my_die( "Unable to set up", $det_id, $iter, $PS_EXIT_CONFIG_ERROR ); # IPP configuration
     61$ipprc->outroot_prepare($outroot) or my_die( "Unable to prepare output root", $det_id, $iter, $PS_EXIT_SYS_ERROR );
    6962my $logName = "$outroot.log"; # Name for log
    70 
    71 $ipprc->redirect_output($logName) if $redirect;
     63$ipprc->redirect_output($logName) or my_die( "Unable to redirect", $det_id, $iter, $PS_EXIT_SYS_ERROR ) if $redirect;
    7264
    7365# values to extract from output metadata and the stats to calculate
     
    344336    my $exit_code = shift; # Exit code to add
    345337
     338    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
     339
    346340    carp($msg);
    347341    if (defined $det_id and defined $iter and not $no_update) {
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/detrend_resid_exp.pl

    r22430 r23352  
    3030use File::Temp qw( tempfile );                   # tools to construct temp files
    3131use PS::IPP::Config 1.01 qw( :standard );
    32 
    33 my $ipprc = PS::IPP::Config->new(); # IPP configuration
    3432
    3533use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt ); # option parsing
     
    4745
    4846# parse the command-line options
    49 my ( $det_id, $iter, $exp_id, $exp_tag, $det_type, $camera, $filter, $reject, $outroot, $dbname, $reduction,
     47my ( $det_id, $iter, $exp_id, $exp_tag, $det_mode, $det_type, $camera, $filter, $reject, $outroot, $dbname, $reduction,
    5048     $verbose, $no_update, $no_op, $save_temps, $redirect );
    5149GetOptions(
     
    5553           'exp_tag|=s'        => \$exp_tag,
    5654           'det_type|t=s'      => \$det_type,
     55           'det_mode=s'        => \$det_mode,
    5756           'camera=s'          => \$camera,
    5857           'outroot|w=s'       => \$outroot,   # output file base name
     
    7675    defined $exp_tag  and
    7776    defined $det_type and
     77    defined $det_mode and
    7878    defined $camera   and
    7979    defined $outroot;
    8080
    81 # Unhandled exceptions should be passed on to my_die so they get pushed into the database
    82 $SIG{__DIE__} = sub { die @_ if $^S;
    83                       my_die( $_[0], $det_id, $iter, $exp_id, $PS_EXIT_UNKNOWN_ERROR ); };
    84 
    8581# load IPP config information for the specified camera
    86 $ipprc->define_camera($camera);
    87 
     82my $ipprc = PS::IPP::Config->new( $camera ) or my_die( "Unable to set up", $det_id, $iter, $exp_id, $PS_EXIT_CONFIG_ERROR ); # IPP configuration
    8883my $logDest = $ipprc->filename("LOG.EXP", $outroot) or &my_die("Missing entry from camera config", $det_id, $iter, $exp_id, $PS_EXIT_CONFIG_ERROR);
    89 
    90 $ipprc->redirect_output($logDest) if $redirect;
     84$ipprc->redirect_output($logDest) or my_die( "Unable to redirect output", $det_id, $iter, $exp_id, $PS_EXIT_SYS_ERROR ) if $redirect;
    9185
    9286# Recipes to use based on reduction class
     
    9690&my_die("Unrecognised detrend type: $det_type", $det_id, $iter, $PS_EXIT_PROG_ERROR) unless defined $recipe;
    9791
     92# variables used for I/O
     93my ($command, $success, $error_code, $full_buf, $stdout_buf, $stderr_buf);
     94
     95# Get list of normalizations by class_id : stored as $norms; save to temp file for ppImage runs below
     96my (%norms, $normsName);
     97if ($det_mode eq 'master') {
     98    # dettool command to select imfile data for this exp_id
     99    $command  = "$dettool -normalizedstat";
     100    $command .= " -det_id $det_id";
     101    $command .= " -iteration $iter";
     102    $command .= " -dbname $dbname" if defined $dbname;
     103    ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     104        run(command => $command, verbose => $verbose);
     105    unless ($success) {
     106        $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     107        warn("Unable to perform dettool -residimfile: $error_code\n");
     108        exit($error_code);
     109    }
     110    if (@$stdout_buf == 0) {
     111        &my_die("No normalizations were found", $det_id, $iter, $PS_EXIT_PROG_ERROR);
     112    }
     113
     114    # Parse the stdout buffer into a metadata
     115    my $mdcParser = PS::IPP::Metadata::Config->new;
     116    my $metadata = $mdcParser->parse(join "", @$stdout_buf) or
     117        &my_die("Unable to parse metadata config doc", $det_id, $iter, $exp_id, $PS_EXIT_PROG_ERROR);
     118
     119    # parse the file info in the metadata
     120    my $normsMD = parse_md_list($metadata) or
     121        &my_die("Unable to parse metadata list", $det_id, $iter, $exp_id, $PS_EXIT_PROG_ERROR);
     122
     123
     124    # write the normalizations to a file as a metadata config file in the form: class_id F32 value
     125    # XXX a possible optimization: if there is only one imfile, skip normalization
     126    my $normsFile;
     127    ($normsFile, $normsName) = tempfile( "/tmp/$exp_tag.detresid.$det_id.$iter.norms.XXXX", UNLINK => !$save_temps );
     128    print "saving norms to $normsName\n";
     129    foreach my $norm (@$normsMD) {
     130        my $class_id = $norm->{class_id};
     131        my $normalization = $norm->{norm};
     132
     133        $norms{$class_id} = $normalization;
     134        printf $normsFile "$class_id F32 $normalization\n",
     135    }
     136    close $normsFile;
     137}
     138
    98139# Get list of imfile files
    99140my $cmdflags;
    100 my ($files, $command, $success, $error_code, $full_buf, $stdout_buf, $stderr_buf);
     141my (@files);
    101142{
    102143    # dettool command to select imfile data for this exp_id
     
    113154        exit($error_code);
    114155    }
    115     # XXX report an error message if stdout_buf is empty
     156    if (@$stdout_buf == 0) {
     157        &my_die("No imfiles were found", $det_id, $iter, $PS_EXIT_PROG_ERROR);
     158    }
    116159
    117160    # Parse the stdout buffer into a metadata
     
    120163        &my_die("Unable to parse metadata config doc", $det_id, $iter, $exp_id, $PS_EXIT_PROG_ERROR);
    121164
     165    # since I can't figure out how to do input and output within PERL, I'm writing the (modified) metadata to a temp file
     166    my ($statFile, $statName) = tempfile( "/tmp/$exp_tag.detresid.$det_id.$iter.stats.XXXX", UNLINK => !$save_temps );
     167
     168    print $statFile "rawResidImfile MULTI\n";
     169
    122170    # parse the file info in the metadata
    123     $files = parse_md_list($metadata) or
    124         &my_die("Unable to parse metadata list", $det_id, $iter, $exp_id, $PS_EXIT_PROG_ERROR);
    125 
    126     # since I can't figure out how to do input and output within PERL, I'm writing to a temp file
    127     my ($statFile, $statName) = tempfile( "/tmp/$exp_tag.detresid.$det_id.$iter.stats.XXXX", UNLINK => !$save_temps );
    128     print "saving stats to $statName\n";
    129     foreach my $line (@$stdout_buf) {
    130         print $statFile $line;
     171    # as we parse the list of files and their stats, apply the normalization to the relevant fields
     172    # also, write out the modified metadata set
     173    foreach my $mdItem (@$metadata) {
     174        if ($mdItem->{class} ne "metadata") {
     175            carp "MD element ", $mdItem->{name}, " isn't of type METADATA --- ignored.\n";
     176            next;
     177        }
     178        my %hash;               # Hash element
     179        my $mdComponents = $mdItem->{value}; # Components of the metadata
     180
     181        # determine the class_id for this block:
     182        my $class_id;
     183        foreach my $data (@$mdComponents) {
     184            unless ($data->{name} eq "class_id") { next; }
     185            $class_id = $data->{value};
     186            last;
     187        }
     188
     189        # a new metadata block
     190        print $statFile "rawResidImfile  METADATA\n";
     191
     192        # modify and save the data in this block:
     193        foreach my $data (@$mdComponents) {
     194            my $norm = 1.0;
     195            if ($det_mode eq "master") {
     196                $norm = $norms{$class_id};
     197            }
     198
     199            # fields to modify by the normalization:
     200            if ($data->{name} eq "bg")            { $data->{value} *= $norm; }
     201            if ($data->{name} eq "bg_stdev")      { $data->{value} *= $norm; }
     202            if ($data->{name} eq "bg_mean_stdev") { $data->{value} *= $norm; }
     203            if ($data->{name} eq "bg_skewness")   { $data->{value} *= $norm; }
     204            if ($data->{name} eq "bg_kurtosis")   { $data->{value} *= $norm; }
     205            if ($data->{name} eq "bin_stdev")     { $data->{value} *= $norm; }
     206
     207            # write out the metadata, save on the array of hashes
     208            print $statFile "  $data->{name}  $data->{type}  $data->{value}\n";
     209            $hash{$data->{name}} = $data->{value};
     210        }
     211        print $statFile "END\n";
     212        push @files, \%hash;
    131213    }
    132214    close $statFile;
     
    162244my ($list1File, $list1Name) = tempfile( "/tmp/$exp_tag.detresid.$det_id.$iter.b1.list.XXXX", UNLINK => !$save_temps );
    163245my ($list2File, $list2Name) = tempfile( "/tmp/$exp_tag.detresid.$det_id.$iter.b2.list.XXXX", UNLINK => !$save_temps );
    164 foreach my $file (@$files) {
     246foreach my $file (@files) {
    165247    print $list1File ($ipprc->filename( "PPIMAGE.BIN1", $file->{path_base}, $file->{class_id} ) . "\n");
    166248    print $list2File ($ipprc->filename( "PPIMAGE.BIN2", $file->{path_base}, $file->{class_id} ) . "\n");
     
    173255unless ($no_op) {
    174256    # Make the jpeg for binning 1
     257    # XXX EAM : supply the collection of normalizations as a metadata
    175258    $command = "$ppImage -list $list1Name $outroot"; # Command to run
    176259    $command .= " -recipe PPIMAGE PPIMAGE_J1";
    177260    $command .= " -recipe JPEG $recipe";
     261    $command .= " -normlist $normsName" if defined $normsName;
    178262    $command .= " -dbname $dbname" if defined $dbname;
    179263    ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     
    186270
    187271    # Make the jpeg for binning 2
     272    # XXX EAM : supply the collection of normalizations as a metadata
    188273    $command = "$ppImage -list $list2Name $outroot"; # Command to run
    189274    $command .= " -recipe PPIMAGE PPIMAGE_J2";
    190275    $command .= " -recipe JPEG $recipe";
     276    $command .= " -normlist $normsName" if defined $normsName;
    191277    $command .= " -dbname $dbname" if defined $dbname;
    192278    ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     
    223309my @fluxes;
    224310
    225 foreach my $file (@$files) {
     311foreach my $file (@files) {
    226312    my $name      = $file->{class_id};
    227313    my $mean      = $file->{bg};        # Mean for this imfile
     
    554640    my $exit_code = shift; # Exit code to add
    555641
     642    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
     643
    556644    carp($msg);
    557645    if (defined $det_id and defined $iter and defined $exp_id and not $no_update) {
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/detrend_resid_imfile.pl

    r22430 r23352  
    1717use PS::IPP::Metadata::Config;
    1818use PS::IPP::Config 1.01 qw( :standard );
    19 
    20 my $ipprc = PS::IPP::Config->new(); # IPP configuration
    2119
    2220use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
     
    7674    defined $detrend;
    7775
    78 # Unhandled exceptions should be passed on to my_die so they get pushed into the database
    79 $SIG{__DIE__} = sub { die @_ if $^S;
    80                       my_die( $_[0], $det_id, $iter, $exp_id, $class_id, $PS_EXIT_UNKNOWN_ERROR ); };
    81 
    82 $ipprc->define_camera($camera);
    83 my $logDest     = $ipprc->filename("LOG.IMFILE", $outroot, $class_id);
    84 if ($redirect) {
    85     $ipprc->redirect_output($logDest);
    86 }
     76my $ipprc = PS::IPP::Config->new( $camera ) or my_die( "Unable to set up", $det_id, $iter, $exp_id, $class_id, $PS_EXIT_CONFIG_ERROR ); # IPP configuration
     77my $logDest = $ipprc->filename("LOG.IMFILE", $outroot, $class_id) or my_die( "Unable to find LOG.IMFILE", $det_id, $iter, $exp_id, $class_id, $PS_EXIT_CONFIG_ERROR );
     78$ipprc->redirect_output($logDest) or my_die( "Unable to find LOG.IMFILE", $det_id, $iter, $exp_id, $class_id, $PS_EXIT_SYS_ERROR ) if $redirect;
    8779
    8880# Recipes to use as a function of detrend type and mode
     
    124116};
    125117
     118# The output file rule name depends on the detrend type
     119my $FILERULES = { 'FLATMASK'         => 'PPIMAGE.OUTPUT.RESID',
     120                  'DARKMASK'         => 'PPIMAGE.OUTPUT.RESID',
     121                  'MASK'             => 'PPIMAGE.OUTPUT.RESID',
     122                  'BIAS'             => 'PPIMAGE.OUTPUT.RESID',
     123                  'DARK'             => 'PPIMAGE.OUTPUT.RESID',
     124                  'DARK_PREMASK'     => 'PPIMAGE.OUTPUT.RESID',
     125                  'SHUTTER'          => 'PPIMAGE.OUTPUT.DETREND',
     126                  'FLAT_PREMASK'     => 'PPIMAGE.OUTPUT.DETREND',
     127                  'DOMEFLAT_PREMASK' => 'PPIMAGE.OUTPUT.DETREND',
     128                  'SKYFLAT_PREMASK'  => 'PPIMAGE.OUTPUT.DETREND',
     129                  'FLAT_RAW'         => 'PPIMAGE.OUTPUT.DETREND',
     130                  'DOMEFLAT_RAW'     => 'PPIMAGE.OUTPUT.DETREND',
     131                  'SKYFLAT_RAW'      => 'PPIMAGE.OUTPUT.DETREND',
     132                  'FLAT'             => 'PPIMAGE.OUTPUT.DETREND',
     133                  'DOMEFLAT'         => 'PPIMAGE.OUTPUT.DETREND',
     134                  'SKYFLAT'          => 'PPIMAGE.OUTPUT.DETREND',
     135                  'FRINGE'           => 'PPIMAGE.OUTPUT.RESID',
     136              };
     137
    126138# outroot examples (HOST components must be set)
    127139# file://data/ipp004.0/gpc1/20080130
     
    135147# my $outputName  = $ipprc->filename("PPIMAGE.OUTPUT", $outroot, $class_id);
    136148
    137 my $outputName  = $ipprc->filename("PPIMAGE.OUTPUT.RESID", $outroot, $class_id);
     149my $filerule = $FILERULES->{$det_type}; # File rule to use
     150
     151my $outputName  = $ipprc->filename($filerule,        $outroot, $class_id);
    138152my $bin1Name    = $ipprc->filename("PPIMAGE.BIN1",   $outroot, $class_id);
    139153my $bin2Name    = $ipprc->filename("PPIMAGE.BIN2",   $outroot, $class_id);
     
    149163    $command .= " -recipe JPEG $jpeg_recipe";
    150164    $command .= " -recipe PPSTATS RESIDUAL";
    151     $command .= " -F PPIMAGE.OUTPUT PPIMAGE.OUTPUT.RESID";
     165    $command .= " -F PPIMAGE.OUTPUT $filerule";
    152166    $command .= " -stats $outputStats";
    153167    $command .= " -tracedest $traceDest -log $logDest";
     
    237251    my $exit_code = shift; # Exit code to add
    238252
     253    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
     254
    239255    carp($msg);
    240256    if (defined $det_id and defined $iter and defined $exp_id and not $no_update) {
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/detrend_stack.pl

    r22430 r23352  
    1818use PS::IPP::Metadata::List qw( parse_md_list );
    1919use PS::IPP::Config 1.01 qw( :standard );
    20 
    21 my $ipprc = PS::IPP::Config->new(); # IPP configuration
    2220
    2321use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
     
    6361    defined $outroot;
    6462
    65 $ipprc->define_camera($camera);
    6663$det_type = uc($det_type);
    6764
     65my $ipprc = PS::IPP::Config->new( $camera ) or my_die( "Unable to set up", $det_id, $iter, $class_id, $PS_EXIT_CONFIG_ERROR ); # IPP configuration
    6866my $logDest = $ipprc->filename("LOG.IMFILE", $outroot, $class_id)
    6967    or &my_die("Missing entry in file rules", $det_id, $iter, $class_id, $PS_EXIT_CONFIG_ERROR);
    70 
    71 # Unhandled exceptions should be passed on to my_die so they get pushed into the database
    72 $SIG{__DIE__} = sub { die @_ if $^S;
    73                       my_die( $_[0], $det_id, $iter, $class_id, $PS_EXIT_UNKNOWN_ERROR ); };
    74 
    75 # optionally redirect the outputs from this script to LOG.IMFILE
    76 $ipprc->redirect_output($logDest) if $redirect;
     68$ipprc->redirect_output($logDest) or my_die( "Unable to redirect output", $det_id, $iter, $class_id, $PS_EXIT_SYS_ERROR ) if $redirect;
    7769
    7870# Recipes to use as a function of detrend type
     
    259251    my $exit_code = shift; # Exit code to add
    260252
     253    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
     254
    261255    carp($msg);
    262256    if (defined $det_id and defined $iter and defined $class_id and not $no_update) {
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/diff_skycell.pl

    r22433 r23352  
    2121use Data::Dumper;
    2222use PS::IPP::Config 1.01 qw( :standard );
    23 
    24 my $ipprc = PS::IPP::Config->new(); # IPP configuration
    2523
    2624use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
     
    6260    and defined $outroot;
    6361
    64 # Unhandled exceptions should be passed on to my_die so they get pushed into the database
    65 $SIG{__DIE__} = sub { die @_ if $^S;
    66                       my_die( $_[0], $diff_id, $skycell_id, $PS_EXIT_UNKNOWN_ERROR ); };
     62my $ipprc = PS::IPP::Config->new() or my_die( "Unable to set up", $diff_id, $skycell_id, $PS_EXIT_CONFIG_ERROR ); # IPP configuration
    6763
    6864# XXX camera is not known here; cannot use filerules...
    6965# my $logDest = $ipprc->filename("LOG.EXP", $outroot);
    7066my $logDest = "$outroot.log";
    71 $ipprc->redirect_output($logDest) if $redirect;
     67$ipprc->redirect_output($logDest) or my_die( "Unable to redirect output", $diff_id, $skycell_id, $PS_EXIT_SYS_ERROR ) if $redirect;
    7268
    7369my $source_id = $ipprc->source_id($dbname, $PS_TABLE_ID_DIFF);
     
    280276    my $exit_code = shift;      # Exit code to add
    281277
     278    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
     279
    282280    warn($msg);
    283281    if (defined $diff_id and defined $skycell_id and not $no_update) {
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/fake_imfile.pl

    r22430 r23352  
    3636use PS::IPP::Metadata::Config;
    3737use PS::IPP::Config 1.01 qw( :standard );
    38 
    39 my $ipprc = PS::IPP::Config->new(); # IPP configuration
    4038
    4139use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
     
    8280    defined $outroot;
    8381
    84 # Unhandled exceptions should be passed on to my_die so they get pushed into the database
    85 $SIG{__DIE__} = sub { die @_ if $^S;
    86                       my_die( $_[0], $exp_id, $fake_id, $class_id, $PS_EXIT_UNKNOWN_ERROR ); };
    87 
    88 $ipprc->define_camera($camera);
    89 
    90 my $logDest = $ipprc->filename("LOG.IMFILE", $outroot, $class_id)  or &my_die("Missing entry from camera config", $exp_id, $fake_id, $class_id, $PS_EXIT_CONFIG_ERROR);
    91 
    92 $ipprc->redirect_output($logDest) if $redirect;
     82my $ipprc = PS::IPP::Config->new( $camera ) or my_die( "Unable to set up", $exp_id, $fake_id, $class_id, $PS_EXIT_CONFIG_ERROR ); # IPP configuration
     83my $logDest = $ipprc->filename("LOG.IMFILE", $outroot, $class_id) or &my_die("Missing entry from camera config", $exp_id, $fake_id, $class_id, $PS_EXIT_CONFIG_ERROR);
     84$ipprc->redirect_output($logDest) or my_die( "Unable to redirect output", $exp_id, $fake_id, $class_id, $PS_EXIT_SYS_ERROR ) if $redirect;
    9385
    9486# Recipes to use based on reduction class
     
    214206    my $exit_code = shift; # Exit code to add
    215207
     208    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
     209
    216210    carp($msg);
    217211    if (defined $exp_id and defined $fake_id and defined $class_id and not $no_update) {
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/ipp_cleanup.pl

    r21371 r23352  
    1818use Pod::Usage qw( pod2usage );
    1919
    20 my $ipprc = PS::IPP::Config->new(); # this is used for PATH, NEB filename conversions
    21 
    2220# Parse the command-line arguments
    2321my ($stage, $camera, $stage_id, $mode, $path_base, $dbname, $verbose, $no_op, $helplist);
    2422GetOptions('stage=s'        => \$stage,     # which analysis stage to clean?
    25            'camera|i=s'     => \$camera,    # user-supplied camera name
    26            'stage_id=s'     => \$stage_id,  # id for this stage (only needed for certain stages)
    27            'mode|m=s'       => \$mode,      # cleanup mode (clean / purge)
    28            'path_base=s'    => \$path_base, # basename for files
    29            'dbname|d=s'     => \$dbname,    # Database name
     23           'camera|i=s'     => \$camera,    # user-supplied camera name
     24           'stage_id=s'     => \$stage_id,  # id for this stage (only needed for certain stages)
     25           'mode|m=s'       => \$mode,      # cleanup mode (clean / purge)
     26           'path_base=s'    => \$path_base, # basename for files
     27           'dbname|d=s'     => \$dbname,    # Database name
    3028           'verbose'        => \$verbose,   # Print to stdout
    31            'no-op'          => \$no_op,     # pretend but don't actually inject
    32            'helplist'       => \$helplist   # give help listing
    33            ) or pod2usage( 2 );
    34 
    35 pod2usage( -msg => "remove temporary / all data files for an IPP analysis stage", 
    36            -exitval => 2) if defined $helplist;
    37 
    38 pod2usage( -msg => "Usage: $0 --camera (name) --stage (stage) --stage_id (stage_id) --mode (mode) [--path_base (path)] [--dbname dbname] [--no-op] [--help]", 
    39            -exitval => 2 ) if scalar @ARGV;
     29           'no-op'          => \$no_op,     # pretend but don't actually inject
     30           'helplist'       => \$helplist   # give help listing
     31           ) or pod2usage( 2 );
     32
     33pod2usage( -msg => "remove temporary / all data files for an IPP analysis stage",
     34           -exitval => 2) if defined $helplist;
     35
     36pod2usage( -msg => "Usage: $0 --camera (name) --stage (stage) --stage_id (stage_id) --mode (mode) [--path_base (path)] [--dbname dbname] [--no-op] [--help]",
     37           -exitval => 2 ) if scalar @ARGV;
    4038
    4139pod2usage( -msg => "Required options:--camera (name) --stage (stage) --mode (mode)",
    42            -exitval => 3) unless
     40           -exitval => 3) unless
    4341    defined $camera and
    4442    defined $stage and
    4543    defined $mode;
    4644
    47 # $mode must be one of "goto_cleaned" or "goto_purged"
    48 unless (($mode eq "goto_cleaned") || ($mode eq "goto_purged")) {
    49     die "invalid cleanup mode $mode\n";   
    50 }
     45my $ipprc = PS::IPP::Config->new( $camera ) or my_die("Unable to set up", $stage_id, $PS_EXIT_CONFIG_ERROR); # this is used for PATH, NEB filename conversions
     46
     47# $mode must be one of "goto_cleaned", "goto_scrubbed", or
     48# "goto_purged" goto_cleaned and goto_scrubbed both result in
     49# 'cleaned' on success ('scrubbed' allows chips without config files
     50# to be cleaned; they cannot be recovered, but the small data is left
     51# behind). XXX make 'scrubbed' a data_state?
     52unless (($mode eq "goto_cleaned") || ($mode eq "goto_scrubbed") || ($mode eq "goto_purged")) {
     53    die "invalid cleanup mode $mode\n";
     54}
     55
     56my $error_state;
     57if ($mode eq "goto_cleaned")  { $error_state = "error_cleaned";  }
     58if ($mode eq "goto_scrubbed") { $error_state = "error_scrubbed"; }
     59if ($mode eq "goto_purged")   { $error_state = "error_purged";   }
     60
    5161
    5262my %stages = ( chip => 1, camera => 1, fake => 1, warp => 1, stack => 1, diff  => 1);
     
    5565}
    5666
    57 $ipprc->define_camera($camera);
    58 
    5967my $mdcParser = PS::IPP::Metadata::Config->new; # Parser for metadata config files
    6068
    6169# choice of files to delete depends on the stage
    6270if ($stage eq "chip") {
    63    
     71
    6472    die "--stage_id required for stage chip\n" if !$stage_id;
    6573    ### select the imfiles for this entry
     
    7886        &my_die("Unable to perform chiptool: $error_code", "chip", $stage_id, $error_code);
    7987    }
     88
     89    # if there are no chipProcessedImfiles (@$stdout_buf == 0), the reset the state to 'new'
     90    if (@$stdout_buf == 0)  {
     91        my $command = "$chiptool -chip_id $stage_id -updaterun -set_state new";
     92        $command .= " -dbname $dbname" if defined $dbname;
     93
     94        my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     95            run(command => $command, verbose => $verbose);
     96        unless ($success) {
     97            $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     98            &my_die("Unable to perform chiptool: $error_code", "chip", $stage_id, $error_code);
     99        }
     100        exit 0;
     101    }
     102
    80103    my $metadata = $mdcParser->parse(join "", @$stdout_buf) or
    81104        &my_die("Unable to parse metadata config doc", "chip", $stage_id, $PS_EXIT_PROG_ERROR);
     
    87110    # loop over all of the imfiles, determine the path_base and class_id for each
    88111    foreach my $imfile (@$imfiles) {
    89         my $class_id = $imfile->{class_id};
    90         my $path_base = $imfile->{path_base};
     112        my $class_id = $imfile->{class_id};
     113        my $path_base = $imfile->{path_base};
    91114        my $status = 1;
    92115
    93116        # don't clean up unless the data needed to update is available
     117        # modes goto_purged and goto_scrubbed will remove files even if the config is non-existent
    94118        if ($mode eq "goto_cleaned") {
    95119            my $config_file = $ipprc->filename("PPIMAGE.CONFIG", $path_base, $class_id);
     
    124148                addFilename (\@files, "PPIMAGE.CONFIG", $path_base, $class_id);
    125149            }
    126        
     150
    127151            # actual command to delete the files
    128152            $status = &delete_files (\@files);
    129153        }
    130154
    131         if ($status)  {
    132             my $command = "$chiptool -chip_id $stage_id -class_id $class_id";
     155        if ($status)  {
     156            my $command = "$chiptool -chip_id $stage_id -class_id $class_id";
    133157            if ($mode eq "goto_purged") {
    134158                $command .= " -topurgedimfile";
     
    136160                $command .= " -tocleanedimfile";
    137161            }
     162            $command .= " -dbname $dbname" if defined $dbname;
     163
     164            my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     165                    run(command => $command, verbose => $verbose);
     166            unless ($success) {
     167                $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     168                &my_die("Unable to perform chiptool: $error_code", "chip", $stage_id, $error_code);
     169            }
     170        } else {
     171
     172            # if an error happens for one chip, the chipRun will stay in goto_*, but the chips will go to error_* (matching the goto_*)
     173            my $command = "$chiptool -updateprocessedimfile -chip_id $stage_id -class_id $class_id -set_state $error_state";
    138174            $command .= " -dbname $dbname" if defined $dbname;
    139175
    140             my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     176            my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    141177                    run(command => $command, verbose => $verbose);
    142             unless ($success) {
    143                 $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    144                 &my_die("Unable to perform chiptool: $error_code", "chip", $stage_id, $error_code);
    145             }
    146         } else {
    147             my $command = "$chiptool -updateprocessedimfile -chip_id $stage_id -class_id $class_id -code 1";
    148             $command .= " -dbname $dbname" if defined $dbname;
    149 
    150             my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    151                     run(command => $command, verbose => $verbose);
    152             unless ($success) {
    153                 $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    154                 &my_die("Unable to perform chiptool: $error_code", "chip", $stage_id, $error_code);
    155             }
    156         }
    157     }
    158 
    159 } elsif ($stage eq "camera") {
     178            unless ($success) {
     179                $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     180                &my_die("Unable to perform chiptool: $error_code", "chip", $stage_id, $error_code);
     181            }
     182        }
     183    }
     184    exit 0;
     185}
     186
     187if ($stage eq "camera") {
    160188    die "--stage_id required for stage camera\n" if !$stage_id;
    161189    # this stage uses 'camtool'
     
    210238
    211239    if ($status)  {
    212         my $command = "$camtool -cam_id $stage_id -updaterun";
     240        my $command;
    213241        if ($mode eq "goto_cleaned") {
    214             $command .= " -state cleaned";
    215         } else {
    216             $command .= " -state purged";
     242            $command = "$camtool -updaterun -cam_id $stage_id -set_state cleaned";
     243        }
     244        if ($mode eq "goto_scrubbed") {
     245            $command = "$camtool -updaterun -cam_id $stage_id -set_state cleaned";
     246        }
     247        if ($mode eq "goto_purged") {
     248            $command = "$camtool -updaterun -cam_id $stage_id -set_state purged";
    217249        }
    218250        $command .= " -dbname $dbname" if defined $dbname;
     
    224256        }
    225257    } else {
    226         my $command = "$camtool -updateprocessedexp -cam_id $stage_id -code 1";
     258        # since 'camera' has only a single imfile, we can just update the run
     259        my $command = "$camtool -updaterun -cam_id $stage_id -set_state $error_state";
    227260        $command .= " -dbname $dbname" if defined $dbname;
    228261
     
    236269    }
    237270    exit 0;
    238 } elsif ($stage eq "warp") {
     271}
     272
     273if ($stage eq "warp") {
    239274    die "--stage_id required for stage warp\n" if !$stage_id;
    240275    # this stage uses 'warptool'
     
    295330        }
    296331
    297         if ($status)  {
    298             my $command = "$warptool -warp_id $stage_id -skycell_id $skycell_id";
     332        if ($status)  {
     333            my $command = "$warptool -warp_id $stage_id -skycell_id $skycell_id";
    299334            if ($mode eq "goto_purged") {
    300335                $command .= " -topurgedskyfile";
     
    302337                $command .= " -tocleanedskyfile";
    303338            }
    304             $command .= " -dbname $dbname" if defined $dbname;
    305 
    306             my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     339            $command .= " -dbname $dbname" if defined $dbname;
     340
     341            my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    307342                    run(command => $command, verbose => $verbose);
    308             unless ($success) {
    309                 $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    310                 &my_die("Unable to perform warptool: $error_code", "warp", $stage_id, $error_code);
    311             }
     343            unless ($success) {
     344                $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     345                &my_die("Unable to perform warptool: $error_code", "warp", $stage_id, $error_code);
     346            }
    312347         } else {
    313             # XXX: -updateskyfile mode does not exist, need to add it
    314             my $command = "$warptool -updateskyfile -warp_id $stage_id -skycell_id $skycell_id -code 1";
     348            my $command = "$warptool -updateskyfile -warp_id $stage_id -skycell_id $skycell_id -set_state $error_state";
    315349            $command .= " -dbname $dbname" if defined $dbname;
    316350
    317351            my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    318352                run(command => $command, verbose => $verbose);
    319             unless ($success) {
    320                 $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    321                 &my_die("Unable to perform warptool: $error_code", "warp", $stage_id, $error_code);
    322             }
     353            unless ($success) {
     354                $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     355                &my_die("Unable to perform warptool: $error_code", "warp", $stage_id, $error_code);
     356            }
    323357            exit $PS_EXIT_UNKNOWN_ERROR;
    324         }
     358        }
    325359    }
    326360    exit 0;
     
    329363# left TODO
    330364# fake : faketool : -pendingcleanupimfile (loop over imfiles)
    331 # stack: stacktool : -pendingcleanupskyfile (loop over skyfiles)
    332 # diff:  difftool : -pendingcleanupskyfile
     365# stack: stacktool : -pendingcleanupskyfile
     366# diff:  difftool : -pendingcleanupskyfile (loop over skyfiles)
    333367
    334368die "ipp_cleanup.pl -stage $stage not yet implemented\n";
    335369
    336 sub delete_files 
     370sub delete_files
    337371{
    338372    my $files = shift; # reference to a list of files to unlink
    339    
    340     # this script is, of course, very dangerous. 
     373
     374    # this script is, of course, very dangerous.
    341375    foreach my $file (@$files) {
    342         print STDERR "unlinking $file\n";
     376        print STDERR "unlinking $file\n";
    343377        $ipprc->file_delete($file);
    344378    }
     
    346380}
    347381
    348 sub addFilename 
     382sub addFilename
    349383{
    350384    my $files      = shift; # reference to a list of files to unlink
     
    359393}
    360394
     395# XXX we currently do not set the error state in the db on my_die
    361396sub my_die
    362397{
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/ipp_maskscript.pl

    r17671 r23352  
    1212use PS::IPP::Config 1.01 qw( :standard );
    1313
    14 my $ipprc = PS::IPP::Config->new(); # IPP configuration
    15 
    1614my ($dbname, $det_id, $camera);
    17 
    1815GetOptions('dbname=s'    => \$dbname,
    19            'det_id=s'    => \$det_id,
    20            'camera|c=s'  => \$camera,
    21            ) or pod2usage( 2 );
     16           'det_id=s'    => \$det_id,
     17           'camera|c=s'  => \$camera,
     18           ) or pod2usage( 2 );
    2219
    2320pod2usage( -msg => "Unknown option: @ARGV", -exitval => 2 ) if @ARGV;
    2421
    2522pod2usage(
    26           -msg => "USAGE: ipp_maskscript.pl --dbname (name) --det_id (id) --iter (iteration) --camera (name)",
    27           -exitval => 3,
    28           ) unless defined $dbname and defined $det_id and defined $camera;
     23          -msg => "USAGE: ipp_maskscript.pl --dbname (name) --det_id (id) --iter (iteration) --camera (name)",
     24          -exitval => 3,
     25          ) unless defined $dbname and defined $det_id and defined $camera;
    2926
    3027# I could determine the camera from a query for the detrun
    31 $ipprc->define_camera($camera);
     28my $ipprc = PS::IPP::Config->new( $camera ) or my_die("Unable to setup", $PS_EXIT_CONFIG_ERROR); # IPP configuration
    3229
    3330###  Get list of dark imfile results
     
    4744
    4845# parse the output into a list
    49 my $mdcParser = PS::IPP::Metadata::Config->new; # Parser for metadata config files
     46my $mdcParser = PS::IPP::Metadata::Config->new; # Parser for metadata config files
    5047my $metadata = $mdcParser->parse(join "", @$stdout_buf) or
    5148    &my_die("Unable to parse metadata config doc", $PS_EXIT_PROG_ERROR);
     
    8178    # print STDERR "contents: @contents\n";
    8279
    83     my $parser = PS::IPP::Metadata::Config->new;        # Parser for metadata config files
     80    my $parser = PS::IPP::Metadata::Config->new;        # Parser for metadata config files
    8481    my $statsList = $parser->parse(join "", @contents) or &my_die("Unable to parse metadata for imfile stats", $PS_EXIT_SYS_ERROR);
    8582
     
    110107    open (DATA, ">$component.dat");
    111108    for (my $i = 0; $i < @{$nameX}; $i++) {
    112         print DATA "${$nameX}[$i] ${$nameY}[$i]\n";
     109        print DATA "${$nameX}[$i] ${$nameY}[$i]\n";
    113110    }
    114111    close (DATA);
     
    147144    my ($exp_time, $tag, $md) = @_;
    148145
    149     # descend through the fpa       
     146    # descend through the fpa
    150147    foreach my $entry (@$md) {
    151         # print STDERR "name: $entry->{name}, class: $entry->{class}\n";
     148        # print STDERR "name: $entry->{name}, class: $entry->{class}\n";
    152149        # recurse on nested metadata
    153150        if ($entry->{class} eq 'metadata') {
    154             my $newtag = $tag . "_" . $entry->{name};
     151            my $newtag = $tag . "_" . $entry->{name};
    155152            &parse_stats_table ($exp_time, $newtag, $entry->{value});
    156153        }
     
    161158                push @bg_stdev_data, $entry->{value};
    162159            } else {
    163                 push @bg_name,    $tag;
     160                push @bg_name,    $tag;
    164161                push @bg_data,    $entry->{value};
    165                 push @bg_exptime, $exp_time;
    166                 # print STDERR "$tag $exp_time $entry->{value}\n";
     162                push @bg_exptime, $exp_time;
     163                # print STDERR "$tag $exp_time $entry->{value}\n";
    167164            }
    168             if (!$componentsHash{$tag}) {
    169                 push @components, $tag;
    170                 $componentsHash{$tag} = 1;
    171             }
    172             next;
    173         }
     165            if (!$componentsHash{$tag}) {
     166                push @components, $tag;
     167                $componentsHash{$tag} = 1;
     168            }
     169            next;
     170        }
    174171    }
    175172    return 1;
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/magic_definerun.pl

    r21006 r23352  
    2525use PS::IPP::Config 1.01 qw( :standard );
    2626
    27 my $ipprc = PS::IPP::Config->new(); # IPP configuration
    28 
    2927use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
    3028use Pod::Usage qw( pod2usage );
    3129
     30# Look for programs we need
     31my $missing_tools;
     32my $magictool = can_run('magictool') or (warn "Can't find magictool" and $missing_tools = 1);
     33my $difftool  = can_run('difftool') or (warn "Can't find difftool" and $missing_tools = 1);
     34my $warptool  = can_run('warptool') or (warn "Can't find warptool" and $missing_tools = 1);
     35if ($missing_tools) {
     36    warn("Can't find required tools.");
     37    exit($PS_EXIT_CONFIG_ERROR);
     38}
     39
    3240# Parse the command-line arguments
    3341my ($exp_id, $warp_id, $min_diff_id, $label, $workdir, $dbname, $save_temps, $verbose);
    34 
    3542GetOptions(
    3643           'exp_id=s'        => \$exp_id,     # exposure identifier
     
    5057    defined $warp_id;
    5158
    52 # $ipprc->define_camera($camera);
    53 
    54 # Look for programs we need
    55 my $missing_tools;
    56 my $magictool = can_run('magictool') or (warn "Can't find magictool" and $missing_tools = 1);
    57 my $difftool  = can_run('difftool') or (warn "Can't find difftool" and $missing_tools = 1);
    58 my $warptool  = can_run('warptool') or (warn "Can't find warptool" and $missing_tools = 1);
    59 if ($missing_tools) {
    60     warn("Can't find required tools.");
    61     exit($PS_EXIT_CONFIG_ERROR);
    62 }
     59my $ipprc = PS::IPP::Config->new() or my_die("Unable to set up", $PS_EXIT_CONFIG_ERROR); # IPP configuration
    6360
    6461my $mdcParser = PS::IPP::Metadata::Config->new; # Parser for metadata config files
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/magic_destreak.pl

    r22430 r23352  
    2121
    2222use PS::IPP::Config 1.01 qw( :standard );
    23 
    24 my $ipprc = PS::IPP::Config->new(); # IPP configuration
    2523
    2624use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
     
    7674    defined $outroot;
    7775
    78 # Unhandled exceptions should be passed on to my_die so they get pushed into the database
    79 $SIG{__DIE__} = sub { die @_ if $^S;
    80                       my_die( $_[0], $magic_ds_id, $component, $PS_EXIT_UNKNOWN_ERROR ); };
    81 
     76my $ipprc = PS::IPP::Config->new( $camera ) or my_die( "Unable to set up", $magic_ds_id, $component, $PS_EXIT_CONFIG_ERROR ); # IPP configuration
     77$ipprc->redirect_output($logfile) or my_die( "Unable to redirect output", $magic_ds_id, $component, $PS_EXIT_SYS_ERROR ) if $logfile;
    8278
    8379my ($skycell_args, $class_id, $skycell_id);
     
    9490    &my_die("Invalid value for stage: $stage", $magic_ds_id, $component, $PS_EXIT_CONFIG_ERROR);
    9591}
    96 
    97 $ipprc->redirect_output($logfile) if $logfile;
    98 
    99 $ipprc->define_camera($camera);
    100 
    10192
    10293my $mdcParser = PS::IPP::Metadata::Config->new; # Parser for metadata config files
     
    276267    my $exit_code = shift;      # Exit code to add
    277268
     269    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
     270
    278271    my $command = "$magicdstool -adddestreakedfile";
    279272    $command   .= " -magic_ds_id $magic_ds_id";
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/magic_mask.pl

    r22430 r23352  
    2222
    2323use PS::IPP::Config 1.01 qw( :standard );
    24 
    25 my $ipprc = PS::IPP::Config->new(); # IPP configuration
    2624
    2725use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
     
    5856    defined $outroot;
    5957
    60 # Unhandled exceptions should be passed on to my_die so they get pushed into the database
    61 $SIG{__DIE__} = sub { die @_ if $^S;
    62                       my_die( $_[0], $magic_id, $PS_EXIT_UNKNOWN_ERROR ); };
    63 
    64 $ipprc->define_camera($camera);
    65 
    66 $ipprc->redirect_output($logfile) if $logfile;
     58my $ipprc = PS::IPP::Config->new( $camera ) or my_die( "Unable to set up", $magic_id, $PS_EXIT_CONFIG_ERROR ); # IPP configuration
     59$ipprc->redirect_output($logfile) or my_die( "Unable to redirect output", $magic_id, $PS_EXIT_SYS_ERROR ) if $logfile;
    6760
    6861my $mdcParser = PS::IPP::Metadata::Config->new; # Parser for metadata config files
     
    153146    my $exit_code = shift;      # Exit code to add
    154147
     148    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
     149
    155150    carp($msg);
    156151    if (defined $magic_id and not $no_update) {
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/magic_process.pl

    r22430 r23352  
    2323
    2424use PS::IPP::Config 1.01 qw( :standard );
    25 
    26 my $ipprc = PS::IPP::Config->new(); # IPP configuration
    2725
    2826use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
     
    6260    defined $outroot;
    6361
    64 # Unhandled exceptions should be passed on to my_die so they get pushed into the database
    65 $SIG{__DIE__} = sub { die @_ if $^S;
    66                       my_die( $_[0], $magic_id, $node, $PS_EXIT_UNKNOWN_ERROR ); };
    67 
    68 $ipprc->define_camera($camera);
     62my $ipprc = PS::IPP::Config->new( $camera ) or my_die( "Unable to set up", $magic_id, $node, $PS_EXIT_CONFIG_ERROR ); # IPP configuration
     63$ipprc->redirect_output($logfile) or my_die( "Unable to redirect output", $magic_id, $node, $PS_EXIT_SYS_ERROR ) if $logfile;
    6964
    7065# RemoveStreaks doesn't know about nebulous. It expects to be able to append strings to outroot
     
    7368# of the file names as arguments
    7469if ($outroot =~ 'neb:/') {
    75     &my_die("RemoveStreaks does not support nebulous paths in outroot", $magic_id, $node,
    76         $PS_EXIT_CONFIG_ERROR);
     70    &my_die("RemoveStreaks does not support nebulous paths in outroot", $magic_id, $node, $PS_EXIT_CONFIG_ERROR);
    7771}
    7872
    7973# resolve any path:// or file:// in outroot
    8074$outroot = $ipprc->file_resolve($outroot);
    81 
    82 $ipprc->redirect_output($logfile) if $logfile;
    8375
    8476my $mdcParser = PS::IPP::Metadata::Config->new; # Parser for metadata config files
     
    340332    my $exit_code = shift;      # Exit code to add
    341333
     334    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
     335
    342336    carp($msg);
    343337    if (defined $magic_id and defined $node and not $no_update) {
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/magic_tree.pl

    r22430 r23352  
    2424use File::Temp qw( tempfile );
    2525use PS::IPP::Config 1.01 qw( :standard );
    26 
    27 my $ipprc = PS::IPP::Config->new(); # IPP configuration
    2826
    2927use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
     
    7068    defined $outroot;
    7169
    72 # Unhandled exceptions should be passed on to my_die so they get pushed into the database
    73 $SIG{__DIE__} = sub { die @_ if $^S;
    74                       my_die( $_[0], $magic_id, $PS_EXIT_UNKNOWN_ERROR ); };
    75 
    76 $ipprc->define_camera($camera);
    77 
    78 $ipprc->redirect_output($logfile) if $logfile;
     70my $ipprc = PS::IPP::Config->new( $camera ) or my_die( "Unable to set up", $magic_id, $PS_EXIT_CONFIG_ERROR ); # IPP configuration
     71$ipprc->redirect_output($logfile) or my_die( "Unable to redirect output", $magic_id, $PS_EXIT_SYS_ERROR ) if $logfile;
    7972
    8073my $mdcParser = PS::IPP::Metadata::Config->new; # Parser for metadata config files
     
    297290    my $exit_code = shift;      # Exit code to add
    298291
     292    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
     293
    299294    carp($msg);
    300295    if (defined $magic_id and not $no_update) {
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/register_exp.pl

    r22430 r23352  
    2424use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
    2525use Pod::Usage qw( pod2usage );
    26 
    27 my $ipprc = PS::IPP::Config->new();
    2826
    2927# Look for commands we need
     
    5351) or pod2usage( 2 );
    5452
    55 # Unhandled exceptions should be passed on to my_die so they get pushed into the database
    56 $SIG{__DIE__} = sub { die @_ if $^S;
    57                       my_die( $_[0], $exp_id, $PS_EXIT_UNKNOWN_ERROR ); };
    58 
    59 $ipprc->redirect_output($logfile) if $logfile;
     53my $ipprc = PS::IPP::Config->new() or my_die( "Unable to set up", $exp_id, $PS_EXIT_CONFIG_ERROR );
     54$ipprc->redirect_output($logfile) or my_die( "Unable to redirect output", $exp_id, $PS_EXIT_SYS_ERROR ) if $logfile;
    6055
    6156pod2usage( -msg => "Unknown option: @ARGV", -exitval => 2 ) if @ARGV;
     
    192187    my $exit_code = shift;
    193188
     189    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
     190
    194191    carp($msg);
    195192    if (defined $exp_id and not $no_update) {
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/register_imfile.pl

    r22428 r23352  
    2323use Math::Trig;
    2424
    25 my $ipprc = PS::IPP::Config->new(); # IPP configuration
    2625use File::Spec;
    2726
     
    4948) or pod2usage( 2 );
    5049
    51 # Unhandled exceptions should be passed on to my_die so they get pushed into the database
    52 $SIG{__DIE__} = sub { die @_ if $^S;
    53                       my_die( $_[0], $exp_id, $tmp_exp_name, $tmp_class_id, $uri, $PS_EXIT_UNKNOWN_ERROR ); };
    54 
    55 $ipprc->redirect_output($logfile) if $logfile;
     50my $ipprc = PS::IPP::Config->new() or my_die( "Unable to set up", $exp_id, $tmp_exp_name, $tmp_class_id, $uri, $PS_EXIT_CONFIG_ERROR ); # IPP configuration
     51$ipprc->redirect_output($logfile) or my_die( "Unable to redirect output", $exp_id, $tmp_exp_name, $tmp_class_id, $uri, $PS_EXIT_SYS_ERROR ) if $logfile;
    5652
    5753pod2usage( -msg => "Unknown option: @ARGV", -exitval => 2 ) if @ARGV;
     
    9894    print "STDOUT:\n$out1";
    9995    print "STDERR:\n$err1";
    100     &my_die("Unable to perform ppStats on exposure id $exp_id: " . $h1->result(), $exp_id, $tmp_exp_name, $tmp_class_id, $uri, $h1->result() ) unless $result1;
     96    &my_die("Unable to perform ppStats on exposure id $exp_id: " . $h1->result(), $exp_id, $tmp_exp_name, $tmp_class_id, $uri, ($h1->result() or $PS_EXIT_PROG_ERROR) ) unless $result1;
    10197
    10298    print "[Running " . join(' ', @command2) . "]\n";
     
    107103    print "STDOUT:\n$out2";
    108104    print "STDERR:\n$err2";
    109     &my_die("Unable to perform ppStatsFromMetadata on exposure id $exp_id: " . $h2->result(), $exp_id, $tmp_exp_name, $tmp_class_id, $uri, $h2->result() ) unless $result2;
     105    &my_die("Unable to perform ppStatsFromMetadata on exposure id $exp_id: " . $h2->result(), $exp_id, $tmp_exp_name, $tmp_class_id, $uri, ($h2->result() or $PS_EXIT_PROG_ERROR) ) unless $result2;
    110106    chomp $out2;
    111107    $cmdflags = $out2;
     
    132128
    133129# determine solar-system parameters
    134 my $longitude = &value_for_flag ($cmdflags, "-longitude");
    135 my $latitude  = &value_for_flag ($cmdflags, "-latitude");
    136 my $elevation = &value_for_flag ($cmdflags, "-elevation");
    137 my $ra        = &value_for_flag ($cmdflags, "-ra");
    138 my $dec       = &value_for_flag ($cmdflags, "-decl");
    139 my $dateobs   = &value_for_flag ($cmdflags, "-dateobs");
     130my $longitude = &value_for_flag($cmdflags, "-longitude");
     131my $latitude  = &value_for_flag($cmdflags, "-latitude");
     132my $elevation = &value_for_flag($cmdflags, "-elevation");
     133my $ra        = &value_for_flag($cmdflags, "-ra");
     134my $dec       = &value_for_flag($cmdflags, "-decl");
     135my $dateobs   = &value_for_flag($cmdflags, "-dateobs");
    140136
    141137# if the needed data is available, pass it to sunmoon:
     
    216212
    217213    # for failed imfiles, we insert UNKNOWN for inst, telescope, class_id
     214
     215    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
    218216
    219217    carp($msg);
     
    230228        $command .= " -hostname $host" if defined $host;
    231229        $command .= " -dbname $dbname" if defined $dbname;
    232         system ($command);
     230        print "Running: $command\n";
     231        system($command);
    233232    }
    234233    exit $exit_code;
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/stack_skycell.pl

    r22430 r23352  
    2424use File::Basename;
    2525use PS::IPP::Config 1.01 qw( :standard );
    26 
    27 my $ipprc = PS::IPP::Config->new(); # IPP configuration
    2826
    2927use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
     
    6664    and defined $run_state;
    6765
    68 # Unhandled exceptions should be passed on to my_die so they get pushed into the database
    69 $SIG{__DIE__} = sub { die @_ if $^S;
    70                       my_die( $_[0], $stack_id, $PS_EXIT_UNKNOWN_ERROR ); };
     66my $ipprc = PS::IPP::Config->new() or my_die( "Unable to set up", $stack_id, $PS_EXIT_CONFIG_ERROR ); # IPP configuration
    7167
    7268# XXX camera is not known here; cannot use filerules...
     
    8177}
    8278
    83 $ipprc->redirect_output($logDest) if $redirect;
     79$ipprc->redirect_output($logDest) or my_die( "Unable to redirect output", $stack_id, $PS_EXIT_SYS_ERROR ) if $redirect;
    8480
    8581my $temp_images_exist = 0;
     
    300296    my $exit_code = shift;      # Exit code to add
    301297
     298    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
     299
    302300    carp($msg);
    303301
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/summit_copy.pl

    r20310 r23352  
    136136    my $exit_code = shift; # Exit code to add
    137137
     138    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
     139
    138140    warn $msg;
    139141    unless ($no_update) {
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/warp_overlap.pl

    r22430 r23352  
    2323use Getopt::Long qw( GetOptions :config auto_help auto_version gnu_getopt );
    2424use Pod::Usage qw( pod2usage );
    25 
    26 my $ipprc = PS::IPP::Config->new(); # IPP configuration
    2725
    2826# Look for programs we need
     
    4947) or pod2usage( 2 );
    5048
    51 $ipprc->redirect_output($logfile) if $logfile;
    52 
    5349pod2usage( -msg => "Unknown option: @ARGV", -exitval => 2 ) if @ARGV;
    5450pod2usage(
     
    5955    and defined $tess_dir;
    6056
    61 # Unhandled exceptions should be passed on to my_die so they get pushed into the database
    62 $SIG{__DIE__} = sub { die @_ if $^S;
    63                       my_die( $_[0], $warp_id, $PS_EXIT_UNKNOWN_ERROR ); };
    64 
    65 $ipprc->define_camera($camera);
     57my $ipprc = PS::IPP::Config->new( $camera ) or my_die( "Unable to set up", $warp_id, $PS_EXIT_CONFIG_ERROR ); # IPP configuration
     58$ipprc->redirect_output($logfile) or my_die( "Unable to redirect output", $warp_id, $PS_EXIT_SYS_ERROR ) if $logfile;
    6659
    6760&my_die("Tessellation identifier not provided: $tess_dir", $warp_id, $PS_EXIT_SYS_ERROR) unless $tess_dir ne "NULL";
     
    193186    my $warp_id = shift;        # Warp identifier
    194187    my $exit_code = shift;      # Exit code to add
     188
     189    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
    195190
    196191    carp($msg);
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/warp_skycell.pl

    r22430 r23352  
    2424use PS::IPP::Metadata::List qw( parse_md_list );
    2525use PS::IPP::Config 1.01 qw( :standard );
    26 
    27 my $ipprc = PS::IPP::Config->new(); # IPP configuration
    2826
    2927# Look for programs we need
     
    6866    and defined $run_state;
    6967
    70 # Unhandled exceptions should be passed on to my_die so they get pushed into the database
    71 $SIG{__DIE__} = sub { die @_ if $^S;
    72                       my_die( $_[0], $warp_id, $skycell_id, $tess_dir, $PS_EXIT_UNKNOWN_ERROR ); };
    73 
    74 $ipprc->define_camera($camera);
    75 
    76 my $logDest = $ipprc->filename("LOG.EXP", $outroot, $skycell_id);
     68my $ipprc = PS::IPP::Config->new( $camera ) or my_die( "Unable to set up", $warp_id, $skycell_id, $tess_dir, $PS_EXIT_CONFIG_ERROR ); # IPP configuration
     69
     70my $logDest = $ipprc->filename("LOG.EXP", $outroot, $skycell_id) or my_die( "Unable to get log filename", $warp_id, $skycell_id, $tess_dir, $PS_EXIT_SYS_ERROR );
    7771$logDest .= ".update" if ($run_state eq 'update');
    7872
    79 $ipprc->redirect_output($logDest) if $redirect;
     73$ipprc->redirect_output($logDest) or my_die( "Unable to redirect output", $warp_id, $skycell_id, $tess_dir, $PS_EXIT_SYS_ERROR ) if $redirect;
    8074
    8175my $source_id = $ipprc->source_id($dbname, $PS_TABLE_ID_WARP);
     
    294288    my $exit_code = shift;      # Exit code to add
    295289
     290    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
     291
    296292    warn($msg);
    297293    if (defined $warp_id and defined $skycell_id and defined $tess_dir and not $no_update) {
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/Makefile.am

    r20879 r23352  
    2020        summit.copy.pro \
    2121        replicate.pro \
     22        dist.pro \
    2223        pstamp.pro
    2324
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/automate.pro

    r19621 r23352  
    175175  end
    176176
     177  task.exit    crash
     178    showcommand crash
     179  end
     180
    177181  # operation times out?
    178182  task.exit    timeout
     
    283287  end
    284288
     289  task.exit    crash
     290    showcommand crash
     291  end
     292
    285293  # operation times out?
    286294  task.exit    timeout
     
    373381  end
    374382
     383  task.exit    crash
     384    showcommand crash
     385  end
     386
    375387  # operation times out?
    376388  task.exit    timeout
     
    448460  end
    449461
     462  task.exit    crash
     463    book setword automate $pageName pantaskState INIT.REGULAR
     464    showcommand crash
     465  end
     466
    450467  # operation times out?
    451468  task.exit    timeout
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/calibration.pro

    r19465 r23352  
    9090  end
    9191
     92  task.exit    crash
     93    showcommand crash
     94  end
     95
    9296  # operation times out?
    9397  task.exit    timeout
     
    166170  end
    167171
     172  task.exit    crash
     173    showcommand crash
     174    book setword calBook $options:0 pantaskState CRASH
     175  end
     176
    168177  # operation timed out?
    169178  task.exit    timeout
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/camera.pro

    r19559 r23352  
    104104  end
    105105
     106  task.exit    crash
     107    showcommand crash
     108  end
     109
    106110  # operation times out?
    107111  task.exit    timeout
     
    177181  task.exit default
    178182    process_exit camPendingExp $options:0 $JOB_STATUS
     183  end
     184
     185  # locked list
     186  task.exit    crash
     187    showcommand crash
     188    echo "hostname: $JOB_HOSTNAME"
     189    book setword camPendingExp $options:0 pantaskState CRASH
    179190  end
    180191
     
    236247  end
    237248
     249  task.exit    crash
     250    showcommand crash
     251  end
     252
    238253  # operation times out?
    239254  task.exit    timeout
     
    289304  end
    290305
     306  task.exit    crash
     307    showcommand crash
     308    book setword camPendingCleanup $options:0 pantaskState CRASH
     309  end
     310
    291311  # operation timed out?
    292312  task.exit    timeout
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/chip.pro

    r21464 r23352  
    2929    active true
    3030  end
    31   task chip.promoteexp
     31  task chip.advanceexp
    3232    active true
    3333  end
     
    4141    active false
    4242  end
    43   task chip.promoteexp
     43  task chip.advanceexp
    4444    active false
    4545  end
     
    111111  task.exit    default
    112112    showcommand failure
     113  end
     114
     115  task.exit    crash
     116    showcommand crash
    113117  end
    114118
     
    188192  end
    189193
     194  # locked list
     195  task.exit    crash
     196    showcommand crash
     197    echo "hostname: $JOB_HOSTNAME"
     198    book setword chipPendingImfile $options:0 pantaskState CRASH
     199  end
     200
    190201  # operation timed out?
    191202  task.exit    timeout
     
    196207
    197208# this variable will cycle through the known database names
    198 $chip_promote_DB = 0
    199 
    200 # promote exposures for which all imfiles have completed processing
     209$chip_advance_DB = 0
     210
     211# advance exposures for which all imfiles have completed processing
    201212# sets the exposure state to full and queues warp processing if requested
    202 task           chip.promoteexp
     213task           chip.advanceexp
    203214  host         local
    204215
     
    209220
    210221  stdout NULL
    211   stderr $LOGDIR/chip.promoteexp.log
    212 
    213   task.exec
    214     $run = chiptool -promoteexp -limit 10
     222  stderr $LOGDIR/chip.advanceexp.log
     223
     224  task.exec
     225    $run = chiptool -advanceexp -limit 10
    215226    if ($DB:n == 0)
    216227      option DEFAULT
    217228    else
    218229      # save the DB name for the exit tasks
    219       option $DB:$chip_promote_DB
    220       $run = $run -dbname $DB:$chip_promote_DB
    221       $chip_promote_DB ++
    222       if ($chip_promote_DB >= $DB:n) set chip_promote_DB = 0
     230      option $DB:$chip_advance_DB
     231      $run = $run -dbname $DB:$chip_advance_DB
     232      $chip_advance_DB ++
     233      if ($chip_advance_DB >= $DB:n) set chip_advance_DB = 0
    223234    end
    224235    add_poll_args run
     
    233244  task.exit    default
    234245    showcommand failure
     246  end
     247
     248  task.exit    crash
     249    showcommand crash
    235250  end
    236251
     
    291306  end
    292307
     308  task.exit    crash
     309    showcommand crash
     310  end
     311
    293312  # operation times out?
    294313  task.exit    timeout
     
    344363  end
    345364
     365  task.exit    crash
     366    showcommand crash
     367    book setword chipPendingCleanup $options:0 pantaskState CRASH
     368  end
     369
    346370  # operation timed out?
    347371  task.exit    timeout
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/detrend.correct.pro

    r20398 r23352  
    8585  end
    8686
     87  task.exit    crash
     88    showcommand crash
     89  end
     90
    8791  # operation times out?
    8892  task.exit    timeout
    89     showcommand
     93    showcommand timeout
    9094  end
    9195end
     
    145149  end
    146150
     151  # locked list
     152  task.exit    crash
     153    showcommand crash
     154    echo "hostname: $JOB_HOSTNAME"
     155    book setword detPendingCorrectImfile $options:0 pantaskState CRASH
     156  end
     157
    147158  # operation times out?
    148159  task.exit    timeout
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/detrend.mkruns.pro

    r16298 r23352  
    3434  end
    3535
     36  task.exit crash
     37    # send someone email?
     38    echo "unable to define a new detrend run"
     39  end
     40
    3641  # operation timed out?  is the database down?
    3742  task.exit timeout
     
    6065  # default exit status
    6166  task.exit default
     67    echo "unable to define a new detrend run"
     68  end
     69
     70  task.exit crash
     71    # send someone email?
    6272    echo "unable to define a new detrend run"
    6373  end
     
    92102  end
    93103
     104  task.exit crash
     105    # send someone email?
     106    echo "unable to define a new detrend run"
     107  end
     108
    94109  # operation timed out?  is the database down?
    95110  task.exit timeout
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/detrend.norm.pro

    r19465 r23352  
    168168  end
    169169
     170  task.exit    crash
     171    showcommand crash
     172  end
     173
    170174  # operation times out?
    171175  task.exit    timeout
     
    225229  task.exit    default
    226230    process_exit detPendingNormStatImfile $options:0 $JOB_STATUS
     231  end
     232
     233  # locked list
     234  task.exit    crash
     235    showcommand crash
     236    echo "hostname: $JOB_HOSTNAME"
     237    book setword detPendingNormStatImfile $options:0 pantaskState CRASH
    227238  end
    228239
     
    278289  task.exit    default
    279290    showcommand failure
     291  end
     292
     293  task.exit    crash
     294    showcommand crash
    280295  end
    281296
     
    342357  end
    343358
     359  # locked list
     360  task.exit    crash
     361    showcommand crash
     362    echo "hostname: $JOB_HOSTNAME"
     363    book setword detPendingNormImfile $options:0 pantaskState CRASH
     364  end
     365
    344366  # operation times out?
    345367  task.exit    timeout
     
    395417  end
    396418
     419  task.exit    crash
     420    showcommand crash
     421  end
     422
    397423  # operation times out?
    398424  task.exit    timeout
     
    452478  task.exit    default
    453479    process_exit detPendingNormExp $options:0 $JOB_STATUS
     480  end
     481
     482  # locked list
     483  task.exit    crash
     484    showcommand crash
     485    echo "hostname: $JOB_HOSTNAME"
     486    book setword detPendingNormExp $options:0 pantaskState CRASH
    454487  end
    455488
     
    506539  end
    507540
     541  task.exit    crash
     542    showcommand crash
     543  end
     544
    508545  # operation times out?
    509546  task.exit    timeout
     
    558595  task.exit    default
    559596    process_exit detCleanupNormStatImfile $options:0 $JOB_STATUS
     597  end
     598
     599  task.exit    crash
     600    showcommand crash
     601    book setword detCleanupNormStatImfile $options:0 pantaskState CRASH
    560602  end
    561603
     
    612654  end
    613655
     656  task.exit    crash
     657    showcommand crash
     658  end
     659
    614660  # operation times out?
    615661  task.exit    timeout
     
    665711  task.exit    default
    666712    process_exit detCleanupNormImfile $options:0 $JOB_STATUS
     713  end
     714
     715  task.exit    crash
     716    showcommand crash
     717    book setword detCleanupNormImfile $options:0 pantaskState CRASH
    667718  end
    668719
     
    719770  end
    720771
     772  task.exit    crash
     773    showcommand crash
     774  end
     775
    721776  # operation times out?
    722777  task.exit    timeout
     
    773828  end
    774829
     830  task.exit    crash
     831    showcommand crash
     832    book setword detCleanupNormExp $options:0 pantaskState CRASH
     833  end
     834
    775835  # operation timed out?
    776836  task.exit    timeout
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/detrend.process.pro

    r19465 r23352  
    136136  end
    137137
     138  task.exit    crash
     139    showcommand crash
     140  end
     141
    138142  # operation times out?
    139143  task.exit    timeout
    140     showcommand
     144    showcommand timeout
    141145  end
    142146end
     
    202206  end
    203207
     208  # locked list
     209  task.exit    crash
     210    showcommand crash
     211    echo "hostname: $JOB_HOSTNAME"
     212    book setword detPendingProcessedImfile $options:0 pantaskState CRASH
     213  end
     214
    204215  # operation times out?
    205216  task.exit    timeout
     
    255266  end
    256267
     268  task.exit    crash
     269    showcommand crash
     270  end
     271
    257272  # operation times out?
    258273  task.exit    timeout
     
    319334  end
    320335
     336  # locked list
     337  task.exit    crash
     338    showcommand crash
     339    echo "hostname: $JOB_HOSTNAME"
     340    book setword detPendingProcessedExp $options:0 pantaskState CRASH
     341  end
     342
    321343  # operation times out?
    322344  task.exit    timeout
     
    371393  end
    372394
     395  task.exit    crash
     396    showcommand crash
     397  end
     398
    373399  # operation times out?
    374400  task.exit    timeout
     
    424450  task.exit    default
    425451    process_exit detCleanupProcessedImfile $options:0 $JOB_STATUS
     452  end
     453
     454  # locked list
     455  task.exit    crash
     456    showcommand crash
     457    echo "hostname: $JOB_HOSTNAME"
     458    book setword detCleanupProcessedImfile $options:0 pantaskState CRASH
    426459  end
    427460
     
    479512  end
    480513
     514  task.exit    crash
     515    showcommand crash
     516  end
     517
    481518  # operation times out?
    482519  task.exit    timeout
     
    533570  end
    534571
     572  # locked list
     573  task.exit    crash
     574    showcommand crash
     575    echo "hostname: $JOB_HOSTNAME"
     576    book setword detCleanupProcessedExp $options:0 pantaskState CRASH
     577  end
     578
    535579  # operation timed out?
    536580  task.exit    timeout
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/detrend.reject.pro

    r19465 r23352  
    8383  end
    8484
     85  task.exit    crash
     86    showcommand crash
     87  end
     88
    8589  # operation times out?
    8690  task.exit    timeout
    87     showcommand failure
     91    showcommand timeout
    8892  end
    8993end
     
    143147  end
    144148
     149  # locked list
     150  task.exit    crash
     151    showcommand crash
     152    echo "hostname: $JOB_HOSTNAME"
     153    book setword detRejectExp $options:0 pantaskState CRASH
     154  end
     155
    145156  # operation times out?
    146157  task.exit    timeout
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/detrend.resid.pro

    r19621 r23352  
    129129  task.exit    default
    130130    showcommand failure
     131  end
     132
     133  task.exit    crash
     134    showcommand crash
    131135  end
    132136
     
    203207  end
    204208
     209  # locked list
     210  task.exit    crash
     211    showcommand crash
     212    echo "hostname: $JOB_HOSTNAME"
     213    book setword detPendingResidImfile $options:0 pantaskState CRASH
     214  end
     215
    205216  # operation times out?
    206217  task.exit    timeout
     
    254265  task.exit    default
    255266    showcommand failure
     267  end
     268
     269  task.exit    crash
     270    showcommand crash
    256271  end
    257272
     
    301316    stderr $LOGDIR/detrend.resid.exp.log
    302317
    303     $run = detrend_resid_exp.pl --det_id $DET_ID --iteration $ITERATION --exp_id $EXP_ID --exp_tag $EXP_TAG --det_type $DET_TYPE --camera $CAMERA --outroot $outroot --redirect-output --verbose
     318    $run = detrend_resid_exp.pl --det_id $DET_ID --iteration $ITERATION --exp_id $EXP_ID --exp_tag $EXP_TAG --det_mode $MODE --det_type $DET_TYPE --camera $CAMERA --outroot $outroot --redirect-output --verbose
    304319
    305320    add_standard_args run
     
    318333  task.exit    default
    319334    process_exit detPendingResidExp $options:0 $JOB_STATUS
     335  end
     336
     337  # locked list
     338  task.exit    crash
     339    showcommand crash
     340    echo "hostname: $JOB_HOSTNAME"
     341    book setword detPendingResidExp $options:0 pantaskState CRASH
    320342  end
    321343
     
    372394  end
    373395
     396  task.exit    crash
     397    showcommand crash
     398  end
     399
    374400  # operation times out?
    375401  task.exit    timeout
     
    426452  task.exit    default
    427453    process_exit detCleanupResidImfile $options:0 $JOB_STATUS
     454  end
     455
     456  # locked list
     457  task.exit    crash
     458    showcommand crash
     459    echo "hostname: $JOB_HOSTNAME"
     460    book setword detCleanupResidImfile $options:0 pantaskState CRASH
    428461  end
    429462
     
    481514  end
    482515
     516  task.exit    crash
     517    showcommand crash
     518  end
     519
    483520  # operation times out?
    484521  task.exit    timeout
     
    536573  end
    537574
     575  # locked list
     576  task.exit    crash
     577    showcommand crash
     578    echo "hostname: $JOB_HOSTNAME"
     579    book setword detCleanupResidExp $options:0 pantaskState CRASH
     580  end
     581
    538582  # operation timed out?
    539583  task.exit    timeout
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/detrend.stack.pro

    r19465 r23352  
    101101  end
    102102
     103  task.exit    crash
     104    showcommand crash
     105  end
     106
    103107  # operation times out?
    104108  task.exit    timeout
     
    163167  task.exit    default
    164168    process_exit detPendingStackedImfile $options:0 $JOB_STATUS
     169  end
     170
     171  # locked list
     172  task.exit    crash
     173    showcommand crash
     174    echo "hostname: $JOB_HOSTNAME"
     175    book setword detPendingStackedImfile $options:0 pantaskState CRASH
    165176  end
    166177
     
    217228  end
    218229
     230  task.exit    crash
     231    showcommand crash
     232  end
     233
    219234  # operation times out?
    220235  task.exit    timeout
     
    272287  end
    273288
     289  # locked list
     290  task.exit    crash
     291    showcommand crash
     292    echo "hostname: $JOB_HOSTNAME"
     293    book setword detCleanupStackedImfile $options:0 pantaskState CRASH
     294  end
     295
    274296  # operation timed out?
    275297  task.exit    timeout
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/diff.pro

    r21312 r23352  
    112112  end
    113113
     114  task.exit    crash
     115    showcommand crash
     116  end
     117
    114118  # operation times out?
    115119  task.exit    timeout
     
    173177  task.exit    default
    174178    process_exit diffSkyfile $options:0 $JOB_STATUS
     179  end
     180
     181  # locked list
     182  task.exit    crash
     183    showcommand crash
     184    echo "hostname: $JOB_HOSTNAME"
     185    book setword diffSkyfile $options:0 pantaskState CRASH
    175186  end
    176187
     
    229240  end
    230241
     242  task.exit    crash
     243    showcommand crash
     244  end
     245
    231246  # operation times out?
    232247  task.exit    timeout
     
    282297  end
    283298
     299  task.exit    crash
     300    showcommand crash
     301    book setword diffCleanup $options:0 pantaskState CRASH
     302  end
     303
    284304  # operation timed out?
    285305  task.exit    timeout
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/fake.pro

    r21464 r23352  
    2626    active true
    2727  end
    28   task fake.promoteexp
     28  task fake.advanceexp
    2929    active true
    3030  end
     
    3838    active false
    3939  end
    40   task fake.promoteexp
     40  task fake.advanceexp
    4141    active false
    4242  end
     
    176176  end
    177177
     178  # locked list
     179  task.exit    crash
     180    showcommand crash
     181    echo "hostname: $JOB_HOSTNAME"
     182    book setword fakePendingImfile $options:0 pantaskState CRASH
     183  end
     184
    178185  # operation timed out?
    179186  task.exit    timeout
     
    183190end
    184191
    185 # promote exposures for which all imfiles have completed processing
     192# advance exposures for which all imfiles have completed processing
    186193# sets the exposure state to full and queues warp processing if requested
    187 $fake_promote_DB = 0
    188 task           fake.promoteexp
     194$fake_advance_DB = 0
     195task           fake.advanceexp
    189196  host         local
    190197
     
    195202
    196203  stdout NULL
    197   stderr $LOGDIR/fake.promoteexp.log
    198 
    199   task.exec
    200     $run = faketool -promoteexp -limit 10
     204  stderr $LOGDIR/fake.advanceexp.log
     205
     206  task.exec
     207    $run = faketool -advanceexp -limit 10
    201208    if ($DB:n == 0)
    202209      option DEFAULT
    203210    else
    204211      # save the DB name for the exit tasks
    205       option $DB:$fake_promote_DB
    206       $run = $run -dbname $DB:$fake_promote_DB
    207       $fake_promote_DB ++
    208       if ($fake_promote_DB >= $DB:n) set fake_promote_DB = 0
     212      option $DB:$fake_advance_DB
     213      $run = $run -dbname $DB:$fake_advance_DB
     214      $fake_advance_DB ++
     215      if ($fake_advance_DB >= $DB:n) set fake_advance_DB = 0
    209216    end
    210217    add_poll_args run
     
    219226  task.exit    default
    220227    showcommand failure
     228  end
     229
     230  task.exit    crash
     231    showcommand crash
    221232  end
    222233
     
    278289  end
    279290
     291  task.exit    crash
     292    showcommand crash
     293  end
     294
    280295  # operation times out?
    281296  task.exit    timeout
     
    331346  end
    332347
     348  task.exit    crash
     349    showcommand crash
     350    book setword fakePendingCleanup $options:0 pantaskState CRASH
     351  end
     352
    333353  # operation timed out?
    334354  task.exit    timeout
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/flatcorr.pro

    r20513 r23352  
    104104  end
    105105
     106  task.exit    crash
     107    showcommand crash
     108  end
     109
    106110  # operation times out?
    107111  task.exit    timeout
     
    157161  end
    158162
     163  task.exit    crash
     164    showcommand crash
     165  end
     166
    159167  # operation times out?
    160168  task.exit    timeout
     
    229237  end
    230238
     239  task.exit    crash
     240    showcommand crash
     241    book setword flatcorrBook $options:0 pantaskState CRASH
     242  end
     243
    231244  # operation timed out?
    232245  task.exit    timeout
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/magic.pro

    r21436 r23352  
    118118  end
    119119
     120  task.exit    crash
     121    showcommand crash
     122  end
     123
    120124  # operation times out?
    121125  task.exit    timeout
     
    189193  end
    190194
     195  task.exit    crash
     196    showcommand crash
     197    book setword magicToTree $options:0 pantaskState CRASH
     198  end
     199
    191200  # operation timed out?
    192201  task.exit    timeout
     
    239248  end
    240249
     250  task.exit    crash
     251    showcommand crash
     252  end
     253
    241254  # operation times out?
    242255  task.exit    timeout
     
    302315  task.exit    default
    303316    process_exit magicToProcess $options:0 $JOB_STATUS
     317  end
     318
     319  task.exit    crash
     320    showcommand crash
     321    book setword magicToProcess $options:0 pantaskState CRASH
    304322  end
    305323
     
    353371  task.exit    default
    354372    showcommand failure
     373  end
     374
     375  task.exit    crash
     376    showcommand crash
    355377  end
    356378
     
    423445  end
    424446
     447  task.exit    crash
     448    showcommand crash
     449    book setword magicToDS $options:0 pantaskState CRASH
     450  end
     451
    425452  # operation timed out?
    426453  task.exit    timeout
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/pstamp.pro

    r21411 r23352  
    9797    end
    9898
     99    task.exit   crash
     100        showcommand crash
     101    end
     102
    99103    task.exit   timeout
    100104        showcommand timeout
     
    136140    end
    137141
     142    task.exit   crash
     143        showcommand crash
     144    end
     145
    138146    task.exit   timeout
    139147        showcommand timeout
     
    178186        showcommand failure
    179187        process_exit pstampRequest $options:0 $JOB_STATUS
     188    end
     189
     190    task.exit crash
     191        showcommand crash
     192        book setword pstampRequest $options:0 pantaskState CRASH
    180193    end
    181194
     
    219232    end
    220233
     234    task.exit   crash
     235        showcommand crash
     236    end
     237
    221238    task.exit   timeout
    222239        showcommand timeout
     
    263280        process_exit pstampFinish $options:0 $JOB_STATUS
    264281        showcommand failure
     282    end
     283
     284    task.exit crash
     285        showcommand crash
     286        book setword pstampFinish $options:0 pantaskState CRASH.run
    265287    end
    266288
     
    307329    end
    308330
     331    task.exit   crash
     332        showcommand crash
     333    end
     334
    309335    task.exit   timeout
    310336        showcommand timeout
     
    362388    end
    363389
     390    task.exit crash
     391        echo pstamp.job.run task.crash $JOB_ID status: $JOB_STATUS
     392        process_exit pstampJob $options:0 $JOB_STATUS
     393        showcommand crash
     394        book setword pstampJob $options:0 pantaskState CRASH
     395    end
     396
    364397    task.exit timeout
    365398        echo pstamp.job.run task.timeout $JOB_ID status: $JOB_STATUS
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/register.pro

    r20498 r23352  
    180180  end
    181181
     182  task.exit    crash
     183    showcommand crash
     184  end
     185
    182186  # operation times out?
    183187  task.exit    timeout
     
    255259  task.exit default
    256260    process_exit regPendingImfile $options:0 $JOB_STATUS
     261  end
     262
     263  # locked list
     264  task.exit    crash
     265    showcommand crash
     266    echo "hostname: $JOB_HOSTNAME"
     267    book setword regPendingImfile $options:0 pantaskState CRASH
    257268  end
    258269
     
    306317  task.exit    default
    307318    showcommand failure
     319  end
     320
     321  task.exit    crash
     322    showcommand crash
    308323  end
    309324
     
    392407  end
    393408
     409  # locked list
     410  task.exit    crash
     411    showcommand crash
     412    echo "hostname: $JOB_HOSTNAME"
     413    book setword regPendingExp $options:0 pantaskState CRASH
     414  end
     415
     416  task.exit    crash
     417    showcommand crash
     418    book setword regPendingExp $options:0 pantaskState CRASH
     419  end
     420
    394421  # operation times out?
    395422  task.exit    timeout
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/replicate.pro

    r19747 r23352  
    6262# the replicate process interacts with only the single Nebulous server
    6363
     64# Each 'pendingreplicate' query is limited to a finite number of so_id values. 
     65# Each time we call replicate.load, we increment SO_ID_START by the range value. 
     66# If the pendingreplicate query exits with exit status 10, we start over at 0
     67
     68$SO_ID_START = 0
     69$SO_ID_RANGE = 100000
     70
    6471# select Nebulous objects which desire additional copies
    6572task           replicate.load
     
    6875  # modify these after the tasks are tested
    6976  periods      -poll 10
    70   periods      -exec 1
     77  periods      -exec 10
    7178  periods      -timeout 1500
    7279  npending     1
     
    7986      # command does not need to be dynamic, but having it so allows us to adjust the periods
    8087      # so that we dont have to wait 10 minutes for things to start up
    81       command neb-admin --host $NEB_HOST --db $NEB_DB --user $NEB_USER --pass $NEB_PASS --pendingreplicate --limit 7500
     88      # XXX smaller limited?  7500 will be a huge book of things to do...
     89      command neb-admin --host $NEB_HOST --db $NEB_DB --user $NEB_USER --pass $NEB_PASS --pendingreplicate --limit 7500 --so_id_start $SO_ID_START --so_id_range $SO_ID_RANGE
    8290      periods      -exec 1800
    8391
     
    8694  # success
    8795  task.exit $EXIT_SUCCESS
     96    # advance the so_id counter
     97    $SO_ID_START += $SO_ID_RANGE
     98
    8899    # convert 'stdout' to book format
    89100    ipptool2book stdout replicatePending -key key -uniq -setword pantaskState INIT
     
    97108  end
    98109
     110  # out of so_id range, reset
     111  task.exit 10
     112    # advance the so_id counter
     113    $SO_ID_START = 0
     114  end
     115
    99116  # locked list
    100117  task.exit    default
    101118    showcommand failure
     119  end
     120
     121  task.exit    crash
     122    showcommand crash
    102123  end
    103124
     
    158179  end
    159180
     181  task.exit    crash
     182    showcommand crash
     183    book setword replicatePending $options:0 pantaskState CRASH
     184  end
     185
    160186  # operation timed out?
    161187  task.exit    timeout
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/stack.pro

    r19597 r23352  
    112112  end
    113113
     114  task.exit    crash
     115    showcommand crash
     116  end
     117
    114118  # operation times out?
    115119  task.exit    timeout
     
    172176  task.exit    default
    173177    process_exit stackSumSkyfile $options:0 $JOB_STATUS
     178  end
     179
     180  # locked list
     181  task.exit    crash
     182    showcommand crash
     183    echo "hostname: $JOB_HOSTNAME"
     184    book setword stackSumSkyfile $options:0 pantaskState CRASH
    174185  end
    175186
     
    229240  end
    230241
     242  task.exit    crash
     243    showcommand crash
     244  end
     245
    231246  # operation times out?
    232247  task.exit    timeout
     
    282297  end
    283298
     299  task.exit    crash
     300    showcommand crash
     301    book setword stackCleanup $options:0 pantaskState CRASH
     302  end
     303
    284304  # operation timed out?
    285305  task.exit    timeout
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/summit.copy.pro

    r21478 r23352  
    126126        showcommand failure
    127127    end
     128    task.exit crash
     129        showcommand crash
     130    end
    128131    task.exit timeout
    129132        showcommand timeout
     
    182185    showcommand failure
    183186  end
     187  task.exit     crash
     188    showcommand crash
     189  end
    184190  task.exit     timeout
    185191    showcommand timeout
     
    228234          queueprint stderr
    229235        end
     236    end
     237    task.exit crash
     238        showcommand crash
    230239    end
    231240    task.exit timeout
     
    296305        showcommand failure
    297306        process_exit pzPendingExp $options:0 $JOB_STATUS
     307    end
     308
     309    task.exit crash
     310        showcommand crash
     311        book setword pzPendingExp $options:0 pantaskState CRASH
    298312    end
    299313
     
    344358        showcommand failure
    345359    end
     360    task.exit     crash
     361        showcommand crash
     362    end
    346363    task.exit     timeout
    347364        showcommand timeout
     
    413430        book setword pzPendingImfile $pageName filename $FILENAME
    414431
     432        stdout $LOGDIR/summit.copy.log
     433        stderr $LOGDIR/summit.copy.log
     434
    415435        $run = summit_copy.pl --uri $URI --filename $FILENAME --exp_name $EXP_NAME --inst $CAMERA --telescope $TELESCOPE --class $CLASS --class_id $CLASS_ID --bytes $BYTES --md5 $MD5SUM --end_stage reg --workdir $workdir --dbname $DBNAME --timeout 120 --verbose --copies 2
    416436        if ($COMPRESS)
     
    442462    end
    443463
     464    task.exit crash
     465        showcommand crash
     466        book setword pzPendingImfile $options:0 pantaskState CRASH
     467    end
     468
    444469    # operation timed out?
    445470    task.exit timeout
     
    476501    task.exit default
    477502        showcommand failure
     503    end
     504    task.exit crash
     505        showcommand crash
    478506    end
    479507    task.exit timeout
     
    518546  end
    519547
     548  task.exit    crash
     549    showcommand crash
     550  end
     551
    520552  # operation times out?
    521553  task.exit    timeout
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/warp.pro

    r20932 r23352  
    127127  end
    128128
     129  task.exit    crash
     130    showcommand crash
     131  end
     132
    129133  # operation times out?
    130134  task.exit    timeout
     
    185189  task.exit    default
    186190    process_exit warpInputExp $options:0 $JOB_STATUS
     191  end
     192
     193  # locked list
     194  task.exit    crash
     195    showcommand crash
     196    echo "hostname: $JOB_HOSTNAME"
     197    book setword warpInputExp $options:0 pantaskState CRASH
    187198  end
    188199
     
    239250  task.exit    default
    240251    showcommand failure
     252  end
     253
     254  task.exit    crash
     255    showcommand crash
    241256  end
    242257
     
    303318  end
    304319
     320  # locked list
     321  task.exit    crash
     322    showcommand crash
     323    echo "hostname: $JOB_HOSTNAME"
     324    book setword warpPendingSkyCell $options:0 pantaskState CRASH
     325  end
     326
    305327  # operation timed out?
    306328  task.exit    timeout
     
    357379  end
    358380
     381  task.exit    crash
     382    showcommand crash
     383  end
     384
    359385  # operation times out?
    360386  task.exit    timeout
     
    410436  end
    411437
     438  task.exit    crash
     439    showcommand crash
     440    book setword warpPendingCleanup $options:0 pantaskState CRASH
     441  end
     442
    412443  # operation timed out?
    413444  task.exit    timeout
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/Makefile.am

    r21521 r23352  
    8484     difftool_skyfile.sql \
    8585     difftool_todiffskyfile.sql \
     86     disttool_pendingcomponent.sql \
     87     disttool_processedcomponent.sql \
     88     disttool_revertrun_update.sql \
     89     disttool_revertrun_delete.sql \
     90     disttool_toadvance.sql \
    8691     faketool_change_exp_state.sql \
    8792     faketool_change_imfile_data_state.sql \
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/chiptool_change_imfile_data_state.sql

    r19527 r23352  
    77    chip_id = %lld
    88    AND class_id = '%s'
    9     -- only update if chipRun.state has the expected value
    10     AND (
    11         SELECT state from chipRun where chipRun.chip_id = chipProcessedImfile.chip_id
    12     ) = '%s'
    13    
    14 
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/chiptool_pendingcleanupimfile.sql

    r19527 r23352  
    1515    ((chipRun.state = 'goto_cleaned' AND chipProcessedImfile.data_state = 'full')
    1616OR
     17    (chipRun.state = 'goto_scrubbed' AND chipProcessedImfile.data_state = 'full')
     18OR
    1719    (chipRun.state = 'goto_purged' AND chipProcessedImfile.data_state != 'purged'))
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/chiptool_pendingcleanuprun.sql

    r19527 r23352  
    77USING (exp_id)
    88WHERE
    9     (chipRun.state = 'goto_cleaned' OR chipRun.state = 'goto_purged')
     9    (chipRun.state = 'goto_cleaned' OR chipRun.state = 'goto_scrubbed' OR chipRun.state = 'goto_purged')
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/dettool_processedimfile.sql

    r18561 r23352  
     1-- is this DISTINCT needed?
    12SELECT DISTINCT
    23  detRun.det_type,
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/dettool_residimfile.sql

    r19632 r23352  
    22   detRun.det_type,
    33   detRun.mode,
    4    detResidImfile.*,
    5    rawExp.exp_time
    6  FROM detResidImfile
    7  JOIN detRun
    8    USING(det_id, iteration)
    9  JOIN rawExp
    10    USING(exp_id)
     4   rawExp.exp_time,
     5   detResidImfile.*
     6FROM detResidImfile
     7JOIN detRun
     8  USING(det_id, iteration)
     9JOIN detInputExp
     10  ON detRun.det_id = detInputExp.det_id
     11  AND detRun.iteration = detInputExp.iteration
     12  AND detResidImfile.exp_id = detInputExp.exp_id
     13JOIN rawExp
     14  ON rawExp.exp_id = detResidImfile.exp_id
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/dettool_todetrunsummary.sql

    r14078 r23352  
    4040        AND detRunSummary.det_id IS NULL
    4141        AND detRunSummary.iteration IS NULL
     42        AND detResidExp.fault = 0
    4243    GROUP BY
    4344        detRun.det_id,
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/dettool_tonormalizedstat.sql

    r18118 r23352  
    1 -- select detRun.det_id (det_id)
    2 -- select detRun.iteration
    3 -- by:
    4 -- find the current iteration bassed on det_id
    5 -- find all exp_ids in the current det_id/iteration from detInputExp
    6 -- sort to detInputExp.imfiles to find the largest value per det_id/iter
    7 -- compare imfiles to the number of detStackedImfiles by class_id
    8 -- and:
    9 -- ???
    10 -- det_id is not in detStackedImfile;
    11 -- iteration is not in detStackedImfile;
    12 
    13 SELECT
    14     det_id,
    15     det_type,
    16     iteration,
    17     camera,
    18     workdir,
    19     class_id
    20 FROM
    21     (SELECT DISTINCT
    22         detRun.det_id,
    23         detRun.det_type,
    24         detRun.iteration,
    25         detRun.workdir,
    26         rawExp.camera,
    27         detStackedImfile.class_id,
    28         rawImfile.class_id as rawimfile_class_id
    29     FROM detRun
    30     JOIN detInputExp
    31         ON detRun.det_id = detInputExp.det_id
    32         AND detRun.iteration = detInputExp.iteration
    33     JOIN rawExp
    34         ON detInputExp.exp_id = rawExp.exp_id
    35     JOIN rawImfile
    36         ON rawExp.exp_id = rawImfile.exp_id
    37     LEFT JOIN detStackedImfile
    38         ON detInputExp.det_id = detStackedImfile.det_id
    39         AND detInputExp.iteration = detStackedImfile.iteration
    40         AND rawImfile.class_id = detStackedImfile.class_id
    41     LEFT JOIN detNormalizedStatImfile
    42         ON detStackedImfile.det_id = detNormalizedStatImfile.det_id
    43         AND detStackedImfile.iteration = detNormalizedStatImfile.iteration
    44         AND detStackedImfile.class_id = detNormalizedStatImfile.class_id
    45     WHERE
    46         detRun.state = 'run'
    47         AND detRun.mode = 'master'
    48         AND detNormalizedStatImfile.det_id IS NULL
    49         AND detNormalizedStatImfile.iteration IS NULL
    50         AND detNormalizedStatImfile.class_id IS NULL
    51     GROUP BY
    52 --        rawExp.exp_id,
    53         detRun.iteration,
    54         detRun.det_id
    55     HAVING
    56         COUNT(rawImfile.class_id) = COUNT(detStackedImfile.class_id)
    57         AND SUM(detStackedImfile.fault) = 0
    58     ) as tonormalizedstat
     1-- a det_run + iteration is ready for normstat when: all detResidImfile entries for that iteration corresponding to all detProcessedImfile entries are available
     2SELECT
     3  detRun.det_id,
     4  detRun.det_type,
     5  detRun.iteration,
     6  detRun.camera,
     7  detRun.workdir,
     8  detProcessedImfile.class_id,
     9  COUNT(detProcessedImfile.class_id),
     10  COUNT(detResidImfile.class_id)
     11FROM detRun
     12JOIN detProcessedImfile
     13    ON  detProcessedImfile.det_id    = detRun.det_id
     14LEFT JOIN detResidImfile
     15    ON  detResidImfile.det_id    = detProcessedImfile.det_id
     16    AND detResidImfile.exp_id    = detProcessedImfile.exp_id
     17    AND detResidImfile.class_id  = detProcessedImfile.class_id
     18    AND detResidImfile.iteration = detRun.iteration
     19LEFT JOIN detNormalizedStatImfile
     20    ON  detNormalizedStatImfile.det_id    = detRun.det_id   
     21    AND detNormalizedStatImfile.iteration = detRun.iteration
     22    AND detNormalizedStatImfile.class_id  = detProcessedImfile.class_id
     23WHERE
     24    detRun.state = 'run'
     25    AND detRun.mode = 'master'
     26    AND detNormalizedStatImfile.det_id IS NULL
     27    AND detNormalizedStatImfile.iteration IS NULL
     28    AND detNormalizedStatImfile.class_id IS NULL
     29GROUP BY
     30    detRun.iteration,
     31    detRun.det_id
     32HAVING
     33    COUNT(detProcessedImfile.class_id) = COUNT(detResidImfile.class_id)
     34    AND SUM(detResidImfile.fault) = 0
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/dettool_toresidexp.sql

    r19815 r23352  
    55-- id, detrend type, and whether the exposure was included in the stack for
    66-- this iteration.
     7
     8-- require the corresponding detNormalizedExp to complete before starting
    79
    810-- select detRun.det_id
     
    1820-- detResidImfile.{det_id, iteration, exp_id} is not in detResidExp
    1921
    20 SELECT DISTINCT
     22SELECT
    2123    det_id,
    2224    iteration,
     
    2830    workdir,
    2931    exp_tag
    30 FROM
    31     (SELECT DISTINCT
     32FROM 
     33(   SELECT
    3234        detRun.det_id AS det_id,
    3335        detRun.iteration,
    3436        detRun.det_type,
    3537        detRun.mode,
    36         detRun.workdir,
    3738        detInputExp.exp_id,
    3839        detInputExp.include,
    3940        rawExp.camera,
    40         rawExp.exp_tag,
    41         detResidImfile.class_id
     41        detRun.workdir,
     42        rawExp.exp_tag
     43    FROM detRun
     44    JOIN detNormalizedExp
     45        USING(det_id, iteration)
     46    JOIN detInputExp
     47        USING(det_id, iteration)
     48    JOIN rawExp
     49        ON detInputExp.exp_id = rawExp.exp_id
     50    JOIN rawImfile
     51        on rawExp.exp_id = rawImfile.exp_id
     52    LEFT JOIN detResidImfile
     53        ON detRun.det_id = detResidImfile.det_id
     54        AND detRun.iteration = detResidImfile.iteration
     55        AND detInputExp.exp_id = detResidImfile.exp_id
     56        AND rawImfile.class_id = detResidImfile.class_id
     57    LEFT JOIN detResidExp
     58        ON detResidImfile.det_id = detResidExp.det_id
     59        AND detResidImfile.iteration = detResidExp.iteration
     60        AND detResidImfile.exp_id = detResidExp.exp_id
     61    WHERE
     62        detRun.state = 'run'
     63        AND detRun.mode = 'master'
     64        AND detResidExp.det_id IS NULL
     65        AND detResidExp.iteration IS NULL
     66        AND detResidExp.exp_id IS NULL
     67    GROUP BY
     68        detInputExp.exp_id,
     69        detRun.iteration,
     70        detRun.det_id
     71    HAVING
     72        COUNT(rawImfile.class_id) = COUNT(detResidImfile.class_id)
     73        AND SUM(detResidImfile.fault) = 0
     74    UNION
     75    SELECT
     76        detRun.det_id AS det_id,
     77        detRun.iteration,
     78        detRun.det_type,
     79        detRun.mode,
     80        detInputExp.exp_id,
     81        detInputExp.include,
     82        rawExp.camera,
     83        detRun.workdir,
     84        rawExp.exp_tag
    4285    FROM detRun
    4386    JOIN detInputExp
     
    58101    WHERE
    59102        detRun.state = 'run'
     103        AND detRun.mode = 'verify'
    60104        AND detResidExp.det_id IS NULL
    61105        AND detResidExp.iteration IS NULL
     
    68112        COUNT(rawImfile.class_id) = COUNT(detResidImfile.class_id)
    69113        AND SUM(detResidImfile.fault) = 0
    70     ) AS toresidexp
     114) as temp
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/dettool_toresidimfile.sql

    r19816 r23352  
    1313    detProcessedImfile.class_id,
    1414    detProcessedImfile.uri,
    15     detNormalizedImfile.uri AS det_uri,
     15--  detNormalizedImfile.uri AS det_uri,
     16    detStackedImfile.uri AS det_uri,
    1617    detRun.det_id AS ref_det_id,
    1718    detRun.iteration AS ref_iter,
     
    2627    ON detRun.det_id = detProcessedImfile.det_id
    2728    AND detInputExp.exp_id = detProcessedImfile.exp_id
    28 JOIN detNormalizedImfile
    29     ON detRun.det_id = detNormalizedImfile.det_id
    30     AND detRun.iteration = detNormalizedImfile.iteration
    31     AND detProcessedImfile.class_id = detNormalizedImfile.class_id
    32 JOIN detNormalizedExp
    33     ON detRun.det_id = detNormalizedExp.det_id
    34     AND detRun.iteration = detNormalizedExp.iteration
     29JOIN detStackedImfile
     30    ON detRun.det_id = detStackedImfile.det_id
     31    AND detRun.iteration = detStackedImfile.iteration
     32    AND detProcessedImfile.class_id = detStackedImfile.class_id
     33-- EAM : replacing detNormalizedImfile with detStackedImfile to change the sequencing
     34-- JOIN detNormalizedImfile
     35--     ON detRun.det_id = detNormalizedImfile.det_id
     36--     AND detRun.iteration = detNormalizedImfile.iteration
     37--     AND detProcessedImfile.class_id = detNormalizedImfile.class_id
     38-- EAM : we there is no reason to wait for all stacks to complete before continuing
     39-- JOIN detNormalizedExp
     40--     ON detRun.det_id = detNormalizedExp.det_id
     41--     AND detRun.iteration = detNormalizedExp.iteration
    3542LEFT JOIN detResidImfile
    3643    ON detRun.det_id = detResidImfile.det_id
     
    4148    detRun.state = 'run'
    4249    AND detRun.mode = 'master'
    43     AND detNormalizedImfile.fault = 0
    44     AND detNormalizedExp.fault = 0
     50    AND detStackedImfile.fault = 0
     51--  AND detNormalizedImfile.fault = 0
     52--  AND detNormalizedExp.fault = 0
    4553    AND detResidImfile.det_id IS NULL
    4654    AND detResidImfile.iteration IS NULL
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/pxadmin_create_tables.sql

    r21308 r23352  
    737737    REFERENCES  detInputExp(det_id, iteration, exp_id),
    738738    FOREIGN KEY (det_id, exp_id, class_id)
    739     REFERENCES  detProcessedImfile(det_id, exp_id, class_id),
    740     FOREIGN KEY (ref_det_id, ref_iter)
    741     REFERENCES  detNormalizedExp(det_id, iteration)
     739    REFERENCES  detProcessedImfile(det_id, exp_id, class_id)
    742740) ENGINE=innodb DEFAULT CHARSET=latin1;
    743741
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/warptool_change_skyfile_data_state.sql

    r19521 r23352  
    99    AND skycell_id = '%s'
    1010    -- only update if chipRun.state has the expected value
    11     AND (
    12         SELECT state from warpRun where warpRun.warp_id = warpSkyfile.warp_id
    13     ) = '%s'
    14    
    15 
     11--    AND (
     12--        SELECT state from warpRun where warpRun.warp_id = warpSkyfile.warp_id
     13--    ) = '%s'
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/camtool.c

    r21443 r23352  
    4444static bool pendingcleanupexpMode(pxConfig *config);
    4545static bool donecleanupMode(pxConfig *config);
     46static bool exportrunMode(pxConfig *config);
     47static bool importrunMode(pxConfig *config);
    4648
    4749# define MODECASE(caseName, func) \
     
    7779        MODECASE(CAMTOOL_MODE_PENDINGCLEANUPEXP,    pendingcleanupexpMode);
    7880        MODECASE(CAMTOOL_MODE_DONECLEANUP,          donecleanupMode);
     81        MODECASE(CAMTOOL_MODE_EXPORTRUN,            exportrunMode);
     82        MODECASE(CAMTOOL_MODE_IMPORTRUN,            importrunMode);
    7983        default:
    8084            psAbort("invalid option (this should not happen)");
     
    10811085    return true;
    10821086}
     1087
     1088bool exportrunMode(pxConfig *config)
     1089{
     1090  typedef struct ExportTable {
     1091    char tableName[80];
     1092    char sqlFilename[80];
     1093  } ExportTable;
     1094 
     1095  int numExportTables = 2;
     1096
     1097  PS_ASSERT_PTR_NON_NULL(config, NULL);
     1098
     1099  PXOPT_LOOKUP_S64(det_id, config->args, "-cam_id", true,  false);
     1100  PXOPT_LOOKUP_STR(outfile, config->args, "-outfile", true,  false);
     1101  PXOPT_LOOKUP_U64(limit,   config->args, "-limit",   false, false);
     1102
     1103  FILE *f = fopen (outfile, "w");
     1104  if (f == NULL) {
     1105    psError(PS_ERR_UNKNOWN, false, "failed to open output file");
     1106    return false;
     1107  }
     1108
     1109  psMetadata *where = psMetadataAlloc();
     1110  PXOPT_COPY_S64(config->args, where, "-cam_id", "cam_id", "==");
     1111
     1112  ExportTable tables [] = {
     1113    {"camRun", "camtool_export_run.sql"},
     1114    {"camProcessedExp", "camtool_export_processed_exp.sql"},
     1115  };
     1116
     1117  for (int i=0; i < numExportTables; i++) {
     1118    psString query = pxDataGet(tables[i].sqlFilename);
     1119    if (!query) {
     1120      psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
     1121      return false;
     1122    }
     1123
     1124    if (where && psListLength(where->list)) {
     1125      psString whereClause = psDBGenerateWhereSQL(where, NULL);
     1126      psStringAppend(&query, " %s", whereClause);
     1127      psFree(whereClause);
     1128    }
     1129
     1130    // treat limit == 0 as "no limit"
     1131    if (limit) {
     1132      psString limitString = psDBGenerateLimitSQL(limit);
     1133      psStringAppend(&query, " %s", limitString);
     1134      psFree(limitString);
     1135    }
     1136
     1137    if (!p_psDBRunQuery(config->dbh, query)) {
     1138      psError(PS_ERR_UNKNOWN, false, "database error");
     1139      psFree(query);
     1140      return false;
     1141    }
     1142    psFree(query);
     1143
     1144    psArray *output = p_psDBFetchResult(config->dbh);
     1145    if (!output) {
     1146      psError(PS_ERR_UNKNOWN, false, "database error");
     1147      return false;
     1148    }
     1149    if (!psArrayLength(output)) {
     1150      psTrace("regtool", PS_LOG_INFO, "no rows found");
     1151      psFree(output);
     1152      return true;
     1153    }
     1154
     1155    // we must write the export table in non-simple (true) format
     1156    if (!ippdbPrintMetadatas(f, output, tables[i].tableName, true)) {
     1157      psError(PS_ERR_UNKNOWN, false, "failed to print array");
     1158      psFree(output);
     1159      return false;
     1160    }
     1161    psFree(output);
     1162  }
     1163
     1164  fclose (f);
     1165
     1166  return true;
     1167}
     1168
     1169bool importrunMode(pxConfig *config)
     1170{
     1171  unsigned int nFail;
     1172
     1173  PS_ASSERT_PTR_NON_NULL(config, NULL);
     1174 
     1175  PXOPT_LOOKUP_STR(infile, config->args, "-infile", true,  false);
     1176
     1177  psMetadata *input = psMetadataConfigRead (NULL, &nFail, infile, false);
     1178
     1179  fprintf (stdout, "---- input ----\n");
     1180  psMetadataPrint (stderr, input, 1);
     1181
     1182  psMetadataItem *item = psMetadataLookup (input, "camRun");
     1183  psAssert (item, "entry not in input?");
     1184  psAssert (item->type == PS_DATA_METADATA_MULTI, "entry not multi?");
     1185 
     1186  psMetadataItem *entry = psListGet (item->data.list, 0);
     1187  assert (entry);
     1188  assert (entry->type == PS_DATA_METADATA);
     1189  camRunRow *camRun = camRunObjectFromMetadata (entry->data.md);
     1190  camRunInsertObject (config->dbh, camRun);
     1191
     1192  // fprintf (stdout, "---- cam run ----\n");
     1193  // psMetadataPrint (stderr, entry->data.md, 1);
     1194 
     1195  item = psMetadataLookup (input, "camProcessedImfile");
     1196  psAssert (item, "entry not in input?");
     1197  psAssert (item->type == PS_DATA_METADATA_MULTI, "entry not multi?");
     1198
     1199  for (int i = 0; i < item->data.list->n; i++) {
     1200    psMetadataItem *entry = psListGet (item->data.list, i);
     1201    assert (entry);
     1202    assert (entry->type == PS_DATA_METADATA);
     1203    camProcessedExpRow *camProcessedExp = camProcessedExpObjectFromMetadata (entry->data.md);
     1204    camProcessedExpInsertObject (config->dbh, camProcessedExp);
     1205
     1206    // fprintf (stdout, "---- row %d ----\n", i);
     1207    // psMetadataPrint (stderr, entry->data.md, 1);
     1208  }
     1209
     1210  return true;
     1211}
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/camtool.h

    r19092 r23352  
    3939    CAMTOOL_MODE_PENDINGCLEANUPEXP,
    4040    CAMTOOL_MODE_DONECLEANUP,
     41    CAMTOOL_MODE_EXPORTRUN,
     42    CAMTOOL_MODE_IMPORTRUN
    4143} camtoolMode;
    4244
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/camtoolConfig.c

    r20276 r23352  
    228228    psMetadataAddU64(donecleanupArgs, PS_LIST_TAIL, "-limit",  0,            "limit result set to N items", 0);
    229229
     230    // -exportrun
     231    psMetadata *exportrunArgs = psMetadataAlloc();
     232    psMetadataAddS64(exportrunArgs, PS_LIST_TAIL, "-cam_id", 0,          "export this camera ID (required)", 0);
     233    psMetadataAddStr(exportrunArgs, PS_LIST_TAIL, "-outfile", 0,          "export to this file (required)", NULL);
     234    psMetadataAddU64(exportrunArgs, PS_LIST_TAIL, "-limit",   0,          "limit result set to N items", 0);
     235
     236    // -importrun
     237    psMetadata *importrunArgs = psMetadataAlloc();
     238    psMetadataAddStr(importrunArgs, PS_LIST_TAIL, "-infile",  0,          "import from this file (required)", NULL);
     239
     240
    230241    psMetadata *argSets = psMetadataAlloc();
    231242    psMetadata *modes = psMetadataAlloc();
     
    245256    PXOPT_ADD_MODE("-pendingcleanupexp",    "show exposures for cleanup runs",      CAMTOOL_MODE_PENDINGCLEANUPEXP, pendingcleanupexpArgs);
    246257    PXOPT_ADD_MODE("-donecleanup",          "show runs that have been cleaned",     CAMTOOL_MODE_DONECLEANUP,       donecleanupArgs);
     258   PXOPT_ADD_MODE("-exportrun",            "export run for import on other database", CAMTOOL_MODE_EXPORTRUN, exportrunArgs);
     259    PXOPT_ADD_MODE("-importrun",            "import run from metadata file",           CAMTOOL_MODE_IMPORTRUN, importrunArgs);
    247260
    248261    if (!pxGetOptions(stderr, argc, argv, config, modes, argSets)) {
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/chiptool.c

    r21521 r23352  
    4242static bool revertprocessedimfileMode(pxConfig *config);
    4343static bool updateprocessedimfileMode(pxConfig *config);
    44 static bool promoteexpMode(pxConfig *config);
     44static bool advanceexpMode(pxConfig *config);
    4545static bool blockMode(pxConfig *config);
    4646static bool maskedMode(pxConfig *config);
     
    8181        MODECASE(CHIPTOOL_MODE_REVERTPROCESSEDIMFILE,   revertprocessedimfileMode);
    8282        MODECASE(CHIPTOOL_MODE_UPDATEPROCESSEDIMFILE,   updateprocessedimfileMode);
    83         MODECASE(CHIPTOOL_MODE_PROMOTEEXP,              promoteexpMode);
     83        MODECASE(CHIPTOOL_MODE_ADVANCEEXP,              advanceexpMode);
    8484        MODECASE(CHIPTOOL_MODE_BLOCK,                   blockMode);
    8585        MODECASE(CHIPTOOL_MODE_MASKED,                  maskedMode);
     
    239239    pxchipGetSearchArgs (config, where); // rawExp, chipRun
    240240    PXOPT_COPY_S64(config->args,  where, "-chip_id", "chipRun.chip_id", "==");
    241     PXOPT_COPY_STR(config->args,  where, "-label", "chipRun.label", "==");
     241    PXOPT_COPY_STR(config->args,  where, "-label",   "chipRun.label",   "==");
     242    PXOPT_COPY_STR(config->args,  where, "-state",   "chipRun.state",   "==");
    242243
    243244    if (!psListLength(where->list)
     
    10781079
    10791080
    1080 static bool promoteexpMode(pxConfig *config)
     1081static bool advanceexpMode(pxConfig *config)
    10811082{
    10821083    PS_ASSERT_PTR_NON_NULL(config, false);
     
    12561257bool exportrunMode(pxConfig *config)
    12571258{
    1258     PS_ASSERT_PTR_NON_NULL(config, NULL);
    1259 
    1260     PXOPT_LOOKUP_S64(chip_id, config->args, "-chip_id", true,  false);
    1261     PXOPT_LOOKUP_STR(outfile, config->args, "-outfile", true,  false);
    1262     PXOPT_LOOKUP_U64(limit,   config->args, "-limit",   false, false);
    1263 
    1264     FILE *f = fopen (outfile, "w");
    1265     if (f == NULL) {
    1266         psError(PS_ERR_UNKNOWN, false, "failed to open output file");
    1267         return false;
    1268     }
    1269 
    1270     psMetadata *where = psMetadataAlloc();
    1271     PXOPT_COPY_S64(config->args, where, "-chip_id", "chip_id", "==");
    1272 
    1273     // *** extract the chipRun in this section ***
    1274     psString query = pxDataGet("chiptool_export_run.sql");
     1259  typedef struct ExportTable {
     1260    char tableName[80];
     1261    char sqlFilename[80];
     1262  } ExportTable;
     1263 
     1264  int numExportTables = 3;
     1265
     1266  PS_ASSERT_PTR_NON_NULL(config, NULL);
     1267
     1268  PXOPT_LOOKUP_S64(det_id, config->args, "-chip_id", true,  false);
     1269  PXOPT_LOOKUP_STR(outfile, config->args, "-outfile", true,  false);
     1270  PXOPT_LOOKUP_U64(limit,   config->args, "-limit",   false, false);
     1271
     1272  FILE *f = fopen (outfile, "w");
     1273  if (f == NULL) {
     1274    psError(PS_ERR_UNKNOWN, false, "failed to open output file");
     1275    return false;
     1276  }
     1277
     1278  psMetadata *where = psMetadataAlloc();
     1279  PXOPT_COPY_S64(config->args, where, "-chip_id", "chip_id", "==");
     1280
     1281  ExportTable tables [] = {
     1282    {"chipRun", "chiptool_export_run.sql"},
     1283    {"chipImfile", "chiptool_export_imfile.sql"},
     1284    {"chipProcessedImfile", "chiptool_export_processed_imfile.sql"},
     1285  };
     1286
     1287
     1288  for (int i=0; i < numExportTables; i++) {
     1289    psString query = pxDataGet(tables[i].sqlFilename);
    12751290    if (!query) {
    1276         psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
    1277         return false;
     1291      psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
     1292      return false;
    12781293    }
    12791294
    12801295    if (where && psListLength(where->list)) {
    1281         psString whereClause = psDBGenerateWhereSQL(where, NULL);
    1282         psStringAppend(&query, " %s", whereClause);
    1283         psFree(whereClause);
     1296      psString whereClause = psDBGenerateWhereSQL(where, NULL);
     1297      psStringAppend(&query, " %s", whereClause);
     1298      psFree(whereClause);
    12841299    }
    12851300
    12861301    // treat limit == 0 as "no limit"
    12871302    if (limit) {
    1288         psString limitString = psDBGenerateLimitSQL(limit);
    1289         psStringAppend(&query, " %s", limitString);
    1290         psFree(limitString);
     1303      psString limitString = psDBGenerateLimitSQL(limit);
     1304      psStringAppend(&query, " %s", limitString);
     1305      psFree(limitString);
    12911306    }
    12921307
    12931308    if (!p_psDBRunQuery(config->dbh, query)) {
    1294         psError(PS_ERR_UNKNOWN, false, "database error");
    1295         psFree(query);
    1296         return false;
     1309      psError(PS_ERR_UNKNOWN, false, "database error");
     1310      psFree(query);
     1311      return false;
    12971312    }
    12981313    psFree(query);
     
    13001315    psArray *output = p_psDBFetchResult(config->dbh);
    13011316    if (!output) {
    1302         psError(PS_ERR_UNKNOWN, false, "database error");
    1303         return false;
     1317      psError(PS_ERR_UNKNOWN, false, "database error");
     1318      return false;
    13041319    }
    13051320    if (!psArrayLength(output)) {
    1306         psTrace("chiptool", PS_LOG_INFO, "no rows found");
    1307         psFree(output);
    1308         return true;
     1321      psTrace("regtool", PS_LOG_INFO, "no rows found");
     1322      psFree(output);
     1323      return true;
    13091324    }
    13101325
    13111326    // we must write the export table in non-simple (true) format
    1312     if (!ippdbPrintMetadatas(f, output, "chipRun", true)) {
    1313         psError(PS_ERR_UNKNOWN, false, "failed to print array");
    1314         psFree(output);
    1315         return false;
     1327    if (!ippdbPrintMetadatas(f, output, tables[i].tableName, true)) {
     1328      psError(PS_ERR_UNKNOWN, false, "failed to print array");
     1329      psFree(output);
     1330      return false;
    13161331    }
    13171332    psFree(output);
    1318 
    1319     // *** extract the chipProcessedImfile entries in this section ***
    1320     query = pxDataGet("chiptool_export_imfiles.sql");
    1321     if (!query) {
    1322         psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
    1323         return false;
    1324     }
    1325 
    1326     if (where && psListLength(where->list)) {
    1327         psString whereClause = psDBGenerateWhereSQL(where, NULL);
    1328         psStringAppend(&query, " %s", whereClause);
    1329         psFree(whereClause);
    1330     }
    1331     psFree(where);
    1332 
    1333     // treat limit == 0 as "no limit"
    1334     if (limit) {
    1335         psString limitString = psDBGenerateLimitSQL(limit);
    1336         psStringAppend(&query, " %s", limitString);
    1337         psFree(limitString);
    1338     }
    1339 
    1340     if (!p_psDBRunQuery(config->dbh, query)) {
    1341         psError(PS_ERR_UNKNOWN, false, "database error");
    1342         psFree(query);
    1343         return false;
    1344     }
    1345     psFree(query);
    1346 
    1347     output = p_psDBFetchResult(config->dbh);
    1348     if (!output) {
    1349         psError(PS_ERR_UNKNOWN, false, "database error");
    1350         return false;
    1351     }
    1352     if (!psArrayLength(output)) {
    1353         psTrace("chiptool", PS_LOG_INFO, "no rows found");
    1354         psFree(output);
    1355         return true;
    1356     }
    1357 
    1358     // we must write the export table in non-simple (true) format
    1359     if (!ippdbPrintMetadatas(f, output, "chipProcessedImfiles", true)) {
    1360         psError(PS_ERR_UNKNOWN, false, "failed to print array");
    1361         psFree(output);
    1362         return false;
    1363     }
    1364     psFree(output);
    1365 
    1366     fclose (f);
    1367 
    1368     return true;
    1369 }
    1370 
     1333  }
     1334
     1335  fclose (f);
     1336
     1337  return true;
     1338}
    13711339
    13721340bool importrunMode(pxConfig *config)
    13731341{
    13741342  unsigned int nFail;
     1343 
     1344  int numImportTables = 2;
     1345 
     1346  char tables[2] [80] = {"chipImfile", "chipProcessedImfile"};
    13751347
    13761348  PS_ASSERT_PTR_NON_NULL(config, NULL);
     
    13831355  psMetadataPrint (stderr, input, 1);
    13841356
    1385   psMetadataItem *chipRunItem = psMetadataLookup (input, "chipRun");
    1386   psAssert (chipRunItem, "entry not in input?");
    1387   psAssert (chipRunItem->type == PS_DATA_METADATA_MULTI, "entry not multi?");
    1388  
    1389   psMetadataItem *chipRunEntry = psListGet (chipRunItem->data.list, 0);
    1390   assert (chipRunEntry);
    1391   assert (chipRunEntry->type == PS_DATA_METADATA);
    1392   chipRunRow *chipRun = chipRunObjectFromMetadata (chipRunEntry->data.md);
    1393   chipRunInsertObject (config->dbh, chipRun);
    1394 
    1395   // fprintf (stdout, "---- chip run ----\n");
    1396   // psMetadataPrint (stderr, chipRunEntry->data.md, 1);
    1397 
    1398   psMetadataItem *item = psMetadataLookup (input, "chipProcessedImfiles");
     1357  psMetadataItem *item = psMetadataLookup (input, "chipRun");
    13991358  psAssert (item, "entry not in input?");
    14001359  psAssert (item->type == PS_DATA_METADATA_MULTI, "entry not multi?");
    14011360
    1402   // XXX would be better to use the iterator?
    1403   for (int i = 0; i < item->data.list->n; i++) {
    1404     psMetadataItem *entry = psListGet (item->data.list, i);
    1405     assert (entry);
    1406     assert (entry->type == PS_DATA_METADATA);
    1407     chipProcessedImfileRow *chipProcessedImfile = chipProcessedImfileObjectFromMetadata (entry->data.md);
    1408     chipProcessedImfileInsertObject (config->dbh, chipProcessedImfile);
    1409 
    1410     // fprintf (stdout, "---- row %d ----\n", i);
    1411     // psMetadataPrint (stderr, entry->data.md, 1);
     1361  psMetadataItem *entry = psListGet (item->data.list, 0);
     1362  assert (entry);
     1363  assert (entry->type == PS_DATA_METADATA);
     1364  chipRunRow *chipRun = chipRunObjectFromMetadata (entry->data.md);
     1365  chipRunInsertObject (config->dbh, chipRun);
     1366
     1367  // fprintf (stdout, "---- chip run ----\n");
     1368  // psMetadataPrint (stderr, entry->data.md, 1);
     1369 
     1370  for (int i = 0; i < numImportTables; i++) {
     1371    psMetadataItem *item = psMetadataLookup (input, tables[i]);
     1372    psAssert (item, "entry not in input?");
     1373    psAssert (item->type == PS_DATA_METADATA_MULTI, "entry not multi?");
     1374 
     1375    switch (i) {
     1376      case 0:
     1377        for (int i = 0; i < item->data.list->n; i++) {
     1378          psMetadataItem *entry = psListGet (item->data.list, i);
     1379          assert (entry);
     1380          assert (entry->type == PS_DATA_METADATA);
     1381          chipImfileRow *chipImfile = chipImfileObjectFromMetadata (entry->data.md);
     1382          chipImfileInsertObject (config->dbh, chipImfile);
     1383
     1384          // fprintf (stdout, "---- row %d ----\n", i);
     1385          // psMetadataPrint (stderr, entry->data.md, 1);
     1386        }
     1387        break;
     1388       
     1389      case 1:
     1390        for (int i = 0; i < item->data.list->n; i++) {
     1391          psMetadataItem *entry = psListGet (item->data.list, i);
     1392          assert (entry);
     1393          assert (entry->type == PS_DATA_METADATA);
     1394          chipProcessedImfileRow *chipProcessedImfile = chipProcessedImfileObjectFromMetadata (entry->data.md);
     1395          chipProcessedImfileInsertObject (config->dbh, chipProcessedImfile);
     1396
     1397          // fprintf (stdout, "---- row %d ----\n", i);
     1398          // psMetadataPrint (stderr, entry->data.md, 1);
     1399        }
     1400        break;
     1401    }
    14121402  }
    14131403
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/chiptool.h

    r21521 r23352  
    3232    CHIPTOOL_MODE_REVERTPROCESSEDIMFILE,
    3333    CHIPTOOL_MODE_UPDATEPROCESSEDIMFILE,
    34     CHIPTOOL_MODE_PROMOTEEXP,
     34    CHIPTOOL_MODE_ADVANCEEXP,
    3535    CHIPTOOL_MODE_BLOCK,
    3636    CHIPTOOL_MODE_MASKED,
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/chiptoolConfig.c

    r21521 r23352  
    6767    psMetadataAddS64(updaterunArgs, PS_LIST_TAIL, "-chip_id",              0,            "search by chip ID", 0);
    6868    psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-state", 0,            "set state", NULL);
     69    psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-label",  0,          "search by label", NULL);
    6970    psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-set_state", 0,        "set state", NULL);
    7071    psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-set_label", 0,        "set label", NULL);
    7172    psMetadataAddBool(updaterunArgs, PS_LIST_TAIL, "-all",  0,            "allow everything to be queued without search terms", false);
    72     psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-label",  0,          "search by label", NULL);
    7373
    7474    // -pendingimfile
     
    176176    psMetadataAddS16(updateprocessedimfileArgs, PS_LIST_TAIL, "-code",  0,            "set fault code (required)", 0);
    177177
    178     // -promoteexp
    179     psMetadata *promoteexpArgs = psMetadataAlloc();
    180     psMetadataAddS64(promoteexpArgs, PS_LIST_TAIL, "-chip_id",  0,          "search by chip ID", 0);
    181     psMetadataAddStr(promoteexpArgs, PS_LIST_TAIL, "-label",  0,            "promote exposures for specified label", NULL);
    182     psMetadataAddU64(promoteexpArgs, PS_LIST_TAIL, "-limit",  0,            "limit result set to N items", 0);
     178    // -advanceexp
     179    psMetadata *advanceexpArgs = psMetadataAlloc();
     180    psMetadataAddS64(advanceexpArgs, PS_LIST_TAIL, "-chip_id",  0,          "search by chip ID", 0);
     181    psMetadataAddStr(advanceexpArgs, PS_LIST_TAIL, "-label",  0,            "advance exposures for specified label", NULL);
     182    psMetadataAddU64(advanceexpArgs, PS_LIST_TAIL, "-limit",  0,            "limit result set to N items", 0);
    183183
    184184    // -block
     
    265265    PXOPT_ADD_MODE("-updateprocessedimfile","change procesed imfile properties",    CHIPTOOL_MODE_UPDATEPROCESSEDIMFILE,updateprocessedimfileArgs);
    266266    PXOPT_ADD_MODE("-revertprocessedimfile","undo a processed imfile",              CHIPTOOL_MODE_REVERTPROCESSEDIMFILE,revertprocessedimfileArgs);
    267     PXOPT_ADD_MODE("-promoteexp",           "promote completed exposures",          CHIPTOOL_MODE_PROMOTEEXP,           promoteexpArgs);
     267    PXOPT_ADD_MODE("-advanceexp",           "advance completed exposures",          CHIPTOOL_MODE_ADVANCEEXP,           advanceexpArgs);
    268268    PXOPT_ADD_MODE("-block",                "set a label block",                    CHIPTOOL_MODE_BLOCK,                blockArgs);
    269269    PXOPT_ADD_MODE("-masked",               "show blocked labels",                  CHIPTOOL_MODE_MASKED,               maskedArgs);
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/dettool.c

    r21402 r23352  
    2828static bool inputMode(pxConfig *config);
    2929static bool rawMode(pxConfig *config);
     30static bool exportrunMode(pxConfig *config);
     31static bool importrunMode(pxConfig *config);
    3032
    3133// run
     
    4648    } \
    4749    break;
    48 
     50/*
     51typedef struct ExportTable {
     52    char tableName[80];
     53    char sqlFilename[80];
     54} ExportTable;
     55*/
    4956int main(int argc, char **argv)
    5057{
     
    146153        MODECASE(DETTOOL_MODE_REGISTER_DETREND, register_detrendMode);
    147154        MODECASE(DETTOOL_MODE_REGISTER_DETREND_IMFILE, register_detrend_imfileMode);
     155        MODECASE(DETTOOL_MODE_EXPORTRUN,               exportrunMode);
     156        MODECASE(DETTOOL_MODE_IMPORTRUN,               importrunMode);
    148157        default:
    149158            psAbort("invalid option (this should not happen)");
     
    578587      // generate a random-valued vector, return an index sorted by the random values
    579588      psVector *randomVector = psVectorAlloc(detrendExps->n, PS_TYPE_F32); // random values
    580       psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 0);
     589      /*
     590       * change due to PAP work on random number generator?
     591       * psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 0);
     592       */
     593      psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS);
    581594      for (int i = 0; i < randomVector->n; i++) {
    582595        randomVector->data.F32[i] = psRandomUniform(rng);
     
    19962009}
    19972010
     2011bool exportrunMode(pxConfig *config)
     2012{
     2013  typedef struct ExportTable {
     2014    char tableName[80];
     2015    char sqlFilename[80];
     2016  } ExportTable;
     2017 
     2018  int numExportTables = 12;
     2019
     2020  PS_ASSERT_PTR_NON_NULL(config, NULL);
     2021
     2022  PXOPT_LOOKUP_S64(det_id, config->args, "-det_id", true,  false);
     2023  PXOPT_LOOKUP_STR(outfile, config->args, "-outfile", true,  false);
     2024  PXOPT_LOOKUP_U64(limit,   config->args, "-limit",   false, false);
     2025
     2026  FILE *f = fopen (outfile, "w");
     2027  if (f == NULL) {
     2028    psError(PS_ERR_UNKNOWN, false, "failed to open output file");
     2029    return false;
     2030  }
     2031
     2032  psMetadata *where = psMetadataAlloc();
     2033  PXOPT_COPY_S64(config->args, where, "-det_id", "det_id", "==");
     2034
     2035  ExportTable tables [] = {
     2036    {"detInputExp", "dettool_export_input_exp.sql"},
     2037    {"detNormalizedExp", "dettool_export_normalized_exp.sql"},
     2038    {"detNormalizedImfile", "dettool_export_normalized_imfile.sql"},
     2039    {"detNormalizedStatImfile", "dettool_export_normalized_stat_imfile.sql"},
     2040    {"detProcessedExp", "dettool_export_processed_exp.sql"},
     2041    {"detProcessedImfile", "dettool_export_processed_imfile.sql"},
     2042    {"detRegisteredImfile", "dettool_export_registered_imfile.sql"},
     2043    {"detResidExp", "dettool_export_resid_exp.sql"},
     2044    {"detResidImfile", "dettool_export_resid_imfile.sql"},
     2045    {"detRun", "dettool_export_run.sql"},
     2046    {"detRunSummary", "dettool_export_run_summary.sql"},
     2047    {"detStackedImfile", "dettool_export_stacked_imfile.sql"},
     2048  };
     2049
     2050  for (int i=0; i < numExportTables; i++) {
     2051    psString query = pxDataGet(tables[i].sqlFilename);
     2052    if (!query) {
     2053      psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
     2054      return false;
     2055    }
     2056
     2057    if (where && psListLength(where->list)) {
     2058      psString whereClause = psDBGenerateWhereSQL(where, NULL);
     2059      psStringAppend(&query, " %s", whereClause);
     2060      psFree(whereClause);
     2061    }
     2062
     2063    // treat limit == 0 as "no limit"
     2064    if (limit) {
     2065      psString limitString = psDBGenerateLimitSQL(limit);
     2066      psStringAppend(&query, " %s", limitString);
     2067      psFree(limitString);
     2068    }
     2069
     2070    if (!p_psDBRunQuery(config->dbh, query)) {
     2071      psError(PS_ERR_UNKNOWN, false, "database error");
     2072      psFree(query);
     2073      return false;
     2074    }
     2075    psFree(query);
     2076
     2077    psArray *output = p_psDBFetchResult(config->dbh);
     2078    if (!output) {
     2079      psError(PS_ERR_UNKNOWN, false, "database error");
     2080      return false;
     2081    }
     2082    if (!psArrayLength(output)) {
     2083      psTrace("chiptool", PS_LOG_INFO, "no rows found");
     2084      psFree(output);
     2085      return true;
     2086    }
     2087
     2088    // we must write the export table in non-simple (true) format
     2089    if (!ippdbPrintMetadatas(f, output, tables[i].tableName, true)) {
     2090      psError(PS_ERR_UNKNOWN, false, "failed to print array");
     2091      psFree(output);
     2092      return false;
     2093    }
     2094    psFree(output);
     2095 
     2096  }
     2097
     2098  fclose (f);
     2099
     2100  return true;
     2101}
     2102
     2103bool importrunMode(pxConfig *config)
     2104{
     2105  unsigned int nFail;
     2106 
     2107  int numImportTables = 11;
     2108 
     2109  char tables[11] [80] = {"detInputExp", "detNormalizedExp",
     2110    "detNormalizedStatImfile", "detProcessedExp", "detProcessedImfile",
     2111    "detRegisteredImfile", "detResidExp", "detResidImfile",
     2112    "detNormalizedImfile", "detRunSummary", "detStackedImfile"};
     2113
     2114  PS_ASSERT_PTR_NON_NULL(config, NULL);
     2115 
     2116  PXOPT_LOOKUP_STR(infile, config->args, "-infile", true,  false);
     2117
     2118  psMetadata *input = psMetadataConfigRead (NULL, &nFail, infile, false);
     2119
     2120  fprintf (stdout, "---- input ----\n");
     2121  psMetadataPrint (stderr, input, 1);
     2122 
     2123  psMetadataItem *item = psMetadataLookup (input, "detRun");
     2124  psAssert (item, "entry not in input?");
     2125  psAssert (item->type == PS_DATA_METADATA_MULTI, "entry not multi?");
     2126
     2127  psMetadataItem *entry = psListGet (item->data.list, 0);
     2128  assert (entry);
     2129  assert (entry->type == PS_DATA_METADATA);
     2130  detRunRow *detRun = detRunObjectFromMetadata (entry->data.md);
     2131  detRunInsertObject (config->dbh, detRun);
     2132 
     2133  // fprintf (stdout, "---- det run ----\n");
     2134  // psMetadataPrint (stderr, entry->data.md, 1);
     2135
     2136  for (int i = 0; i < numImportTables; i++) {
     2137    item = psMetadataLookup (input, tables[i]);
     2138    psAssert (item, "entry not in input?");
     2139    psAssert (item->type == PS_DATA_METADATA_MULTI, "entry not multi?");
     2140 
     2141    switch (i) {
     2142      case 0:
     2143        for (int i = 0; i < item->data.list->n; i++) {
     2144          entry = psListGet (item->data.list, i);
     2145          assert (entry);
     2146          assert (entry->type == PS_DATA_METADATA);
     2147          detInputExpRow *detInputExp = detInputExpObjectFromMetadata (entry->data.md);
     2148          detInputExpInsertObject (config->dbh, detInputExp);
     2149
     2150          // fprintf (stdout, "---- row %d ----\n", i);
     2151          // psMetadataPrint (stderr, entry->data.md, 1);
     2152        }
     2153        break;
     2154 
     2155      case 1:
     2156        for (int i = 0; i < item->data.list->n; i++) {
     2157          entry = psListGet (item->data.list, i);
     2158          assert (entry);
     2159          assert (entry->type == PS_DATA_METADATA);
     2160          detNormalizedExpRow *detNormalizedExp = detNormalizedExpObjectFromMetadata (entry->data.md);
     2161          detNormalizedExpInsertObject (config->dbh, detNormalizedExp);
     2162
     2163          // fprintf (stdout, "---- row %d ----\n", i);
     2164          // psMetadataPrint (stderr, entry->data.md, 1);
     2165        }
     2166        break;
     2167       
     2168      case 2:
     2169        for (int i = 0; i < item->data.list->n; i++) {
     2170          entry = psListGet (item->data.list, i);
     2171          assert (entry);
     2172          assert (entry->type == PS_DATA_METADATA);
     2173          detNormalizedStatImfileRow *detNormalizedStatImfile = detNormalizedStatImfileObjectFromMetadata (entry->data.md);
     2174          detNormalizedStatImfileInsertObject (config->dbh, detNormalizedStatImfile);
     2175
     2176          // fprintf (stdout, "---- row %d ----\n", i);
     2177          // psMetadataPrint (stderr, entry->data.md, 1);
     2178        }
     2179        break;
     2180 
     2181      case 3:
     2182        for (int i = 0; i < item->data.list->n; i++) {
     2183          entry = psListGet (item->data.list, i);
     2184          assert (entry);
     2185          assert (entry->type == PS_DATA_METADATA);
     2186          detProcessedExpRow *detProcessedExp =  detProcessedExpObjectFromMetadata (entry->data.md);
     2187          detProcessedExpInsertObject (config->dbh, detProcessedExp);
     2188
     2189          // fprintf (stdout, "---- row %d ----\n", i);
     2190          // psMetadataPrint (stderr, entry->data.md, 1);
     2191        }
     2192        break;
     2193       
     2194      case 4:
     2195        for (int i = 0; i < item->data.list->n; i++) {
     2196          entry = psListGet (item->data.list, i);
     2197          assert (entry);
     2198          assert (entry->type == PS_DATA_METADATA);
     2199          detProcessedImfileRow *detProcessedImfile =  detProcessedImfileObjectFromMetadata (entry->data.md);
     2200          detProcessedImfileInsertObject (config->dbh, detProcessedImfile);
     2201
     2202          // fprintf (stdout, "---- row %d ----\n", i);
     2203          // psMetadataPrint (stderr, entry->data.md, 1);
     2204        }
     2205        break;
     2206       
     2207      case 5:
     2208        for (int i = 0; i < item->data.list->n; i++) {
     2209          entry = psListGet (item->data.list, i);
     2210          assert (entry);
     2211          assert (entry->type == PS_DATA_METADATA);
     2212          detRegisteredImfileRow *detRegisteredImfile = detRegisteredImfileObjectFromMetadata (entry->data.md);
     2213          detRegisteredImfileInsertObject (config->dbh, detRegisteredImfile);
     2214
     2215          // fprintf (stdout, "---- row %d ----\n", i);
     2216          // psMetadataPrint (stderr, entry->data.md, 1);
     2217        }
     2218        break;
     2219       
     2220      case 6:
     2221        for (int i = 0; i < item->data.list->n; i++) {
     2222          entry = psListGet (item->data.list, i);
     2223          assert (entry);
     2224          assert (entry->type == PS_DATA_METADATA);
     2225          detResidExpRow *detResidExp = detResidExpObjectFromMetadata (entry->data.md);
     2226          detResidExpInsertObject (config->dbh, detResidExp);
     2227
     2228          // fprintf (stdout, "---- row %d ----\n", i);
     2229          // psMetadataPrint (stderr, entry->data.md, 1);
     2230        }
     2231        break;
     2232       
     2233      case 7:
     2234        for (int i = 0; i < item->data.list->n; i++) {
     2235          entry = psListGet (item->data.list, i);
     2236          assert (entry);
     2237          assert (entry->type == PS_DATA_METADATA);
     2238          detResidImfileRow *detResidImfile = detResidImfileObjectFromMetadata (entry->data.md);
     2239          detResidImfileInsertObject (config->dbh, detResidImfile);
     2240
     2241          // fprintf (stdout, "---- row %d ----\n", i);
     2242          // psMetadataPrint (stderr, entry->data.md, 1);
     2243        }
     2244        break;
     2245       
     2246      case 8:
     2247        for (int i = 0; i < item->data.list->n; i++) {
     2248          entry = psListGet (item->data.list, i);
     2249          assert (entry);
     2250          assert (entry->type == PS_DATA_METADATA);
     2251          detNormalizedImfileRow *detNormalizedImfile = detNormalizedImfileObjectFromMetadata (entry->data.md);
     2252          detNormalizedImfileInsertObject (config->dbh, detNormalizedImfile);
     2253
     2254          // fprintf (stdout, "---- row %d ----\n", i);
     2255          // psMetadataPrint (stderr, entry->data.md, 1);
     2256        }
     2257        break;
     2258       
     2259      case 9:
     2260        for (int i = 0; i < item->data.list->n; i++) {
     2261          entry = psListGet (item->data.list, i);
     2262          assert (entry);
     2263          assert (entry->type == PS_DATA_METADATA);
     2264          detRunSummaryRow *detRunSummary = detRunSummaryObjectFromMetadata (entry->data.md);
     2265          detRunSummaryInsertObject (config->dbh, detRunSummary);
     2266
     2267          // fprintf (stdout, "---- row %d ----\n", i);
     2268          // psMetadataPrint (stderr, entry->data.md, 1);
     2269        }
     2270        break;
     2271       
     2272      case 10:
     2273        for (int i = 0; i < item->data.list->n; i++) {
     2274          entry = psListGet (item->data.list, i);
     2275          assert (entry);
     2276          assert (entry->type == PS_DATA_METADATA);
     2277          detStackedImfileRow *detStackedImfile = detStackedImfileObjectFromMetadata (entry->data.md);
     2278          detStackedImfileInsertObject (config->dbh, detStackedImfile);
     2279
     2280          // fprintf (stdout, "---- row %d ----\n", i);
     2281          // psMetadataPrint (stderr, entry->data.md, 1);
     2282        }
     2283        break;
     2284    }
     2285  }
     2286
     2287  return true;
     2288}
     2289
    19982290#if 0
    19992291// XXX this function was left in commented as this method may be useful in the
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/dettool.h

    r19814 r23352  
    114114    DETTOOL_MODE_RERUN,
    115115    DETTOOL_MODE_REGISTER_DETREND,
    116     DETTOOL_MODE_REGISTER_DETREND_IMFILE
     116    DETTOOL_MODE_REGISTER_DETREND_IMFILE,
     117
     118    DETTOOL_MODE_EXPORTRUN,
     119    DETTOOL_MODE_IMPORTRUN
    117120} dettoolMode;
    118121
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/dettoolConfig.c

    r20375 r23352  
    648648    psMetadataAddBool(residimfileArgs, PS_LIST_TAIL, "-faulted",  0,            "only return imfiles with a fault status set", false);
    649649    psMetadataAddBool(residimfileArgs, PS_LIST_TAIL, "-simple",  0,            "use the simple output format", false);
     650    psMetadataAddBool(residimfileArgs, PS_LIST_TAIL, "-included",  0,            "use only files included in ths detrun", false);
     651    // XXX is this option used?
    650652    psMetadataAddStr(residimfileArgs, PS_LIST_TAIL, "-select_state",  0,            "search for state", NULL);
    651653
     
    855857    psMetadataAddStr(register_detrend_imfileArgs, PS_LIST_TAIL, "-path_base",  0,            "define base output location", NULL);
    856858
     859    // -exportrun
     860    psMetadata *exportrunArgs = psMetadataAlloc();
     861    psMetadataAddS64(exportrunArgs, PS_LIST_TAIL, "-det_id", 0,          "export this detrend ID (required)", 0);
     862    psMetadataAddStr(exportrunArgs, PS_LIST_TAIL, "-outfile", 0,          "export to this file (required)", NULL);
     863    psMetadataAddU64(exportrunArgs, PS_LIST_TAIL, "-limit",   0,          "limit result set to N items", 0);
     864
     865    // -importrun
     866    psMetadata *importrunArgs = psMetadataAlloc();
     867    psMetadataAddStr(importrunArgs, PS_LIST_TAIL, "-infile",  0,          "import from this file (required)", NULL);
     868
     869
    857870    psFree(now);
    858871
     
    947960    PXOPT_ADD_MODE("-register_detrend", "", DETTOOL_MODE_REGISTER_DETREND, register_detrendArgs);
    948961    PXOPT_ADD_MODE("-register_detrend_imfile", "", DETTOOL_MODE_REGISTER_DETREND_IMFILE, register_detrend_imfileArgs);
     962    PXOPT_ADD_MODE("-exportrun",            "export run for import on other database", DETTOOL_MODE_EXPORTRUN, exportrunArgs);
     963    PXOPT_ADD_MODE("-importrun",            "import run from metadata file",           DETTOOL_MODE_IMPORTRUN, importrunArgs);
    949964
    950965    if (!pxGetOptions(stderr, argc, argv, config, modes, argSets)) {
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/dettool_processedimfile.c

    r19621 r23352  
    165165    PS_ASSERT_PTR_NON_NULL(config, false);
    166166
    167     bool hasWhere = false;
    168 
    169     PXOPT_LOOKUP_BOOL(included, config->args, "-included", false);
    170     PXOPT_LOOKUP_BOOL(faulted, config->args, "-faulted", false);
    171     PXOPT_LOOKUP_U64(limit, config->args, "-limit", false, false);
    172     PXOPT_LOOKUP_BOOL(simple, config->args, "-simple", false);
    173 
    174167    psMetadata *where = psMetadataAlloc();
    175168    PXOPT_COPY_S64(config->args, where, "-det_id", "detProcessedImfile.det_id", "==");
     
    179172    PXOPT_COPY_STR(config->args, where, "-select_mode", "detRun.mode", "==");
    180173
     174    PXOPT_LOOKUP_U64(limit, config->args, "-limit", false, false);
     175    PXOPT_LOOKUP_BOOL(simple, config->args, "-simple", false);
     176
     177    PXOPT_LOOKUP_BOOL(faulted, config->args, "-faulted", false);
     178    PXOPT_LOOKUP_BOOL(included, config->args, "-included", false);
     179
    181180    psString query = pxDataGet("dettool_processedimfile.sql");
    182181    if (!query) {
     
    186185    }
    187186
     187    bool hasWhere = false;
    188188    if (psListLength(where->list)) {
    189189        psString whereClause = psDBGenerateWhereSQL(where, NULL);
     
    211211
    212212    if (faulted) {
     213        // list only faulted rows
    213214        psStringAppend(&query, " %s", " detProcessedImfile.fault != 0");
    214215    } else {
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/dettool_residimfile.c

    r19632 r23352  
    159159    PXOPT_LOOKUP_U64(limit, config->args, "-limit", false, false);
    160160    PXOPT_LOOKUP_BOOL(simple, config->args, "-simple", false);
     161
    161162    PXOPT_LOOKUP_BOOL(faulted, config->args, "-faulted", false);
     163    PXOPT_LOOKUP_BOOL(included, config->args, "-included", false);
    162164
    163165    psString query = pxDataGet("dettool_residimfile.sql");
     
    175177    }
    176178    psFree(where);
     179
     180    // restrict search to included imfiles
     181    if (included) {
     182        if (hasWhere) {
     183            psStringAppend(&query, " AND detInputExp.include = 1");
     184        } else {
     185            psStringAppend(&query, " WHERE detInputExp.include = 1");
     186        }
     187        hasWhere = true;
     188    }
    177189
    178190    if (hasWhere) {
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/difftool.c

    r21402 r23352  
    4545static bool donecleanupMode(pxConfig *config);
    4646static bool updatediffskyfileMode(pxConfig *config);
     47static bool exportrunMode(pxConfig *config);
     48static bool importrunMode(pxConfig *config);
    4749
    4850static bool setdiffRunState(pxConfig *config, psS64 diff_id, const char *state);
     
    8183        MODECASE(DIFFTOOL_MODE_DONECLEANUP,           donecleanupMode);
    8284        MODECASE(DIFFTOOL_MODE_UPDATEDIFFSKYFILE,     updatediffskyfileMode);
     85        MODECASE(DIFFTOOL_MODE_EXPORTRUN,             exportrunMode);
     86        MODECASE(DIFFTOOL_MODE_IMPORTRUN,             importrunMode);
    8387        default:
    8488            psAbort("invalid option (this should not happen)");
     
    14371441}
    14381442
     1443bool exportrunMode(pxConfig *config)
     1444{
     1445  typedef struct ExportTable {
     1446    char tableName[80];
     1447    char sqlFilename[80];
     1448  } ExportTable;
     1449 
     1450  int numExportFiles = 3;
     1451
     1452  PS_ASSERT_PTR_NON_NULL(config, NULL);
     1453
     1454  PXOPT_LOOKUP_S64(det_id, config->args, "-diff_id", true,  false);
     1455  PXOPT_LOOKUP_STR(outfile, config->args, "-outfile", true,  false);
     1456  PXOPT_LOOKUP_U64(limit,   config->args, "-limit",   false, false);
     1457
     1458  FILE *f = fopen (outfile, "w");
     1459  if (f == NULL) {
     1460    psError(PS_ERR_UNKNOWN, false, "failed to open output file");
     1461    return false;
     1462  }
     1463
     1464  psMetadata *where = psMetadataAlloc();
     1465  PXOPT_COPY_S64(config->args, where, "-diff_id", "diff_id", "==");
     1466
     1467  ExportTable tables [] = {
     1468    {"diffRun", "difftool_export_run.sql"},
     1469    {"diffInputSkyfile", "difftool_export_input_skyfile.sql"},
     1470    {"diffSkyfile", "difftool_export_skyfile.sql"},
     1471  };
     1472
     1473  for (int i=0; i < numExportFiles; i++) {
     1474    psString query = pxDataGet(tables[i].sqlFilename);
     1475    if (!query) {
     1476      psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
     1477      return false;
     1478    }
     1479
     1480    if (where && psListLength(where->list)) {
     1481      psString whereClause = psDBGenerateWhereSQL(where, NULL);
     1482      psStringAppend(&query, " %s", whereClause);
     1483      psFree(whereClause);
     1484    }
     1485
     1486    // treat limit == 0 as "no limit"
     1487    if (limit) {
     1488      psString limitString = psDBGenerateLimitSQL(limit);
     1489      psStringAppend(&query, " %s", limitString);
     1490      psFree(limitString);
     1491    }
     1492
     1493    if (!p_psDBRunQuery(config->dbh, query)) {
     1494      psError(PS_ERR_UNKNOWN, false, "database error");
     1495      psFree(query);
     1496      return false;
     1497    }
     1498    psFree(query);
     1499
     1500    psArray *output = p_psDBFetchResult(config->dbh);
     1501    if (!output) {
     1502      psError(PS_ERR_UNKNOWN, false, "database error");
     1503      return false;
     1504    }
     1505    if (!psArrayLength(output)) {
     1506      psTrace("regtool", PS_LOG_INFO, "no rows found");
     1507      psFree(output);
     1508      return true;
     1509    }
     1510
     1511    // we must write the export table in non-simple (true) format
     1512    if (!ippdbPrintMetadatas(f, output, tables[i].tableName, true)) {
     1513      psError(PS_ERR_UNKNOWN, false, "failed to print array");
     1514      psFree(output);
     1515      return false;
     1516    }
     1517    psFree(output);
     1518  }
     1519
     1520  fclose (f);
     1521
     1522  return true;
     1523}
     1524
     1525bool importrunMode(pxConfig *config)
     1526{
     1527  unsigned int nFail;
     1528 
     1529  int numImportTables = 2;
     1530 
     1531  char tables[2] [80] = {"diffInputSkyfile", "diffSkyfile"};
     1532
     1533  PS_ASSERT_PTR_NON_NULL(config, NULL);
     1534 
     1535  PXOPT_LOOKUP_STR(infile, config->args, "-infile", true,  false);
     1536
     1537  psMetadata *input = psMetadataConfigRead (NULL, &nFail, infile, false);
     1538
     1539  fprintf (stdout, "---- input ----\n");
     1540  psMetadataPrint (stderr, input, 1);
     1541
     1542  psMetadataItem *item = psMetadataLookup (input, "diffRun");
     1543  psAssert (item, "entry not in input?");
     1544  psAssert (item->type == PS_DATA_METADATA_MULTI, "entry not multi?");
     1545
     1546  psMetadataItem *entry = psListGet (item->data.list, 0);
     1547  assert (entry);
     1548  assert (entry->type == PS_DATA_METADATA);
     1549  diffRunRow *diffRun = diffRunObjectFromMetadata (entry->data.md);
     1550  diffRunInsertObject (config->dbh, diffRun);
     1551
     1552  // fprintf (stdout, "---- diff run ----\n");
     1553  // psMetadataPrint (stderr, entry->data.md, 1);
     1554
     1555  for (int i = 0; i < numImportTables; i++) {
     1556    item = psMetadataLookup (input, tables[i]);
     1557    psAssert (item, "entry not in input?");
     1558    psAssert (item->type == PS_DATA_METADATA_MULTI, "entry not multi?");
     1559 
     1560    switch (i) {
     1561      case 0:
     1562        for (int i = 0; i < item->data.list->n; i++) {
     1563          entry = psListGet (item->data.list, i);
     1564          assert (entry);
     1565          assert (entry->type == PS_DATA_METADATA);
     1566          diffInputSkyfileRow *diffInputSkyfile = diffInputSkyfileObjectFromMetadata (entry->data.md);
     1567          diffInputSkyfileInsertObject (config->dbh, diffInputSkyfile);
     1568
     1569          // fprintf (stdout, "---- row %d ----\n", i);
     1570          // psMetadataPrint (stderr, entry->data.md, 1);
     1571        }
     1572        break;
     1573       
     1574      case 1:
     1575        for (int i = 0; i < item->data.list->n; i++) {
     1576          entry = psListGet (item->data.list, i);
     1577          assert (entry);
     1578          assert (entry->type == PS_DATA_METADATA);
     1579          diffSkyfileRow *diffSkyfile = diffSkyfileObjectFromMetadata (entry->data.md);
     1580          diffSkyfileInsertObject (config->dbh, diffSkyfile);
     1581
     1582          // fprintf (stdout, "---- row %d ----\n", i);
     1583          // psMetadataPrint (stderr, entry->data.md, 1);
     1584        }
     1585        break;
     1586    }
     1587  }
     1588
     1589  return true;
     1590}
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/difftool.h

    r19677 r23352  
    3939    DIFFTOOL_MODE_DONECLEANUP,
    4040    DIFFTOOL_MODE_UPDATEDIFFSKYFILE,
     41    DIFFTOOL_MODE_EXPORTRUN,
     42    DIFFTOOL_MODE_IMPORTRUN
    4143} difftoolMode;
    4244
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/difftoolConfig.c

    r21308 r23352  
    187187    psMetadataAddS16(updatediffskyfileArgs, PS_LIST_TAIL, "-code", 0,         "set fault code (required)", 0);
    188188
     189    // -exportrun
     190    psMetadata *exportrunArgs = psMetadataAlloc();
     191    psMetadataAddS64(exportrunArgs, PS_LIST_TAIL, "-diff_id", 0,          "export this diff ID (required)", 0);
     192    psMetadataAddStr(exportrunArgs, PS_LIST_TAIL, "-outfile", 0,          "export to this file (required)", NULL);
     193    psMetadataAddU64(exportrunArgs, PS_LIST_TAIL, "-limit",   0,          "limit result set to N items", 0);
     194
     195    // -importrun
     196    psMetadata *importrunArgs = psMetadataAlloc();
     197    psMetadataAddStr(importrunArgs, PS_LIST_TAIL, "-infile",  0,          "import from this file (required)", NULL);
     198
     199
    189200
    190201    psFree(now);
     
    207218    PXOPT_ADD_MODE("-donecleanup",           "show runs that have been cleaned",     DIFFTOOL_MODE_DONECLEANUP,          donecleanupArgs);
    208219    PXOPT_ADD_MODE("-updatediffskyfile",     "update fault code for a diffskyfile",  DIFFTOOL_MODE_UPDATEDIFFSKYFILE,          updatediffskyfileArgs);
     220    PXOPT_ADD_MODE("-exportrun",            "export run for import on other database", DIFFTOOL_MODE_EXPORTRUN, exportrunArgs);
     221    PXOPT_ADD_MODE("-importrun",            "import run from metadata file",           DIFFTOOL_MODE_IMPORTRUN, importrunArgs);
    209222
    210223    if (!pxGetOptions(stderr, argc, argv, config, modes, argSets)) {
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/faketool.c

    r21463 r23352  
    4141static bool revertprocessedimfileMode(pxConfig *config);
    4242static bool updateprocessedimfileMode(pxConfig *config);
    43 static bool promoteexpMode(pxConfig *config);
     43static bool advanceexpMode(pxConfig *config);
    4444static bool blockMode(pxConfig *config);
    4545static bool maskedMode(pxConfig *config);
     
    5252static bool tofullimfileMode(pxConfig *config);
    5353static bool topurgedimfileMode(pxConfig *config);
     54static bool exportrunMode(pxConfig *config);
     55static bool importrunMode(pxConfig *config);
    5456
    5557# define MODECASE(caseName, func) \
     
    7880        MODECASE(FAKETOOL_MODE_REVERTPROCESSEDIMFILE,   revertprocessedimfileMode);
    7981        MODECASE(FAKETOOL_MODE_UPDATEPROCESSEDIMFILE,   updateprocessedimfileMode);
    80         MODECASE(FAKETOOL_MODE_PROMOTEEXP,              promoteexpMode);
     82        MODECASE(FAKETOOL_MODE_ADVANCEEXP,              advanceexpMode);
    8183        MODECASE(FAKETOOL_MODE_BLOCK,                   blockMode);
    8284        MODECASE(FAKETOOL_MODE_MASKED,                  maskedMode);
     
    8991        MODECASE(FAKETOOL_MODE_TOFULLIMFILE,            tofullimfileMode);
    9092        MODECASE(FAKETOOL_MODE_TOPURGEDIMFILE,          topurgedimfileMode);
     93        MODECASE(FAKETOOL_MODE_EXPORTRUN,               exportrunMode);
     94        MODECASE(FAKETOOL_MODE_IMPORTRUN,               importrunMode);
    9195
    9296        default:
     
    10481052}
    10491053
    1050 static bool promoteexpMode(pxConfig *config)
     1054static bool advanceexpMode(pxConfig *config)
    10511055{
    10521056    PS_ASSERT_PTR_NON_NULL(config, false);
     
    12251229    return change_imfile_data_state(config, "purged", "goto_purged");
    12261230}
     1231
     1232bool exportrunMode(pxConfig *config)
     1233{
     1234  typedef struct ExportTable {
     1235    char tableName[80];
     1236    char sqlFilename[80];
     1237  } ExportTable;
     1238
     1239  int numExportTables = 2;
     1240 
     1241  PS_ASSERT_PTR_NON_NULL(config, NULL);
     1242
     1243  PXOPT_LOOKUP_S64(det_id, config->args, "-fake_id", true,  false);
     1244  PXOPT_LOOKUP_STR(outfile, config->args, "-outfile", true,  false);
     1245  PXOPT_LOOKUP_U64(limit,   config->args, "-limit",   false, false);
     1246
     1247  FILE *f = fopen (outfile, "w");
     1248  if (f == NULL) {
     1249    psError(PS_ERR_UNKNOWN, false, "failed to open output file");
     1250    return false;
     1251  }
     1252
     1253  psMetadata *where = psMetadataAlloc();
     1254  PXOPT_COPY_S64(config->args, where, "-fake_id", "fake_id", "==");
     1255
     1256  ExportTable tables [] = {
     1257    {"fakeRun", "faketool_export_run.sql"},
     1258    {"fakeProcessedImfile", "faketool_export_processed_imfile.sql"},
     1259  };
     1260
     1261  for (int i=0; i < numExportTables; i++) {
     1262    psString query = pxDataGet(tables[i].sqlFilename);
     1263    if (!query) {
     1264      psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
     1265      return false;
     1266    }
     1267
     1268    if (where && psListLength(where->list)) {
     1269      psString whereClause = psDBGenerateWhereSQL(where, NULL);
     1270      psStringAppend(&query, " %s", whereClause);
     1271      psFree(whereClause);
     1272    }
     1273
     1274    // treat limit == 0 as "no limit"
     1275    if (limit) {
     1276      psString limitString = psDBGenerateLimitSQL(limit);
     1277      psStringAppend(&query, " %s", limitString);
     1278      psFree(limitString);
     1279    }
     1280
     1281    if (!p_psDBRunQuery(config->dbh, query)) {
     1282      psError(PS_ERR_UNKNOWN, false, "database error");
     1283      psFree(query);
     1284      return false;
     1285    }
     1286    psFree(query);
     1287
     1288    psArray *output = p_psDBFetchResult(config->dbh);
     1289    if (!output) {
     1290      psError(PS_ERR_UNKNOWN, false, "database error");
     1291      return false;
     1292    }
     1293    if (!psArrayLength(output)) {
     1294      psTrace("regtool", PS_LOG_INFO, "no rows found");
     1295      psFree(output);
     1296      return true;
     1297    }
     1298
     1299    // we must write the export table in non-simple (true) format
     1300    if (!ippdbPrintMetadatas(f, output, tables[i].tableName, true)) {
     1301      psError(PS_ERR_UNKNOWN, false, "failed to print array");
     1302      psFree(output);
     1303      return false;
     1304    }
     1305    psFree(output);
     1306  }
     1307
     1308    fclose (f);
     1309
     1310    return true;
     1311}
     1312
     1313bool importrunMode(pxConfig *config)
     1314{
     1315  unsigned int nFail;
     1316
     1317  PS_ASSERT_PTR_NON_NULL(config, NULL);
     1318 
     1319  PXOPT_LOOKUP_STR(infile, config->args, "-infile", true,  false);
     1320
     1321  psMetadata *input = psMetadataConfigRead (NULL, &nFail, infile, false);
     1322
     1323  fprintf (stdout, "---- input ----\n");
     1324  psMetadataPrint (stderr, input, 1);
     1325
     1326  psMetadataItem *item = psMetadataLookup (input, "fakeRun");
     1327  psAssert (item, "entry not in input?");
     1328  psAssert (item->type == PS_DATA_METADATA_MULTI, "entry not multi?");
     1329
     1330  psMetadataItem *entry = psListGet (item->data.list, 0);
     1331  assert (entry);
     1332  assert (entry->type == PS_DATA_METADATA);
     1333  fakeRunRow *fakeRun = fakeRunObjectFromMetadata (entry->data.md);
     1334  fakeRunInsertObject (config->dbh, fakeRun);
     1335
     1336  // fprintf (stdout, "---- fake run ----\n");
     1337  // psMetadataPrint (stderr, entry->data.md, 1);
     1338
     1339  item = psMetadataLookup (input, "fakeProcessedImfile");
     1340  psAssert (item, "entry not in input?");
     1341  psAssert (item->type == PS_DATA_METADATA_MULTI, "entry not multi?");
     1342
     1343  for (int i = 0; i < item->data.list->n; i++) {
     1344    psMetadataItem *entry = psListGet (item->data.list, i);
     1345    assert (entry);
     1346    assert (entry->type == PS_DATA_METADATA);
     1347    fakeProcessedImfileRow *fakeProcessedImfile = fakeProcessedImfileObjectFromMetadata (entry->data.md);
     1348    fakeProcessedImfileInsertObject (config->dbh, fakeProcessedImfile);
     1349
     1350    // fprintf (stdout, "---- row %d ----\n", i);
     1351    // psMetadataPrint (stderr, entry->data.md, 1);
     1352  }
     1353
     1354  return true;
     1355}
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/faketool.h

    r21463 r23352  
    3333    FAKETOOL_MODE_REVERTPROCESSEDIMFILE,
    3434    FAKETOOL_MODE_UPDATEPROCESSEDIMFILE,
    35     FAKETOOL_MODE_PROMOTEEXP,
     35    FAKETOOL_MODE_ADVANCEEXP,
    3636    FAKETOOL_MODE_BLOCK,
    3737    FAKETOOL_MODE_MASKED,
     
    4545    FAKETOOL_MODE_TOFULLIMFILE,
    4646    FAKETOOL_MODE_TOPURGEDIMFILE,
     47    FAKETOOL_MODE_EXPORTRUN,
     48    FAKETOOL_MODE_IMPORTRUN
    4749} FAKETOOLMode;
    4850
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/faketoolConfig.c

    r21463 r23352  
    242242
    243243
    244     // -promoteexp
    245     psMetadata *promoteexpArgs = psMetadataAlloc();
    246     psMetadataAddS64(promoteexpArgs, PS_LIST_TAIL, "-fake_id", 0,      "search by fake ID", 0);
    247     psMetadataAddStr(promoteexpArgs, PS_LIST_TAIL, "-label",  0,       "search by label ", NULL);
    248     psMetadataAddU64(promoteexpArgs, PS_LIST_TAIL, "-limit",  0,       "limit exposures to promote to N items", 0);
     244    // -advanceexp
     245    psMetadata *advanceexpArgs = psMetadataAlloc();
     246    psMetadataAddS64(advanceexpArgs, PS_LIST_TAIL, "-fake_id", 0,      "search by fake ID", 0);
     247    psMetadataAddStr(advanceexpArgs, PS_LIST_TAIL, "-label",  0,       "search by label ", NULL);
     248    psMetadataAddU64(advanceexpArgs, PS_LIST_TAIL, "-limit",  0,       "limit exposures to advance to N items", 0);
    249249
    250250    // -block
     
    301301    psMetadataAddStr(topurgedimfileArgs, PS_LIST_TAIL, "-class_id",  0,        "class ID to update", NULL);
    302302
     303    // -exportrun
     304    psMetadata *exportrunArgs = psMetadataAlloc();
     305    psMetadataAddS64(exportrunArgs, PS_LIST_TAIL, "-fake_id", 0,          "export this fake ID (required)", 0);
     306    psMetadataAddStr(exportrunArgs, PS_LIST_TAIL, "-outfile", 0,          "export to this file (required)", NULL);
     307    psMetadataAddU64(exportrunArgs, PS_LIST_TAIL, "-limit",   0,          "limit result set to N items", 0);
     308
     309    // -importrun
     310    psMetadata *importrunArgs = psMetadataAlloc();
     311    psMetadataAddStr(importrunArgs, PS_LIST_TAIL, "-infile",  0,          "import from this file (required)", NULL);
     312
     313
    303314
    304315
     
    314325    PXOPT_ADD_MODE("-updateprocessedimfile","change procesed imfile properties",     FAKETOOL_MODE_UPDATEPROCESSEDIMFILE,    updateprocessedimfileArgs);
    315326    PXOPT_ADD_MODE("-revertprocessedimfile", "undo a processed imfile",              FAKETOOL_MODE_REVERTPROCESSEDIMFILE,    revertprocessedimfileArgs);
    316     PXOPT_ADD_MODE("-promoteexp",            "promote completed exposoures",         FAKETOOL_MODE_PROMOTEEXP,          promoteexpArgs);
     327    PXOPT_ADD_MODE("-advanceexp",            "advance completed exposoures",         FAKETOOL_MODE_ADVANCEEXP,          advanceexpArgs);
    317328    PXOPT_ADD_MODE("-block",                 "set a label block",                    FAKETOOL_MODE_BLOCK,          blockArgs);
    318329    PXOPT_ADD_MODE("-masked",                "show blocked labels",                  FAKETOOL_MODE_MASKED,         maskedArgs);
     
    325336    PXOPT_ADD_MODE("-tofullimfile",        "set imfile state to full",               FAKETOOL_MODE_TOFULLIMFILE,         tofullimfileArgs);
    326337    PXOPT_ADD_MODE("-topurgedimfile",      "set imfile state to purged",             FAKETOOL_MODE_TOPURGEDIMFILE,       topurgedimfileArgs);
     338    PXOPT_ADD_MODE("-exportrun",            "export run for import on other database", FAKETOOL_MODE_EXPORTRUN, exportrunArgs);
     339    PXOPT_ADD_MODE("-importrun",            "import run from metadata file",           FAKETOOL_MODE_IMPORTRUN, importrunArgs);
    327340
    328341
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/flatcorr.c

    r21402 r23352  
    4646static bool inputexpMode(pxConfig *config);
    4747static bool inputimfileMode(pxConfig *config);
     48static bool exportrunMode(pxConfig *config);
     49static bool importrunMode(pxConfig *config);
    4850
    4951static bool setflatcorrRunState(pxConfig *config, psS64 corr_id, const char *state);
     
    7880        MODECASE(FLATCORR_MODE_INPUTEXP,       inputexpMode);
    7981        MODECASE(FLATCORR_MODE_INPUTIMFILE,    inputimfileMode);
     82        MODECASE(FLATCORR_MODE_EXPORTRUN,      exportrunMode);
     83        MODECASE(FLATCORR_MODE_IMPORTRUN,      importrunMode);
    8084        default:
    8185            psAbort("invalid option (this should not happen)");
     
    734738    return true;
    735739}
     740
     741bool exportrunMode(pxConfig *config)
     742{
     743  typedef struct ExportTable {
     744    char tableName[80];
     745    char sqlFilename[80];
     746  } ExportTable;
     747 
     748  int numExportTables = 3;
     749
     750  PS_ASSERT_PTR_NON_NULL(config, NULL);
     751
     752  PXOPT_LOOKUP_S64(det_id, config->args, "-corr_id", true,  false);
     753  PXOPT_LOOKUP_STR(outfile, config->args, "-outfile", true,  false);
     754  PXOPT_LOOKUP_U64(limit,   config->args, "-limit",   false, false);
     755
     756  FILE *f = fopen (outfile, "w");
     757  if (f == NULL) {
     758    psError(PS_ERR_UNKNOWN, false, "failed to open output file");
     759    return false;
     760  }
     761
     762  psMetadata *where = psMetadataAlloc();
     763  PXOPT_COPY_S64(config->args, where, "-coor_id", "corr_id", "==");
     764
     765  ExportTable tables [] = {
     766    {"flatcorrRun", "flatcorrtool_export_run.sql"},
     767    {"flatcorrCamLink", "flatcorrtool_export_cam_link.sql"},
     768    {"flatcorrChipLink", "flatcorr_export_chip_link.sql"},
     769  };
     770
     771  for (int i=0; i < numExportTables; i++) {
     772    psString query = pxDataGet(tables[i].sqlFilename);
     773    if (!query) {
     774      psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
     775      return false;
     776    }
     777
     778    if (where && psListLength(where->list)) {
     779      psString whereClause = psDBGenerateWhereSQL(where, NULL);
     780      psStringAppend(&query, " %s", whereClause);
     781      psFree(whereClause);
     782    }
     783
     784    // treat limit == 0 as "no limit"
     785    if (limit) {
     786      psString limitString = psDBGenerateLimitSQL(limit);
     787      psStringAppend(&query, " %s", limitString);
     788      psFree(limitString);
     789    }
     790
     791    if (!p_psDBRunQuery(config->dbh, query)) {
     792      psError(PS_ERR_UNKNOWN, false, "database error");
     793      psFree(query);
     794      return false;
     795    }
     796    psFree(query);
     797
     798    psArray *output = p_psDBFetchResult(config->dbh);
     799    if (!output) {
     800      psError(PS_ERR_UNKNOWN, false, "database error");
     801      return false;
     802    }
     803    if (!psArrayLength(output)) {
     804      psTrace("regtool", PS_LOG_INFO, "no rows found");
     805      psFree(output);
     806      return true;
     807    }
     808
     809    // we must write the export table in non-simple (true) format
     810    if (!ippdbPrintMetadatas(f, output, tables[i].tableName, true)) {
     811      psError(PS_ERR_UNKNOWN, false, "failed to print array");
     812      psFree(output);
     813      return false;
     814    }
     815    psFree(output);
     816  }
     817
     818    fclose (f);
     819
     820    return true;
     821}
     822
     823bool importrunMode(pxConfig *config)
     824{
     825  unsigned int nFail;
     826  psMetadataItem *item, *entry;
     827 
     828  int numImportTables = 3;
     829 
     830  char tables[3] [80] = {"flatcorrRun", "flatcorrCamLink", "flatcorrChipLink"};
     831
     832  PS_ASSERT_PTR_NON_NULL(config, NULL);
     833 
     834  PXOPT_LOOKUP_STR(infile, config->args, "-infile", true,  false);
     835
     836  psMetadata *input = psMetadataConfigRead (NULL, &nFail, infile, false);
     837
     838  fprintf (stdout, "---- input ----\n");
     839  psMetadataPrint (stderr, input, 1);
     840
     841  for (int i = 0; i < numImportTables; i++) {
     842    item = psMetadataLookup (input, tables[i]);
     843    psAssert (item, "entry not in input?");
     844    psAssert (item->type == PS_DATA_METADATA_MULTI, "entry not multi?");
     845   
     846    entry = psListGet (item->data.list, 0);
     847    assert (entry);
     848    assert (entry->type == PS_DATA_METADATA);
     849 
     850    switch (i) {
     851      case 0:
     852      {
     853        flatcorrRunRow *flatcorrRun = flatcorrRunObjectFromMetadata (entry->data.md);
     854        flatcorrRunInsertObject (config->dbh, flatcorrRun);
     855
     856        // fprintf (stdout, "---- flatcorr run ----\n");
     857        // psMetadataPrint (stderr, entry->data.md, 1);
     858        break;
     859      }
     860      case 1:
     861      {
     862        flatcorrCamLinkRow *flatcorrCamLink = flatcorrCamLinkObjectFromMetadata (entry->data.md);
     863        flatcorrCamLinkInsertObject (config->dbh, flatcorrCamLink);
     864
     865        // fprintf (stdout, "---- flatcorr cam link ----\n");
     866        // psMetadataPrint (stderr, entry->data.md, 1);
     867        break;
     868      }
     869      case 2:
     870      {
     871        flatcorrChipLinkRow *flatcorrChipLink = flatcorrChipLinkObjectFromMetadata (entry->data.md);
     872        flatcorrChipLinkInsertObject (config->dbh, flatcorrChipLink);
     873
     874        // fprintf (stdout, "---- flatcorr chip link ----\n");
     875        // psMetadataPrint (stderr, entry->data.md, 1);
     876        break;
     877      }
     878    }
     879  }
     880  return true;
     881}
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/flatcorr.h

    r20397 r23352  
    3535    FLATCORR_MODE_UPDATERUN,
    3636    FLATCORR_MODE_INPUTEXP,
    37     FLATCORR_MODE_INPUTIMFILE
     37    FLATCORR_MODE_INPUTIMFILE,
     38    FLATCORR_MODE_EXPORTRUN,
     39    FLATCORR_MODE_IMPORTRUN
    3840} flatcorrMode;
    3941
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/flatcorrConfig.c

    r20397 r23352  
    125125    psMetadataAddU64(inputimfileArgs, PS_LIST_TAIL, "-limit",   0, "limit result set to N items", 0);
    126126
     127    // -exportrun
     128    psMetadata *exportrunArgs = psMetadataAlloc();
     129    psMetadataAddS64(exportrunArgs, PS_LIST_TAIL, "-corr_id", 0,          "export this correction ID (required)", 0);
     130    psMetadataAddStr(exportrunArgs, PS_LIST_TAIL, "-outfile", 0,          "export to this file (required)", NULL);
     131    psMetadataAddU64(exportrunArgs, PS_LIST_TAIL, "-limit",   0,          "limit result set to N items", 0);
     132
     133    // -importrun
     134    psMetadata *importrunArgs = psMetadataAlloc();
     135    psMetadataAddStr(importrunArgs, PS_LIST_TAIL, "-infile",  0,          "import from this file (required)", NULL);
     136
     137
    127138    psFree(now);
    128139
     
    141152    PXOPT_ADD_MODE("-inputexp",       "list exposures for a correction run",               FLATCORR_MODE_INPUTEXP,       inputexpArgs);
    142153    PXOPT_ADD_MODE("-inputimfile",    "list imfiles for a chip run",                       FLATCORR_MODE_INPUTIMFILE,    inputimfileArgs);
     154    PXOPT_ADD_MODE("-exportrun",            "export run for import on other database", FLATCORR_MODE_EXPORTRUN, exportrunArgs);
     155    PXOPT_ADD_MODE("-importrun",            "import run from metadata file",           FLATCORR_MODE_IMPORTRUN, importrunArgs);
    143156
    144157    if (!pxGetOptions(stderr, argc, argv, config, modes, argSets)) {
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/pxadmin.c

    r18927 r23352  
    2929
    3030bool createMode(pxConfig *config);
     31bool createMirrorMode(pxConfig *config);
    3132bool deleteMode(pxConfig *config);
    3233static bool runMultipleStatments(pxConfig *config, const char *query);
     
    5354            }
    5455            break;
     56        case PXADMIN_MODE_CREATE_MIRROR:
     57            if (!createMirrorMode(config)) {
     58                goto FAIL;
     59            }
     60            break;
    5561        case PXADMIN_MODE_DELETE:
    5662            if (!deleteMode(config)) {
     
    8692
    8793    psString query = pxDataGet("pxadmin_create_tables.sql");
     94    if (!query) {
     95        psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
     96        return false;
     97    }
     98
     99    // BEGIN
     100    if (!psDBTransaction(config->dbh)) {
     101        psError(PS_ERR_UNKNOWN, false, "database error");
     102        return false;
     103    }
     104
     105    if (!runMultipleStatments(config, query)) {
     106        if (!psDBRollback(config->dbh)) {
     107                psError(PS_ERR_UNKNOWN, false, "database error");
     108        }
     109        psError(PS_ERR_UNKNOWN, false, "database error");
     110        psFree(query);
     111        return false;
     112    }
     113    psFree(query);
     114
     115    // COMMIT
     116    if (!psDBCommit(config->dbh)) {
     117        psError(PS_ERR_UNKNOWN, false, "database error");
     118        return false;
     119    }
     120
     121    return true;
     122}
     123
     124
     125bool createMirrorMode(pxConfig *config)
     126{
     127    PS_ASSERT_PTR_NON_NULL(config, false);
     128
     129    psString query = pxDataGet("pxadmin_create_mirror_tables.sql");
    88130    if (!query) {
    89131        psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/pxadmin.h

    r9392 r23352  
    2626    PXADMIN_MODE_NONE      = 0x0,
    2727    PXADMIN_MODE_CREATE,
     28    PXADMIN_MODE_CREATE_MIRROR,
    2829    PXADMIN_MODE_DELETE,
    2930    PXADMIN_MODE_RECREATE
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/pxadminConfig.c

    r19062 r23352  
    3131    fprintf (stderr, "\nPan-STARRS DataBase Admin Tool\n\n");
    3232    fprintf (stderr, "Usage: %s [mode]\n", program);
    33     fprintf (stderr, " [mode] : -create | -delete\n\n");
     33    fprintf (stderr, " [mode] : -create | -create-mirror | -delete\n\n");
    3434
    3535    psMetadataItem *server = pmConfigUserSite(config->modules, "DBSERVER",   PS_DATA_STRING);
     
    8787        config->mode = PXADMIN_MODE_CREATE;
    8888    }
     89    if ((N = psArgumentGet(argc, argv, "-create-mirror"))) {
     90        psArgumentRemove(N, &argc, argv);
     91        if (config->mode) {
     92            psAbort("only one mode selection is allowed");
     93        }
     94        config->mode = PXADMIN_MODE_CREATE_MIRROR;
     95    }
    8996    if ((N = psArgumentGet(argc, argv, "-delete"))) {
    9097        psArgumentRemove(N, &argc, argv);
     
    105112    psMetadataAddStr(arguments, PS_LIST_TAIL, "-create", 0,
    106113            "create all IPP tables", "");
     114    psMetadataAddStr(arguments, PS_LIST_TAIL, "-create-mirror", 0,
     115            "mirror all IPP tables", "");
    107116    psMetadataAddStr(arguments, PS_LIST_TAIL, "-delete", 0,
    108117            "delete all IPP tables", "");
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/pxtools.c

    r20413 r23352  
    3030    PS_ASSERT_PTR_NON_NULL(state, false);
    3131   
    32     // XXX replace strncmp with strcmp
    33 
    3432    if (!strcmp(state, "new")) return true;
    3533    if (!strcmp(state, "reg")) return true;
     
    3836    if (!strcmp(state, "wait")) return true;
    3937    if (!strcmp(state, "goto_cleaned")) return true;
     38    if (!strcmp(state, "error_cleaned")) return true;
     39    if (!strcmp(state, "goto_scrubbed")) return true;
     40    if (!strcmp(state, "error_scrubbed")) return true;
    4041    if (!strcmp(state, "cleaned")) return true;
    4142    if (!strcmp(state, "update")) return true;
    4243    if (!strcmp(state, "purged")) return true;
    4344    if (!strcmp(state, "goto_purged")) return true;
     45    if (!strcmp(state, "error_purged")) return true;
    4446
    4547    return false;
    4648}
     49
     50// 'scrubbed' is a virtual state equivalent to cleaned, but allows files to be removed
     51// even if the config files is missing
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/pxwarp.c

    r21402 r23352  
    5858    // check that state is a valid string value
    5959    if (!pxIsValidState(state)) {
    60         psError(PS_ERR_UNKNOWN, false, "invalid chipRun state: %s", state);
     60        psError(PS_ERR_UNKNOWN, false, "invalid warpRun state: %s", state);
    6161        return false;
    6262    }
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/regtool.c

    r21402 r23352  
    4444static bool updateprocessedexpMode(pxConfig *config);
    4545static bool cleardupexpMode(pxConfig *config);
     46static bool exportrunMode(pxConfig *config);
     47static bool importrunMode(pxConfig *config);
    4648
    4749# define MODECASE(caseName, func) \
     
    7678        MODECASE(REGTOOL_MODE_UPDATEPROCESSEDEXP,    updateprocessedexpMode);
    7779        MODECASE(REGTOOL_MODE_CLEARDUPEXP,           cleardupexpMode);
     80        MODECASE(CHIPTOOL_MODE_EXPORTRUN,            exportrunMode);
     81        MODECASE(CHIPTOOL_MODE_IMPORTRUN,            importrunMode);
    7882        default:
    7983            psAbort("invalid option (this should not happen)");
     
    11071111    return true;
    11081112}
     1113
     1114bool exportrunMode(pxConfig *config)
     1115{
     1116  typedef struct ExportTable {
     1117    char tableName[80];
     1118    char sqlFilename[80];
     1119  } ExportTable;
     1120 
     1121  int numExportTables = 2;
     1122
     1123  PS_ASSERT_PTR_NON_NULL(config, NULL);
     1124
     1125  PXOPT_LOOKUP_S64(det_id, config->args, "-exp_id", true,  false);
     1126  PXOPT_LOOKUP_STR(outfile, config->args, "-outfile", true,  false);
     1127  PXOPT_LOOKUP_U64(limit,   config->args, "-limit",   false, false);
     1128
     1129  FILE *f = fopen (outfile, "w");
     1130  if (f == NULL) {
     1131    psError(PS_ERR_UNKNOWN, false, "failed to open output file");
     1132    return false;
     1133  }
     1134
     1135  psMetadata *where = psMetadataAlloc();
     1136  PXOPT_COPY_S64(config->args, where, "-exp_id", "exp_id", "==");
     1137
     1138  ExportTable tables [] = {
     1139    {"rawExp", "regtool_export_raw__exp.sql"},
     1140    {"rawImfile", "regtool_export_raw_imfile.sql"},
     1141  };
     1142
     1143  for (int i=0; i < numExportTables; i++) {
     1144    psString query = pxDataGet(tables[i].sqlFilename);
     1145    if (!query) {
     1146      psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
     1147      return false;
     1148    }
     1149
     1150    if (where && psListLength(where->list)) {
     1151      psString whereClause = psDBGenerateWhereSQL(where, NULL);
     1152      psStringAppend(&query, " %s", whereClause);
     1153      psFree(whereClause);
     1154    }
     1155
     1156    // treat limit == 0 as "no limit"
     1157    if (limit) {
     1158      psString limitString = psDBGenerateLimitSQL(limit);
     1159      psStringAppend(&query, " %s", limitString);
     1160      psFree(limitString);
     1161    }
     1162
     1163    if (!p_psDBRunQuery(config->dbh, query)) {
     1164      psError(PS_ERR_UNKNOWN, false, "database error");
     1165      psFree(query);
     1166      return false;
     1167    }
     1168    psFree(query);
     1169
     1170    psArray *output = p_psDBFetchResult(config->dbh);
     1171    if (!output) {
     1172      psError(PS_ERR_UNKNOWN, false, "database error");
     1173      return false;
     1174    }
     1175    if (!psArrayLength(output)) {
     1176      psTrace("regtool", PS_LOG_INFO, "no rows found");
     1177      psFree(output);
     1178      return true;
     1179    }
     1180
     1181    // we must write the export table in non-simple (true) format
     1182    if (!ippdbPrintMetadatas(f, output, tables[i].tableName, true)) {
     1183      psError(PS_ERR_UNKNOWN, false, "failed to print array");
     1184      psFree(output);
     1185      return false;
     1186    }
     1187    psFree(output);
     1188  }
     1189
     1190  fclose (f);
     1191
     1192  return true;
     1193}
     1194
     1195bool importrunMode(pxConfig *config)
     1196{
     1197  unsigned int nFail;
     1198
     1199  PS_ASSERT_PTR_NON_NULL(config, NULL);
     1200 
     1201  PXOPT_LOOKUP_STR(infile, config->args, "-infile", true,  false);
     1202
     1203  psMetadata *input = psMetadataConfigRead (NULL, &nFail, infile, false);
     1204
     1205  fprintf (stdout, "---- input ----\n");
     1206  psMetadataPrint (stderr, input, 1);
     1207
     1208  psMetadataItem *item = psMetadataLookup (input, "rawExp");
     1209  psAssert (item, "entry not in input?");
     1210  psAssert (item->type == PS_DATA_METADATA_MULTI, "entry not multi?");
     1211 
     1212  psMetadataItem *entry = psListGet (item->data.list, 0);
     1213  assert (entry);
     1214  assert (entry->type == PS_DATA_METADATA);
     1215  rawExpRow *rawExp = rawExpObjectFromMetadata (entry->data.md);
     1216  rawExpInsertObject (config->dbh, rawExp);
     1217
     1218  // fprintf (stdout, "---- raw exp ----\n");
     1219  // psMetadataPrint (stderr, entry->data.md, 1);
     1220
     1221  item = psMetadataLookup (input, "rawImfile");
     1222  psAssert (item, "entry not in input?");
     1223  psAssert (item->type == PS_DATA_METADATA_MULTI, "entry not multi?");
     1224
     1225  for (int i = 0; i < item->data.list->n; i++) {
     1226    psMetadataItem *entry = psListGet (item->data.list, i);
     1227    assert (entry);
     1228    assert (entry->type == PS_DATA_METADATA);
     1229    rawImfileRow *rawImfile = rawImfileObjectFromMetadata (entry->data.md);
     1230    rawImfileInsertObject (config->dbh, rawImfile);
     1231
     1232    // fprintf (stdout, "---- row %d ----\n", i);
     1233    // psMetadataPrint (stderr, entry->data.md, 1);
     1234  }
     1235
     1236  return true;
     1237}
     1238
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/regtool.h

    r18328 r23352  
    3636    REGTOOL_MODE_UPDATEPROCESSEDEXP,
    3737    REGTOOL_MODE_CLEARDUPEXP,
     38    REGTOOL_MODE_EXPORTRUN,
     39    REGTOOL_MODE_IMPORTRUN
    3840} regtoolMode;
    3941
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/regtoolConfig.c

    r20608 r23352  
    278278    psMetadataAddS16(updatedprocessedexpArgs, PS_LIST_TAIL, "-code",    0,            "set fault code (required)", INT16_MAX);
    279279
     280    // -exportrun
     281    psMetadata *exportrunArgs = psMetadataAlloc();
     282    psMetadataAddS64(exportrunArgs, PS_LIST_TAIL, "-exp_id", 0,          "export this exposure ID (required)", 0);
     283    psMetadataAddStr(exportrunArgs, PS_LIST_TAIL, "-outfile", 0,          "export to this file (required)", NULL);
     284    psMetadataAddU64(exportrunArgs, PS_LIST_TAIL, "-limit",   0,          "limit result set to N items", 0);
     285
     286    // -importrun
     287    psMetadata *importrunArgs = psMetadataAlloc();
     288    psMetadataAddStr(importrunArgs, PS_LIST_TAIL, "-infile",  0,          "import from this file (required)", NULL);
     289
     290
    280291    // -cleardupexp
    281292    psMetadata *cleardupexpArgs = psMetadataAlloc();
     
    295306    PXOPT_ADD_MODE("-updateprocessedexp",      "", REGTOOL_MODE_UPDATEPROCESSEDEXP,      updatedprocessedexpArgs);
    296307    PXOPT_ADD_MODE("-cleardupexp",             "", REGTOOL_MODE_CLEARDUPEXP,      cleardupexpArgs);
     308    PXOPT_ADD_MODE("-exportrun",            "export run for import on other database", REGTOOL_MODE_EXPORTRUN, exportrunArgs);
     309    PXOPT_ADD_MODE("-importrun",            "import run from metadata file",           REGTOOL_MODE_IMPORTRUN, importrunArgs);
    297310
    298311    if (!pxGetOptions(stderr, argc, argv, config, modes, argSets)) {
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/stacktool.c

    r21402 r23352  
    4444static bool donecleanupMode(pxConfig *config);
    4545static bool updatesumskyfileMode(pxConfig *config);
     46static bool exportrunMode(pxConfig *config);
     47static bool importrunMode(pxConfig *config);
    4648
    4749static bool setstackRunState(pxConfig *config, psS64 stack_id, const char *state);
     
    7880        MODECASE(STACKTOOL_MODE_DONECLEANUP,           donecleanupMode);
    7981        MODECASE(STACKTOOL_MODE_UPDATESUMSKYFILE,      updatesumskyfileMode);
     82        MODECASE(STACKTOOL_MODE_EXPORTRUN,             exportrunMode);
     83        MODECASE(STACKTOOL_MODE_IMPORTRUN,             importrunMode);
    8084        default:
    8185            psAbort("invalid option (this should not happen)");
     
    11801184}
    11811185
     1186bool exportrunMode(pxConfig *config)
     1187{
     1188  typedef struct ExportTable {
     1189    char tableName[80];
     1190    char sqlFilename[80];
     1191  } ExportTable;
     1192
     1193  int numExportTables = 3;
     1194 
     1195  PS_ASSERT_PTR_NON_NULL(config, NULL);
     1196
     1197  PXOPT_LOOKUP_S64(det_id, config->args, "-stack_id", true,  false);
     1198  PXOPT_LOOKUP_STR(outfile, config->args, "-outfile", true,  false);
     1199  PXOPT_LOOKUP_U64(limit,   config->args, "-limit",   false, false);
     1200
     1201  FILE *f = fopen (outfile, "w");
     1202  if (f == NULL) {
     1203      psError(PS_ERR_UNKNOWN, false, "failed to open output file");
     1204      return false;
     1205  }
     1206
     1207  psMetadata *where = psMetadataAlloc();
     1208  PXOPT_COPY_S64(config->args, where, "-stack_id", "stack_id", "==");
     1209
     1210  ExportTable tables [] = {
     1211    {"stackRun", "stacktool_export_run.sql"},
     1212    {"stackInputSkyfile", "stacktool_export_input_skyfile.sql"},
     1213    {"stackSumSkyfile", "stacktool_export_sum_skyfile.sql"},
     1214  };
     1215
     1216  for (int i=0; i < numExportTables; i++) {
     1217    psString query = pxDataGet(tables[i].sqlFilename);
     1218    if (!query) {
     1219      psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
     1220      return false;
     1221    }
     1222
     1223    if (where && psListLength(where->list)) {
     1224      psString whereClause = psDBGenerateWhereSQL(where, NULL);
     1225      psStringAppend(&query, " %s", whereClause);
     1226      psFree(whereClause);
     1227    }
     1228
     1229    // treat limit == 0 as "no limit"
     1230    if (limit) {
     1231      psString limitString = psDBGenerateLimitSQL(limit);
     1232      psStringAppend(&query, " %s", limitString);
     1233      psFree(limitString);
     1234    }
     1235
     1236    if (!p_psDBRunQuery(config->dbh, query)) {
     1237      psError(PS_ERR_UNKNOWN, false, "database error");
     1238      psFree(query);
     1239      return false;
     1240    }
     1241    psFree(query);
     1242
     1243    psArray *output = p_psDBFetchResult(config->dbh);
     1244    if (!output) {
     1245      psError(PS_ERR_UNKNOWN, false, "database error");
     1246      return false;
     1247    }
     1248    if (!psArrayLength(output)) {
     1249      psTrace("regtool", PS_LOG_INFO, "no rows found");
     1250      psFree(output);
     1251      return true;
     1252    }
     1253    psFree(output);
     1254  }
     1255
     1256    fclose (f);
     1257
     1258    return true;
     1259}
     1260
     1261bool importrunMode(pxConfig *config)
     1262{
     1263  unsigned int nFail;
     1264 
     1265  int numImportTables = 2;
     1266 
     1267  char tables[2] [80] = {"stackInputSkyfile", "stackSumSkyfile"};
     1268
     1269  PS_ASSERT_PTR_NON_NULL(config, NULL);
     1270 
     1271  PXOPT_LOOKUP_STR(infile, config->args, "-infile", true,  false);
     1272
     1273  psMetadata *input = psMetadataConfigRead (NULL, &nFail, infile, false);
     1274
     1275  fprintf (stdout, "---- input ----\n");
     1276  psMetadataPrint (stderr, input, 1);
     1277
     1278  psMetadataItem *item = psMetadataLookup (input, "stackRun");
     1279  psAssert (item, "entry not in input?");
     1280  psAssert (item->type == PS_DATA_METADATA_MULTI, "entry not multi?");
     1281
     1282  psMetadataItem *entry = psListGet (item->data.list, 0);
     1283  assert (entry);
     1284  assert (entry->type == PS_DATA_METADATA);
     1285  stackRunRow *stackRun = stackRunObjectFromMetadata (entry->data.md);
     1286  stackRunInsertObject (config->dbh, stackRun);
     1287
     1288  // fprintf (stdout, "---- stack run ----\n");
     1289  // psMetadataPrint (stderr, entry->data.md, 1);
     1290
     1291  for (int i = 0; i < numImportTables; i++) {
     1292    psMetadataItem *item = psMetadataLookup (input, tables[i]);
     1293    psAssert (item, "entry not in input?");
     1294    psAssert (item->type == PS_DATA_METADATA_MULTI, "entry not multi?");
     1295 
     1296    switch (i) {
     1297      case 0:
     1298        for (int i = 0; i < item->data.list->n; i++) {
     1299          entry = psListGet (item->data.list, i);
     1300          assert (entry);
     1301          assert (entry->type == PS_DATA_METADATA);
     1302          stackInputSkyfileRow *stackInputSkyfile = stackInputSkyfileObjectFromMetadata (entry->data.md);
     1303          stackInputSkyfileInsertObject (config->dbh, stackInputSkyfile);
     1304
     1305          // fprintf (stdout, "---- row %d ----\n", i);
     1306          // psMetadataPrint (stderr, entry->data.md, 1);
     1307        }
     1308        break;
     1309       
     1310      case 1:
     1311        for (int i = 0; i < item->data.list->n; i++) {
     1312          entry = psListGet (item->data.list, i);
     1313          assert (entry);
     1314          assert (entry->type == PS_DATA_METADATA);
     1315          stackSumSkyfileRow *stackSumSkyfile = stackSumSkyfileObjectFromMetadata (entry->data.md);
     1316          stackSumSkyfileInsertObject (config->dbh, stackSumSkyfile);
     1317
     1318          // fprintf (stdout, "---- row %d ----\n", i);
     1319          // psMetadataPrint (stderr, entry->data.md, 1);
     1320        }
     1321        break;
     1322    }
     1323  }
     1324 
     1325  return true;
     1326}
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/stacktool.h

    r19676 r23352  
    3838    STACKTOOL_MODE_DONECLEANUP,
    3939    STACKTOOL_MODE_UPDATESUMSKYFILE,
     40    STACKTOOL_MODE_EXPORTRUN,
     41    STACKTOOL_MODE_IMPORTRUN
    4042} stacktoolMode;
    4143
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/stacktoolConfig.c

    r19931 r23352  
    187187    psMetadataAddS16(updatesumskyfileArgs, PS_LIST_TAIL, "-code", 0,            "set fault code (required)", 0);
    188188
     189    // -exportrun
     190    psMetadata *exportrunArgs = psMetadataAlloc();
     191    psMetadataAddS64(exportrunArgs, PS_LIST_TAIL, "-stack_id", 0,          "export this stack ID (required)", 0);
     192    psMetadataAddStr(exportrunArgs, PS_LIST_TAIL, "-outfile", 0,          "export to this file (required)", NULL);
     193    psMetadataAddU64(exportrunArgs, PS_LIST_TAIL, "-limit",   0,          "limit result set to N items", 0);
     194
     195    // -importrun
     196    psMetadata *importrunArgs = psMetadataAlloc();
     197    psMetadataAddStr(importrunArgs, PS_LIST_TAIL, "-infile",  0,          "import from this file (required)", NULL);
     198
     199
    189200    psFree(now);
    190201
     
    205216    PXOPT_ADD_MODE("-donecleanup",           "show runs that have been cleaned",     STACKTOOL_MODE_DONECLEANUP,          donecleanupArgs);
    206217    PXOPT_ADD_MODE("-updatesumskyfile",      "update fault code for sumskyfile",     STACKTOOL_MODE_UPDATESUMSKYFILE,          updatesumskyfileArgs);
     218    PXOPT_ADD_MODE("-exportrun",            "export run for import on other database", STACKTOOL_MODE_EXPORTRUN, exportrunArgs);
     219    PXOPT_ADD_MODE("-importrun",            "import run from metadata file",           STACKTOOL_MODE_IMPORTRUN, importrunArgs);
    207220
    208221    if (!pxGetOptions(stderr, argc, argv, config, modes, argSets)) {
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/warptool.c

    r21402 r23352  
    5454static bool tofullskyfileMode(pxConfig *config);
    5555static bool updateskyfileMode(pxConfig *config);
     56static bool exportrunMode(pxConfig *config);
     57static bool importrunMode(pxConfig *config);
    5658
    5759static bool parseAndInsertSkyCellMap(pxConfig *config, const char *mapfile);
     
    99101        MODECASE(WARPTOOL_MODE_TOFULLSKYFILE,      tofullskyfileMode);
    100102        MODECASE(WARPTOOL_MODE_UPDATESKYFILE,      updateskyfileMode);
     103        MODECASE(WARPTOOL_MODE_EXPORTRUN,          exportrunMode);
     104        MODECASE(WARPTOOL_MODE_IMPORTRUN,          importrunMode);
    101105
    102106        default:
     
    16801684    return true;
    16811685}
     1686
     1687bool exportrunMode(pxConfig *config)
     1688{
     1689  typedef struct ExportTable {
     1690    char tableName[80];
     1691    char sqlFilename[80];
     1692  } ExportTable;
     1693
     1694    PS_ASSERT_PTR_NON_NULL(config, NULL);
     1695
     1696    PXOPT_LOOKUP_S64(det_id, config->args, "-warp_id", true,  false);
     1697    PXOPT_LOOKUP_STR(outfile, config->args, "-outfile", true,  false);
     1698    PXOPT_LOOKUP_U64(limit,   config->args, "-limit",   false, false);
     1699
     1700    FILE *f = fopen (outfile, "w");
     1701    if (f == NULL) {
     1702        psError(PS_ERR_UNKNOWN, false, "failed to open output file");
     1703        return false;
     1704    }
     1705
     1706    psMetadata *where = psMetadataAlloc();
     1707    PXOPT_COPY_S64(config->args, where, "-warp_id", "warp_id", "==");
     1708
     1709    ExportTable tables [] = {
     1710      {"warpRun", "warptool_export_run.sql"},
     1711      {"warpImfile", "warptool_export_imfile.sql"},
     1712      {"warpSkyfile", "warptool_export_skyfile.sql"},
     1713      {"warpSkyCellMap", "warptool_export_sky_cell_map.sql"},
     1714    };
     1715
     1716
     1717    for (int i=0; i < sizeof(tables); i++) {
     1718      psString query = pxDataGet(tables[i].sqlFilename);
     1719      if (!query) {
     1720          psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
     1721          return false;
     1722      }
     1723
     1724      if (where && psListLength(where->list)) {
     1725          psString whereClause = psDBGenerateWhereSQL(where, NULL);
     1726          psStringAppend(&query, " %s", whereClause);
     1727          psFree(whereClause);
     1728      }
     1729
     1730      // treat limit == 0 as "no limit"
     1731      if (limit) {
     1732        psString limitString = psDBGenerateLimitSQL(limit);
     1733        psStringAppend(&query, " %s", limitString);
     1734        psFree(limitString);
     1735      }
     1736
     1737      if (!p_psDBRunQuery(config->dbh, query)) {
     1738        psError(PS_ERR_UNKNOWN, false, "database error");
     1739        psFree(query);
     1740        return false;
     1741      }
     1742      psFree(query);
     1743
     1744      psArray *output = p_psDBFetchResult(config->dbh);
     1745      if (!output) {
     1746          psError(PS_ERR_UNKNOWN, false, "database error");
     1747          return false;
     1748      }
     1749      if (!psArrayLength(output)) {
     1750        psTrace("regtool", PS_LOG_INFO, "no rows found");
     1751        psFree(output);
     1752        return true;
     1753      }
     1754
     1755      // we must write the export table in non-simple (true) format
     1756      if (!ippdbPrintMetadatas(f, output, tables[i].tableName, true)) {
     1757        psError(PS_ERR_UNKNOWN, false, "failed to print array");
     1758        psFree(output);
     1759        return false;
     1760      }
     1761      psFree(output);
     1762    }
     1763
     1764    fclose (f);
     1765
     1766    return true;
     1767}
     1768
     1769bool importrunMode(pxConfig *config)
     1770{
     1771  unsigned int nFail;
     1772
     1773  int numImportTables = 3;
     1774 
     1775  char tables[3] [80] = {"warpImfile", "warpSkyfile", "warpSkyCellMap"};
     1776
     1777  PS_ASSERT_PTR_NON_NULL(config, NULL);
     1778 
     1779  PXOPT_LOOKUP_STR(infile, config->args, "-infile", true,  false);
     1780
     1781  psMetadata *input = psMetadataConfigRead (NULL, &nFail, infile, false);
     1782
     1783  fprintf (stdout, "---- input ----\n");
     1784  psMetadataPrint (stderr, input, 1);
     1785
     1786  psMetadataItem *item = psMetadataLookup (input, "warpRun");
     1787  psAssert (item, "entry not in input?");
     1788  psAssert (item->type == PS_DATA_METADATA_MULTI, "entry not multi?");
     1789 
     1790  psMetadataItem *entry = psListGet (item->data.list, 0);
     1791  assert (entry);
     1792  assert (entry->type == PS_DATA_METADATA);
     1793  warpRunRow *warpRun = warpRunObjectFromMetadata (entry->data.md);
     1794  warpRunInsertObject (config->dbh, warpRun);
     1795
     1796  // fprintf (stdout, "---- warp run ----\n");
     1797  // psMetadataPrint (stderr, entry->data.md, 1);
     1798
     1799  for (int i = 0; i < numImportTables; i++) {
     1800    item = psMetadataLookup (input, tables[i]);
     1801    psAssert (item, "entry not in input?");
     1802    psAssert (item->type == PS_DATA_METADATA_MULTI, "entry not multi?");
     1803   
     1804    switch (i) {
     1805      case 0: 
     1806        for (int i = 0; i < item->data.list->n; i++) {
     1807          entry = psListGet (item->data.list, i);
     1808          assert (entry);
     1809          assert (entry->type == PS_DATA_METADATA);
     1810          warpImfileRow *warpImfile = warpImfileObjectFromMetadata (entry->data.md);
     1811          warpImfileInsertObject (config->dbh, warpImfile);
     1812
     1813          // fprintf (stdout, "---- row %d ----\n", i);
     1814          // psMetadataPrint (stderr, entry->data.md, 1);
     1815        }
     1816        break;
     1817       
     1818      case 1: 
     1819        for (int i = 0; i < item->data.list->n; i++) {
     1820          entry = psListGet (item->data.list, i);
     1821          assert (entry);
     1822          assert (entry->type == PS_DATA_METADATA);
     1823          warpSkyfileRow *warpSkyfile = warpSkyfileObjectFromMetadata (entry->data.md);
     1824          warpSkyfileInsertObject (config->dbh, warpSkyfile);
     1825
     1826          // fprintf (stdout, "---- row %d ----\n", i);
     1827          // psMetadataPrint (stderr, entry->data.md, 1);
     1828        }
     1829        break;
     1830       
     1831      case 2: 
     1832        for (int i = 0; i < item->data.list->n; i++) {
     1833          entry = psListGet (item->data.list, i);
     1834          assert (entry);
     1835          assert (entry->type == PS_DATA_METADATA);
     1836          warpSkyCellMapRow *warpSkyCellMap = warpSkyCellMapObjectFromMetadata (entry->data.md);
     1837          warpSkyCellMapInsertObject (config->dbh, warpSkyCellMap);
     1838
     1839          // fprintf (stdout, "---- row %d ----\n", i);
     1840          // psMetadataPrint (stderr, entry->data.md, 1);
     1841        }
     1842        break;
     1843    }
     1844  }
     1845  return true;
     1846}
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/warptool.h

    r19522 r23352  
    4949    WARPTOOL_MODE_TOFULLSKYFILE,
    5050    WARPTOOL_MODE_UPDATESKYFILE,
     51    WARPTOOL_MODE_EXPORTRUN,
     52    WARPTOOL_MODE_IMPORTRUN
    5153} warptoolMode;
    5254
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/warptoolConfig.c

    r20973 r23352  
    354354    psMetadataAddS16(updateskyfileArgs, PS_LIST_TAIL, "-code",  0,      "new fault code", 0);
    355355
     356    // -exportrun
     357    psMetadata *exportrunArgs = psMetadataAlloc();
     358    psMetadataAddS64(exportrunArgs, PS_LIST_TAIL, "-warp_id", 0,          "export this warp ID (required)", 0);
     359    psMetadataAddStr(exportrunArgs, PS_LIST_TAIL, "-outfile", 0,          "export to this file (required)", NULL);
     360    psMetadataAddU64(exportrunArgs, PS_LIST_TAIL, "-limit",   0,          "limit result set to N items", 0);
     361
     362    // -importrun
     363    psMetadata *importrunArgs = psMetadataAlloc();
     364    psMetadataAddStr(importrunArgs, PS_LIST_TAIL, "-infile",  0,          "import from this file (required)", NULL);
     365
     366
    356367    psFree(now);
    357368    psMetadata *argSets = psMetadataAlloc();
     
    380391    PXOPT_ADD_MODE("-tofullskyfile", "set skyfile as full (updated)", WARPTOOL_MODE_TOFULLSKYFILE, tofullskyfileArgs);
    381392    PXOPT_ADD_MODE("-updateskyfile", "update fault code for skyfile", WARPTOOL_MODE_UPDATESKYFILE, updateskyfileArgs);
     393    PXOPT_ADD_MODE("-exportrun",            "export run for import on other database", WARPTOOL_MODE_EXPORTRUN, exportrunArgs);
     394    PXOPT_ADD_MODE("-importrun",            "import run from metadata file",           WARPTOOL_MODE_IMPORTRUN, importrunArgs);
    382395
    383396    if (!pxGetOptions(stderr, argc, argv, config, modes, argSets)) {
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/gpc1/format_20080925.config

    r21023 r23352  
    189189        FPA.RA          STR     RA
    190190        FPA.DEC         STR     DEC
    191         FPA.RADECSYS    STR     RADECSYS
     191        FPA.RADECSYS    STR     EQUINOX
    192192        FPA.OBSTYPE     STR     OBSTYPE
    193193        FPA.OBJECT      STR     OBJECT
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/gpc1/format_20080929.config

    r21023 r23352  
    184184        FPA.RA          STR     RA
    185185        FPA.DEC         STR     DEC
    186         FPA.RADECSYS    STR     RADECSYS
     186        FPA.RADECSYS    STR     EQUINOX
    187187        FPA.OBSTYPE     STR     OBSTYPE
    188188        FPA.OBJECT      STR     OBJECT
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/gpc1/format_20081011.config

    r20951 r23352  
    174174        FPA.RA          STR     RA
    175175        FPA.DEC         STR     DEC
    176         FPA.RADECSYS    STR     RADECSYS
     176        FPA.RADECSYS    STR     EQUINOX
    177177        FPA.OBSTYPE     STR     OBSTYPE
    178178        FPA.OBJECT      STR     OBJECT
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/gpc1/format_20090120.config

    r21539 r23352  
    173173        FPA.RA          STR     RA
    174174        FPA.DEC         STR     DEC
    175         FPA.RADECSYS    STR     RADECSYS
     175        FPA.RADECSYS    STR     EQUINOX
    176176        FPA.OBSTYPE     STR     OBSTYPE
    177177        FPA.OBJECT      STR     OBJECT
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/gpc1/format_20090220.config

    r22212 r23352  
    173173        FPA.RA          STR     RA
    174174        FPA.DEC         STR     DEC
    175         FPA.RADECSYS    STR     RADECSYS
     175        FPA.RADECSYS    STR     EQUINOX
    176176        FPA.OBSTYPE     STR     OBSTYPE
    177177        FPA.OBJECT      STR     OBJECT
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/gpc1/format_mef.config

    r22685 r23352  
    168168        FPA.RA          STR     RA
    169169        FPA.DEC         STR     DEC
    170         FPA.RADECSYS    STR     RADECSYS
     170        FPA.RADECSYS    STR     EQUINOX
    171171        FPA.OBSTYPE     STR     OBSTYPE
    172172        FPA.OBJECT      STR     OBJECT
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/gpc1/format_orig.config

    r21023 r23352  
    182182        # FPA.RA          STR     COMRA
    183183        # FPA.DEC         STR     COMDEC
    184         FPA.RADECSYS    STR     RADECSYS
     184        FPA.RADECSYS    STR     EQUINOX
    185185        FPA.OBSTYPE     STR     OBSTYPE
    186186        FPA.OBJECT      STR     OBJECT
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/gpc1/format_relphot.config

    r21023 r23352  
    105105        FPA.RA          STR     RA
    106106        FPA.DEC         STR     DEC
    107         FPA.RADECSYS    STR     RADECSYS
     107        FPA.RADECSYS    STR     EQUINOX
    108108        FPA.OBSTYPE     STR     OBSTYPE
    109109        FPA.OBJECT      STR     OBJECT
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/gpc1/ppImage.config

    r21370 r23352  
    1010OVERSCAN.BOXCAR         S32     3
    1111
     12# Normalization class
     13NORM.CLASS              STR     CHIP             # How to find the per-class normalizations
     14
    1215OLDDARK                 BOOL    FALSE
    1316
     
    134137# Overscan, bias, dark, shutter
    135138PPIMAGE_OBDS       METADATA
    136   BASE.FITS        BOOL    TRUE            # Save base detrended image?
    137   BASE.MASK.FITS   BOOL    TRUE            # Save base detrended image?
     139  BASE.FITS          BOOL    TRUE            # Save base detrended image?
     140  BASE.MASK.FITS     BOOL    TRUE            # Save base detrended image?
    138141  BASE.VARIANCE.FITS BOOL    TRUE            # Save base detrended image?
    139   CHIP.FITS        BOOL    FALSE           # Save chip-mosaic-ed image?
    140   CHIP.MASK.FITS   BOOL    FALSE           # Save chip-mosaic-ed image?
    141   CHIP.VARIANCE.FITS BOOL    FALSE           # Save chip-mosaic-ed image?
    142   OVERSCAN         BOOL    TRUE            # Overscan subtraction
    143   BIAS             BOOL    FALSE           # Bias subtraction
    144   DARK             BOOL    TRUE            # Dark subtraction
    145   SHUTTER          BOOL    FALSE           # Shutter correction
    146   FLAT             BOOL    FALSE           # Flat-field normalisation
    147   MASK             BOOL    FALSE           # Mask bad pixels
    148   FRINGE           BOOL    FALSE           # Fringe subtraction
    149   PHOTOM           BOOL    FALSE           # Source identification and photometry
    150   ASTROM.CHIP      BOOL    FALSE           # Astrometry per chip?
    151   ASTROM.MOSAIC    BOOL    FALSE           # Astrometry for mosaic?
    152   BIN1.FITS        BOOL    TRUE            # Save 1st binned chip image?
    153   BIN2.FITS        BOOL    TRUE            # Save 2nd binned chip image?
     142  CHIP.FITS          BOOL    FALSE           # Save chip-mosaic-ed image?
     143  CHIP.MASK.FITS     BOOL    FALSE           # Save chip-mosaic-ed image?
     144  CHIP.VARIANCE.FITS BOOL    FALSE           # Save chip-mosaic-ed image?
     145  OVERSCAN           BOOL    TRUE            # Overscan subtraction
     146  BIAS               BOOL    FALSE           # Bias subtraction
     147  DARK               BOOL    TRUE            # Dark subtraction
     148  SHUTTER            BOOL    FALSE           # Shutter correction
     149  FLAT               BOOL    FALSE           # Flat-field normalisation
     150  MASK               BOOL    FALSE           # Mask bad pixels
     151  FRINGE             BOOL    FALSE           # Fringe subtraction
     152  PHOTOM             BOOL    FALSE           # Source identification and photometry
     153  ASTROM.CHIP        BOOL    FALSE           # Astrometry per chip?
     154  ASTROM.MOSAIC      BOOL    FALSE           # Astrometry for mosaic?
     155  BIN1.FITS          BOOL    TRUE            # Save 1st binned chip image?
     156  BIN2.FITS          BOOL    TRUE            # Save 2nd binned chip image?
     157END
     158
     159# Overscan, bias, dark, shutter
     160PPIMAGE_FLATPROC_PREMASK       METADATA
     161  BASE.FITS          BOOL    TRUE            # Save base detrended image?
     162  BASE.MASK.FITS     BOOL    TRUE            # Save base detrended image?
     163  BASE.VARIANCE.FITS BOOL    TRUE            # Save base detrended image?
     164  CHIP.FITS          BOOL    FALSE           # Save chip-mosaic-ed image?
     165  CHIP.MASK.FITS     BOOL    FALSE           # Save chip-mosaic-ed image?
     166  CHIP.VARIANCE.FITS BOOL    FALSE           # Save chip-mosaic-ed image?
     167  OVERSCAN           BOOL    TRUE            # Overscan subtraction
     168  BIAS               BOOL    FALSE           # Bias subtraction
     169  DARK               BOOL    TRUE            # Dark subtraction
     170  SHUTTER            BOOL    FALSE           # Shutter correction
     171  FLAT               BOOL    FALSE           # Flat-field normalisation
     172  MASK               BOOL    FALSE           # Mask bad pixels
     173  FRINGE             BOOL    FALSE           # Fringe subtraction
     174  PHOTOM             BOOL    FALSE           # Source identification and photometry
     175  ASTROM.CHIP        BOOL    FALSE           # Astrometry per chip?
     176  ASTROM.MOSAIC      BOOL    FALSE           # Astrometry for mosaic?
     177  BIN1.FITS          BOOL    TRUE            # Save 1st binned chip image?
     178  BIN2.FITS          BOOL    TRUE            # Save 2nd binned chip image?
     179
     180  DETREND.CONSTRAINTS  METADATA
     181    DARK METADATA
     182      DETTYPE STR DARK_PREMASK
     183    END
     184  END   
    154185END
    155186
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/gpc1/ppMerge.config

    r18252 r23352  
    2121DARK.ORDINATES  METADATA
    2222        CELL.DARKTIME   S32     1
    23         CHIP.TEMP       METADATA
    24                 ORDER   S32     1
    25                 SCALE   BOOL    TRUE
    26                 MIN     F32     -95
    27                 MAX     F32     -50
    28         END
     23#       CHIP.TEMP       METADATA
     24#               ORDER   S32     1
     25#               SCALE   BOOL    TRUE
     26#               MIN     F32     -95
     27#               MAX     F32     -50
     28#       END
    2929END
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/ipprc.config.in

    r22215 r23352  
    33# Default search path for configuration files (add $HOME if desired)
    44# Note: do not include $HOME in the distributed copy used by ippMonitor
    5 # PATH            STR     @pkgdatadir@:$HOME/.ipp:.
    6 PATH              STR     $HOME/ippconfig/:$PSCONFDIR/$PSCONFIG/share/ippconfig/
     5PATH            STR     @pkgdatadir@
     6### This is a useful setting for an individual user:
     7#PATH           STR     $HOME/ippconfig/:$PSCONFDIR/$PSCONFIG/share/ippconfig/
    78
    89# load the site-specific information from here
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/megacam/psphot.config

    r21070 r23352  
    1414SKY_CLIP_SIGMA      F32  2.0             # statistic used to measure background
    1515
    16 PSF_SN_LIM          F32  100             # minimum S/N for stars used for PSF model
     16PSF_SN_LIM          F32  20             # minimum S/N for stars used for PSF model
    1717PSF_MAX_NSTARS      S32  300             # limit number of stars used for PSF model
    1818
     
    2020PSF_MODEL           STR  PS_MODEL_QGAUSS
    2121
    22 MOMENTS_SN_MIN      F32   30.0
     22PSF_MOMENTS_RADIUS  F32   10.0           # calculate initial source moments with this radius
     23
     24MOMENTS_SN_MIN      F32    2.0
    2325EXT_MIN_SN           F32  50.0           # fit galaxies above this S/N limit
    2426FULL_FIT_SN_LIM      F32  50.0
    25 AP_MIN_SN            F32  50.0
    26 
    27 # OUTPUT.FORMAT       STR SMPDATA
    28 OUTPUT.FORMAT       STR PS1_DEV_1
     27AP_MIN_SN            F32   2.0
    2928
    3029PSF_SHAPE_NSIGMA     F32  3.0            # max significance for shape variation
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/recipes/filerules-mef.mdc

    r21370 r23352  
    9898PPSUB.INPUT.MASK        INPUT    @FILES        FPA        MASK
    9999PPSUB.INPUT.VARIANCE    INPUT    @FILES        FPA        VARIANCE
     100PPSUB.INPUT.SOURCES     INPUT    @FILES        FPA        CMF
    100101PPSUB.REF               INPUT    @FILES        FPA        IMAGE
    101102PPSUB.REF.MASK          INPUT    @FILES        FPA        MASK
    102103PPSUB.REF.VARIANCE      INPUT    @FILES        FPA        VARIANCE
    103 PPSUB.SOURCES           INPUT    @FILES        FPA        CMF
     104PPSUB.REF.SOURCES       INPUT    @FILES        FPA        CMF
    104105
    105106## files used by ppstack
     
    128129PPIMAGE.OUT.WT.SPL      OUTPUT {OUTPUT}.{CHIP.NAME}.wt.fits      VARIANCE  NONE       CHIP       TRUE      SPLIT
    129130PPIMAGE.OUTPUT.DETMASK  OUTPUT {OUTPUT}.fits                     IMAGE     MASK       CHIP       TRUE      MEF
     131PPIMAGE.OUTPUT.DETREND  OUTPUT {OUTPUT}.fits                     IMAGE     COMP_DET   CHIP       TRUE      MEF
    130132PPIMAGE.OUTPUT.RESID    OUTPUT {OUTPUT}.b0.fits                  IMAGE     COMP_SUB   CHIP       TRUE      MEF
    131133PPIMAGE.CONFIG          OUTPUT {OUTPUT}.{CHIP.NAME}.ppImage.mdc  TEXT      NONE       CHIP       TRUE      NONE
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/recipes/filerules-simple.mdc

    r21370 r23352  
    6161PPSUB.INPUT.MASK        INPUT    @FILES        FPA        MASK
    6262PPSUB.INPUT.VARIANCE    INPUT    @FILES        FPA        VARIANCE
     63PPSUB.INPUT.SOURCES     INPUT    @FILES        FPA        CMF
    6364PPSUB.REF               INPUT    @FILES        FPA        IMAGE
    6465PPSUB.REF.MASK          INPUT    @FILES        FPA        MASK
    6566PPSUB.REF.VARIANCE      INPUT    @FILES        FPA        VARIANCE
    66 PPSUB.SOURCES           INPUT    @FILES        FPA        CMF
     67PPSUB.REF.SOURCES       INPUT    @FILES        FPA        CMF
    6768
    6869## files used by ppstack
     
    9192PPIMAGE.OUTPUT.VARIANCE OUTPUT {OUTPUT}.wt.fits      VARIANCE  NONE       FPA        TRUE      SIMPLE
    9293PPIMAGE.OUTPUT.DETMASK  OUTPUT {OUTPUT}.fits         IMAGE     NONE       FPA        TRUE      SIMPLE
     94PPIMAGE.OUTPUT.DETREND  OUTPUT {OUTPUT}.fits         IMAGE     NONE       FPA        TRUE      SIMPLE
    9395PPIMAGE.OUTPUT.RESID    OUTPUT {OUTPUT}.fits         IMAGE     NONE       FPA        TRUE      SIMPLE
    9496PPIMAGE.CONFIG          OUTPUT {OUTPUT}.ppImage.mdc  TEXT      NONE       FPA        TRUE      NONE
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/recipes/filerules-split.mdc

    r21531 r23352  
    7373PPSUB.INPUT.MASK        INPUT    @FILES        FPA        MASK
    7474PPSUB.INPUT.VARIANCE    INPUT    @FILES        FPA        VARIANCE
     75PPSUB.INPUT.SOURCES     INPUT    @FILES        FPA        CMF
    7576PPSUB.REF               INPUT    @FILES        FPA        IMAGE
    7677PPSUB.REF.MASK          INPUT    @FILES        FPA        MASK
    7778PPSUB.REF.VARIANCE      INPUT    @FILES        FPA        VARIANCE
    78 PPSUB.SOURCES           INPUT    @FILES        FPA        CMF
     79PPSUB.REF.SOURCES       INPUT    @FILES        FPA        CMF
    7980
    8081## files used by ppstack
     
    100101PPIMAGE.OUTPUT.VARIANCE OUTPUT {OUTPUT}.{CHIP.NAME}.wt.fits      VARIANCE  COMP_WT    CHIP       TRUE      NONE
    101102PPIMAGE.OUTPUT.DETMASK  OUTPUT {OUTPUT}.{CHIP.NAME}.fits         IMAGE     DET_MASK   CHIP       TRUE      NONE
     103PPIMAGE.OUTPUT.DETREND  OUTPUT {OUTPUT}.{CHIP.NAME}.fits         IMAGE     COMP_DET   CHIP       TRUE      NONE
    102104PPIMAGE.OUTPUT.RESID    OUTPUT {OUTPUT}.{CHIP.NAME}.fits         IMAGE     COMP_SUB   CHIP       TRUE      NONE
    103105PPIMAGE.CONFIG          OUTPUT {OUTPUT}.{CHIP.NAME}.ppImage.mdc  TEXT      NONE       CHIP       TRUE      NONE
    104 
    105 #PPIMAGE.OUTPUT          OUTPUT {OUTPUT}.{CHIP.NAME}.fits         IMAGE     NONE  CHIP       TRUE      NONE
    106 #PPIMAGE.OUTPUT.MASK     OUTPUT {OUTPUT}.{CHIP.NAME}.mk.fits      MASK      NONE  CHIP       TRUE      NONE
    107 #PPIMAGE.OUTPUT.VARIANCE OUTPUT {OUTPUT}.{CHIP.NAME}.wt.fits      VARIANCE  NONE  CHIP       TRUE      NONE
    108 #PPIMAGE.OUTPUT.DETMASK  OUTPUT {OUTPUT}.{CHIP.NAME}.fits         IMAGE     NONE  CHIP       TRUE      NONE
    109106                                                                                               
    110107PPIMAGE.CHIP            OUTPUT {OUTPUT}.{CHIP.NAME}.ch.fits      IMAGE     COMP_IMG   CHIP       TRUE      NONE
     
    124121                                                                                                       
    125122PPIMAGE.STATS           OUTPUT {OUTPUT}.{CHIP.NAME}.stats        STATS     NONE       CHIP       TRUE      NONE
    126                                                                                                        
     123
    127124## note: these use the  same output naming convention since they are used for different ppMerge runs
    128 PPMERGE.OUTPUT.MASK     OUTPUT {OUTPUT}.{CHIP.NAME}.fits         MASK      NONE       CHIP       TRUE      NONE
     125PPMERGE.OUTPUT.MASK     OUTPUT {OUTPUT}.{CHIP.NAME}.fits         MASK      DET_MASK   CHIP       TRUE      NONE
    129126PPMERGE.OUTPUT.BIAS     OUTPUT {OUTPUT}.{CHIP.NAME}.fits         IMAGE     NONE       CHIP       TRUE      NONE
    130127PPMERGE.OUTPUT.DARK     OUTPUT {OUTPUT}.{CHIP.NAME}.fits         DARK      NONE       CHIP       TRUE      NONE
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/recipes/fitstypes.mdc

    r21534 r23352  
    1919# STDEV.NUM(F32) is the number of standard deviations to the edge (when SCALING = STDEV_NEGATIVE|STDEV_POSITIVE)
    2020# FLOAT(STR) is the name of a custom floating-point type
     21
     22# Compressed detrend
     23COMP_FLAT       METADATA
     24        BITPIX          S32     16
     25        SCALING         STR     MANUAL
     26        BSCALE          F32     1.0
     27        BZERO           F32     32768.0
     28        COMPRESSION     STR     RICE
     29        TILE.X          S32     0
     30        TILE.Y          S32     1
     31        TILE.Z          S32     1
     32        NOISE           S32     8
     33END
    2134
    2235DET_IMAGE       METADATA
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/recipes/jpeg.mdc

    r19743 r23352  
    138138                COLORMAP        STR     -greyscale
    139139                SCALE.MODE      STR     FRACTION
    140                 SCALE.MIN       F32     0.95
    141                 SCALE.MAX       F32     1.05
     140                SCALE.MIN       F32     0.99
     141                SCALE.MAX       F32     1.01
    142142        END
    143143
     
    145145                COLORMAP        STR     -greyscale
    146146                SCALE.MODE      STR     FRACTION
    147                 SCALE.MIN       F32     0.95
    148                 SCALE.MAX       F32     1.05
     147                SCALE.MIN       F32     0.99
     148                SCALE.MAX       F32     1.01
    149149        END
    150150END
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/recipes/ppImage.config

    r21370 r23352  
    4141NONLIN.DATA             STR     nonlin.dat      # Filename for lookup table
    4242
     43# Normalization class
     44NORM.CLASS              STR     FPA             # How to find the per-class normalizations
     45
    4346OLDDARK         BOOL    FALSE           # Use old-style darks?
    4447
     
    433436  BIN1.FITS        BOOL    TRUE            # Save 1st binned chip image?
    434437  BIN2.FITS        BOOL    TRUE            # Save 2nd binned chip image?
     438END
     439
     440# used for the pre-mask version of flat-field processing
     441PPIMAGE_FLATPROC_PREMASK       METADATA
     442  BASE.FITS          BOOL    TRUE            # Save base detrended image?
     443  BASE.MASK.FITS     BOOL    TRUE            # Save base detrended image?
     444  BASE.VARIANCE.FITS BOOL    TRUE            # Save base detrended image?
     445  CHIP.FITS          BOOL    FALSE           # Save chip-mosaic-ed image?
     446  CHIP.MASK.FITS     BOOL    FALSE           # Save chip-mosaic-ed image?
     447  CHIP.VARIANCE.FITS BOOL    FALSE           # Save chip-mosaic-ed image?
     448  OVERSCAN           BOOL    TRUE            # Overscan subtraction
     449  BIAS               BOOL    TRUE            # Bias subtraction
     450  DARK               BOOL    TRUE            # Dark subtraction
     451  SHUTTER            BOOL    FALSE           # Shutter correction
     452  FLAT               BOOL    FALSE           # Flat-field normalisation
     453  MASK               BOOL    FALSE           # Mask bad pixels
     454  FRINGE             BOOL    FALSE           # Fringe subtraction
     455  PHOTOM             BOOL    FALSE           # Source identification and photometry
     456  ASTROM.CHIP        BOOL    FALSE           # Astrometry per chip?
     457  ASTROM.MOSAIC      BOOL    FALSE           # Astrometry for mosaic?
     458  BIN1.FITS          BOOL    TRUE            # Save 1st binned chip image?
     459  BIN2.FITS          BOOL    TRUE            # Save 2nd binned chip image?
     460
     461  DETREND.CONSTRAINTS  METADATA
     462    DARK METADATA
     463      DETTYPE STR DARK_PREMASK
     464    END
     465  END   
    435466END
    436467
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/recipes/ppStack.config

    r21475 r23352  
    3232
    3333ZP.RADIUS       F32     1.0             # Radius (pixels) for matching sources
    34 ZP.ITER         S32     1000            # Maximum iterations for zero point
     34ZP.ITER.1       S32     5               # Iterations for zero point; pass 1
     35ZP.ITER.2       S32     1000            # Iterations for zero point; pass 2
    3536ZP.TOL          F32     1.0e-6          # Tolerance for zero point iterations
    3637ZP.TRANS.ITER   S32     2               # Iterations for transparency determination
    3738ZP.TRANS.REJ    F32     3.0             # Rejection threshold for transparency determination
    3839ZP.TRANS.THRESH F32     1.0             # Threshold for transparency determination
    39 ZP.STAR.REJ     F32     3.0             # Rejection threshold for stars
     40ZP.STAR.REJ.1   F32     20.0            # Rejection threshold for stars; pass 1
     41ZP.STAR.REJ.2   F32     3.0             # Rejection threshold for stars; pass 2
    4042ZP.STAR.LIMIT   F32     1.0e-2          # Limit on star rejection fraction for successful iteration
    41 ZP.STAR.SYS     F32     0.05            # Estimated systematic error
     43ZP.STAR.SYS.1   F32     0.10            # Estimated systematic error; pass 1
     44ZP.STAR.SYS.2   F32     0.05            # Estimated systematic error; pass 2
     45ZP.MATCH        F32     0.3             # Fraction of images to match for good star
    4246ZP.AIRMASS      METADATA                # Airmass terms by filter
    4347        g       F32     0.0
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/recipes/ppSub.config

    r21370 r23352  
    55SPATIAL.ORDER   S32     0               # Spatial polynomial order
    66REGION.SIZE     F32     0               # Iso-kernel region size (pixels)
     7SOURCE.RADIUS   F32     3.0             # Source matching radius (pixels)
    78STAMP.SPACING   F32     200             # Typical spacing between stamps (pixels)
    89STAMP.FOOTPRINT S32     20              # Size of stamps (pixels)
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/recipes/psphot.config

    r21505 r23352  
    1616ZERO_PT                             F32   25.000          # zero point used by DVO
    1717
    18 OUTPUT.FORMAT                       STR   PS1_DEV_1
     18OUTPUT.FORMAT                       STR   PS1_V1
    1919
    2020# these parameter govern how the background is measured
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/recipes/reductionClasses.mdc

    r20745 r23352  
    3131
    3232        # *** premask (unmasked) flat-field types
    33         FLAT_PREMASK_PROCESS    STR     PPIMAGE_OBDS
     33        FLAT_PREMASK_PROCESS    STR     PPIMAGE_FLATPROC_PREMASK
    3434        FLAT_PREMASK_RESID      STR     PPIMAGE_F
    3535        FLAT_PREMASK_VERIFY     STR     PPIMAGE_F
    3636        FLAT_PREMASK_STACK      STR     PPMERGE_FLAT
    3737        FLAT_PREMASK_JPEG_IMAGE STR     FLAT
    38         FLAT_PREMASK_JPEG_RESID STRE    FLAT_RESID
     38        FLAT_PREMASK_JPEG_RESID STR     FLAT_RESID
    3939
    4040        DOMEFLAT_PREMASK_PROCESS        STR     PPIMAGE_OBDS
  • branches/cnb_branches/cnb_branch_20090301/magic/remove/src/streaksrelease.c

    r21156 r23352  
    88static void excisePixel(streakFiles *sfiles, unsigned int x, unsigned int y, bool streak, double newMaskValue);
    99static void writeImages(streakFiles *sf, bool exciseImageCube);
    10 static bool replicateOutputs(streakFiles *sfiles);
    1110
    1211int
     
    252251        // image data directly from psFits
    253252        readImage(sf->inImage, sf->extnum, sf->stage, false);
     253       
     254        // astrom struct is only needed for raw stage, and only the chip to cell parameters are used
     255        sf->astrom = streakSetAstrometry(sf->astrom, sf->stage, NULL, NULL, false,
     256            sf->inImage->header, sf->inImage->numCols, sf->inImage->numRows);
    254257    }
    255258    sf->outImage->header = (psMetadata*) psMemIncrRefCounter(sf->inImage->header);
     
    264267    if (sf->inImage->image) {
    265268        setupImageRefs(sf->outImage, sf->recImage, sf->inImage, sf->extnum, exciseAll);
     269    } else if (sf->inImage->imagecube) {
     270        // Image cubes should have been excised in the destreaking process
     271        streaksExit("unexpected imagecube found", PS_EXIT_CONFIG_ERROR);
    266272    }  else {
    267         // Image cubes are handeled specially
     273        return false;
    268274    }
    269275
     
    285291    if (sf->inMask) {
    286292        readImage(sf->inMask, sf->extnum, sf->stage, true);
    287         sf->outMask->header = (psMetadata*) psMemIncrRefCounter(sf->inMask->header);
    288         if (sf->recMask) {
    289             sf->recMask->header = (psMetadata*) psMemIncrRefCounter(sf->inMask->header);
    290         }
    291         setupImageRefs(sf->outMask, sf->recMask, sf->inMask, sf->extnum, exciseAll);
    292         if (sf->outChMask) {
    293             sf->outChMask->header = (psMetadata *) psMemIncrRefCounter(sf->outMask->header);
    294             sf->outChMask->image = (psImage *) psMemIncrRefCounter(sf->outMask->image);
    295             if (sf->recChMask) {
    296                 sf->recChMask->header = (psMetadata *) psMemIncrRefCounter(sf->recMask->header);
    297                 sf->recChMask->image = (psImage *) psMemIncrRefCounter(sf->recMask->image);
    298             }
    299         }
     293        if (sf->outMask) {
     294            sf->outMask->header = (psMetadata*) psMemIncrRefCounter(sf->inMask->header);
     295            if (sf->recMask) {
     296                sf->recMask->header = (psMetadata*) psMemIncrRefCounter(sf->inMask->header);
     297            }
     298            setupImageRefs(sf->outMask, sf->recMask, sf->inMask, sf->extnum, exciseAll);
     299            if (sf->outChMask) {
     300                sf->outChMask->header = (psMetadata *) psMemIncrRefCounter(sf->outMask->header);
     301                sf->outChMask->image = (psImage *) psMemIncrRefCounter(sf->outMask->image);
     302                if (sf->recChMask) {
     303                    sf->recChMask->header = (psMetadata *) psMemIncrRefCounter(sf->recMask->header);
     304                    sf->recChMask->image = (psImage *) psMemIncrRefCounter(sf->recMask->image);
     305                }
     306            }
    300307
    301308#ifdef STREAKS_COMPRESS_OUTPUT
    302         // XXX: see note above
    303         copyFitsOptions(sf->outMask, sf->recMask, sf->inMask);
    304         psFitsSetCompression(sf->outMask->fits, PS_FITS_COMPRESS_PLIO, sf->tiles, 8, 0, 0);
    305         if (sf->recMask) {
    306             psFitsSetCompression(sf->recMask->fits, PS_FITS_COMPRESS_PLIO, sf->tiles, 8, 0, 0);
    307         }
    308         if (sf->outChMask) {
    309             copyFitsOptions(sf->outChMask, sf->recChMask, sf->inMask);
    310             psFitsSetCompression(sf->outChMask->fits, PS_FITS_COMPRESS_PLIO, sf->tiles, 8, 0, 0);
    311             if (sf->recChMask) {
    312                 psFitsSetCompression(sf->recChMask->fits, PS_FITS_COMPRESS_PLIO, sf->tiles, 8, 0, 0);
    313             }
    314         }
     309            // XXX: see note above
     310            copyFitsOptions(sf->outMask, sf->recMask, sf->inMask);
     311            psFitsSetCompression(sf->outMask->fits, PS_FITS_COMPRESS_PLIO, sf->tiles, 8, 0, 0);
     312            if (sf->recMask) {
     313                psFitsSetCompression(sf->recMask->fits, PS_FITS_COMPRESS_PLIO, sf->tiles, 8, 0, 0);
     314            }
     315            if (sf->outChMask) {
     316                copyFitsOptions(sf->outChMask, sf->recChMask, sf->inMask);
     317                psFitsSetCompression(sf->outChMask->fits, PS_FITS_COMPRESS_PLIO, sf->tiles, 8, 0, 0);
     318                if (sf->recChMask) {
     319                    psFitsSetCompression(sf->recChMask->fits, PS_FITS_COMPRESS_PLIO, sf->tiles, 8, 0, 0);
     320                }
     321            }
    315322#endif
     323        }
    316324    }
    317325
     
    396404    }
    397405}
    398 
    399 // for any of the outputs that are stored in Nebulous set their extended attributes
    400 // and replicate the files
    401 
    402 static bool
    403 replicateOutputs(streakFiles *sfiles)
    404 {
    405     bool status = false;
    406 
    407     // XXX: TODO: need a nebGetXatrr function, but there isn't one
    408     // another option would be to take the number of copies to be
    409     // created as an option. That way the system could decide
    410     // whether to replicate anything other than raw Image files
    411     void *xattr = NULL;
    412 
    413     if (!replicate(sfiles->outImage, xattr)) {
    414         psError(PM_ERR_SYS, false, "failed to replicate outImage.");
    415         return false;
    416     }
    417 
    418 #ifdef notyet
    419     // XXX: don't replicate mask and weight images until we can look up
    420     // the input's xattr. There may be a perl program that can getXattr
    421     if (sfiles->outMask) {
    422         // get xattr from input to see if we need to replicate
    423         if (!replicate(sfiles->outMask, xattr)) {
    424             psError(PM_ERR_SYS, false, "failed to replicate outImage.");
    425             return false;
    426         }
    427     }
    428     if (sfiles->outWeight) {
    429         // get xattr from input to see if we need to replicate
    430         if (!replicate(sfiles->outWeight, xattr)) {
    431             psError(PM_ERR_SYS, false, "failed to replicate outImage.");
    432             return false;
    433         }
    434     }
    435 #endif
    436 
    437     return true;
    438 }
    439 
    440 
  • branches/cnb_branches/cnb_branch_20090301/magic/remove/src/streaksreplace.c

    r21156 r23352  
    44static bool readAndCopyToOutput(streakFiles *sf, bool restoreImageCube);
    55static void writeImages(streakFiles *sf, bool exciseImageCube);
    6 static bool replicateOutputs(streakFiles *sfiles);
    76static bool readAndCopyToOutput(streakFiles *sf, bool restoreImageCube);
    87
     
    9291    closeImages(sfiles);
    9392
    94     // NOTE: from here on we can't just quit if something goes wrong.
    95     // especially if we're working at the raw stage
    96 
    9793    if (!replicateOutputs(sfiles)) {
    9894        psError(PS_ERR_UNKNOWN, false, "failed to replicate output files");
     
    429425    }
    430426}
    431 
    432 static bool replicateOutputs(streakFiles *sfiles)
    433 {
    434     bool status = false;
    435 
    436     // XXX: TODO: need a nebGetXatrr function, but there isn't one
    437     // another option would be to take the number of copies to be
    438     // created as an option. That way the system could decide
    439     // whether to replicate anything other than raw Image files
    440     void *xattr = NULL;
    441 
    442     if (!replicate(sfiles->outImage, xattr)) {
    443         psError(PM_ERR_SYS, false, "failed to replicate outImage.");
    444         return false;
    445     }
    446 
    447 #ifdef notyet
    448     // XXX: don't replicate mask and weight images until we can look up
    449     // the input's xattr. There may be a perl program that can getXattr
    450     if (sfiles->outMask) {
    451         // get xattr from input to see if we need to replicate
    452         if (!replicate(sfiles->outMask, xattr)) {
    453             psError(PM_ERR_SYS, false, "failed to replicate outImage.");
    454             return false;
    455         }
    456     }
    457     if (sfiles->outWeight) {
    458         // get xattr from input to see if we need to replicate
    459         if (!replicate(sfiles->outWeight, xattr)) {
    460             psError(PM_ERR_SYS, false, "failed to replicate outImage.");
    461             return false;
    462         }
    463     }
    464 #endif
    465 
    466 //      replicate the recovery images (if in nebulous)
    467 //      perhaps whether we do that or not should be configurable.
    468 //      Sounds like we need a recipe
    469 
    470     return true;
    471 }
    472 
  • branches/cnb_branches/cnb_branch_20090301/ppArith/src/Makefile.am

    r15571 r23352  
    11bin_PROGRAMS = ppArith
    2 ppArith_CPPFLAGS = $(PSLIB_CFLAGS) $(PSMODULE_CFLAGS) $(PPSTATS_CFLAGS) $(PSPHOT_CFLAGS) $(PPARITH_CFLAGS)
     2
     3# PPARITH_VERSION=`if [ -e ../../VERSION ]; then cat ../../VERSION; else svnversion; fi`
     4# PPARITH_BRANCH=`if [ -e ../../BRANCH ]; then cat ../../BRANCH; else svn info | sed -n -e '/URL:/ h' -e '/Repository Root:/ { x; H; x; s|Repository Root: \(.*\)\nURL: \1\(.*\)|\2| ; s|^/|| ; s|/[a-zA-Z]*/src.*|| ; p }'; fi`
     5# PPARITH_SOURCE=`if [ -e ../../SOURCE ]; then cat ../../SOURCE; else svn info | sed -n -e 's/Repository UUID: // p'; fi`
     6#
     7# # Force recompilation of ppArithVersion.c, since it gets the version information
     8# ppArithVersion.c: FORCE
     9#       touch ppArith.c
     10# FORCE: ;
     11
     12ppArith_CPPFLAGS = $(PSLIB_CFLAGS) $(PSMODULE_CFLAGS) $(PPSTATS_CFLAGS) $(PSPHOT_CFLAGS) $(PPARITH_CFLAGS) -DPPARITH_VERSION=$(SVN_VERSION) -DPPARITH_BRANCH=$(SVN_BRANCH) -DPPARITH_SOURCE=$(SVN_SOURCE)
    313ppArith_LDFLAGS  = $(PSLIB_LIBS)   $(PSMODULE_LIBS)   $(PPSTATS_LIBS)   $(PSPHOT_LIBS)   $(PPARITH_LIBS)
    414
  • branches/cnb_branches/cnb_branch_20090301/ppArith/src/ppArith.c

    r21378 r23352  
    3434    }
    3535
     36    ppArithVersionPrint();
     37
    3638    if (!ppArithArguments(argc, argv, config)) {
    3739        psErrorStackPrint(stderr, "Error reading arguments.\n");
  • branches/cnb_branches/cnb_branch_20090301/ppArith/src/ppArith.h

    r21244 r23352  
    2222 * Parse the arguments
    2323 */
    24 bool ppArithArguments(int argc, char *argv[], ///< Command-line arguments 
    25                       pmConfig *config    ///< Configuration 
     24bool ppArithArguments(int argc, char *argv[], ///< Command-line arguments
     25                      pmConfig *config    ///< Configuration
    2626    );
    2727
     
    2929 * Parse the camera input
    3030 */
    31 bool ppArithCamera(pmConfig *config       ///< Configuration 
     31bool ppArithCamera(pmConfig *config       ///< Configuration
    3232    );
    3333
     
    3535 * Loop over the FPA hierarchy
    3636 */
    37 bool ppArithLoop(pmConfig *config         ///< Configuration 
     37bool ppArithLoop(pmConfig *config         ///< Configuration
    3838    );
    3939
     
    4141 * Perform arithmetic on the readout
    4242 */
    43 bool ppArithReadout(pmReadout *output,  ///< Output readout 
    44                     const pmReadout *input1, ///< Input readout 
    45                     const pmReadout *input2, ///< Input readout 
    46                     const pmConfig *config, ///< Configuration 
    47                     const pmFPAview *view ///< View of readout on which to operate 
     43bool ppArithReadout(pmReadout *output,  ///< Output readout
     44                    const pmReadout *input1, ///< Input readout
     45                    const pmReadout *input2, ///< Input readout
     46                    const pmConfig *config, ///< Configuration
     47                    const pmFPAview *view ///< View of readout on which to operate
    4848    );
    4949
    5050/**
    51  * Put the program version information into a metadata
     51 * Put the program version information into header
    5252 */
    53 void ppArithVersionMetadata(psMetadata *metadata ///< Metadata to populate
     53bool ppArithVersionHeader(psMetadata *header ///< Header to populate
    5454    );
     55
     56/// Print version information
     57void ppArithVersionPrint(void);
    5558
    5659///@}
  • branches/cnb_branches/cnb_branch_20090301/ppArith/src/ppArithLoop.c

    r21378 r23352  
    113113                    hdu->header = psMetadataAlloc();
    114114                }
    115                 ppArithVersionMetadata(hdu->header);
     115                ppArithVersionHeader(hdu->header);
    116116                lastHDU = hdu;
    117117            }
  • branches/cnb_branches/cnb_branch_20090301/ppArith/src/ppArithVersion.c

    r21378 r23352  
    2222#include "ppArith.h"
    2323
    24 static const char *cvsTag = "$Name: not supported by cvs2svn $";///< CVS tag name
     24#ifndef PPARITH_VERSION
     25#error "PPARITH_VERSION is not set"
     26#endif
     27#ifndef PPARITH_BRANCH
     28#error "PPARITH_BRANCH is not set"
     29#endif
     30#ifndef PPARITH_SOURCE
     31#error "PPARITH_SOURCE is not set"
     32#endif
     33
     34#define xstr(s) str(s)
     35#define str(s) #s
    2536
    2637psString ppArithVersion(void)
    2738{
    28     psString version = NULL;            // Version, to return
    29     psStringAppend(&version, "%s-%s",PACKAGE_NAME,PACKAGE_VERSION);
    30     return version;
     39    char *value = NULL;
     40    psStringAppend(&value, "%s@%s", xstr(PPARITH_BRANCH), xstr(PPARITH_VERSION));
     41    return value;
     42}
     43
     44psString ppArithSource(void)
     45{
     46    return psStringCopy(xstr(PPARITH_SOURCE));
    3147}
    3248
    3349psString ppArithVersionLong(void)
    3450{
    35     psString version = ppArithVersion(); // Version, to return
    36     psString tag = psStringStripCVS(cvsTag, "Name"); // CVS tag
    37     psStringAppend(&version, " (cvs tag %s) %s, %s", tag, __DATE__, __TIME__);
    38     psFree(tag);
     51    psString version = ppArithVersion();  // Version, to return
     52    psString source = ppArithSource();    // Source
     53
     54    psStringPrepend(&version, "ppArith ");
     55    psStringAppend(&version, " from %s, built %s, %s", source, __DATE__, __TIME__);
     56    psFree(source);
     57
     58#ifdef __OPTIMIZE__
     59    psStringAppend(&version, " optimised");
     60#else
     61    psStringAppend(&version, " unoptimised");
     62#endif
     63
    3964    return version;
     65};
     66
     67bool ppArithVersionHeader(psMetadata *header)
     68{
     69    PS_ASSERT_METADATA_NON_NULL(header, false);
     70
     71    psTime *time = psTimeGetNow(PS_TIME_TAI); // The time now
     72    psString timeString = psTimeToISO(time); // The time in an ISO string
     73    psFree(time);
     74    psString history = NULL;               // History string
     75    psStringAppend(&history, "ppArith at %s", timeString);
     76    psFree(timeString);
     77    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, history);
     78    psFree(history);
     79
     80    psLibVersionHeader(header);
     81    psModulesVersionHeader(header);
     82    ppStatsVersionHeader(header);
     83
     84    psString version = ppArithVersion(); // Software version
     85    psString source  = ppArithSource();  // Software source
     86
     87    psStringPrepend(&version, "ppArith version: ");
     88    psStringPrepend(&version, "ppArith source: ");
     89
     90    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, version);
     91    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, source);
     92
     93    psFree(version);
     94    psFree(source);
     95
     96    return true;
    4097}
    4198
    42 
    43 void ppArithVersionMetadata(psMetadata *metadata)
     99void ppArithVersionPrint(void)
    44100{
    45     PS_ASSERT_METADATA_NON_NULL(metadata,);
     101    psTime *time = psTimeGetNow(PS_TIME_TAI); // The time now
     102    psString timeString = psTimeToISO(time); // The time in an ISO string
     103    psFree(time);
     104    psLogMsg("ppArith", PS_LOG_INFO, "ppArith at %s", timeString);
     105    psFree(timeString);
    46106
    47107    psString pslib = psLibVersionLong();// psLib version
     
    50110    psString ppArith = ppArithVersionLong(); // ppArith version
    51111
    52     psTime *time = psTimeGetNow(PS_TIME_TAI); // The time now
    53     psString timeString = psTimeToISO(time); // The time in an ISO string
    54     psFree(time);
    55     psString head = NULL;               // Head string
    56     psStringAppend(&head, "ppArith processing at %s. Component information:", timeString);
    57     psFree(timeString);
     112    psLogMsg("ppArith", PS_LOG_INFO, "%s", pslib);
     113    psLogMsg("ppArith", PS_LOG_INFO, "%s", psmodules);
     114    psLogMsg("ppArith", PS_LOG_INFO, "%s", ppStats);
     115    psLogMsg("ppArith", PS_LOG_INFO, "%s", ppArith);
    58116
    59     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, head, "");
    60     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, pslib, "");
    61     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, psmodules, "");
    62     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, ppStats, "");
    63     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, ppArith, "");
    64 
    65     psFree(head);
    66117    psFree(pslib);
    67118    psFree(psmodules);
  • branches/cnb_branches/cnb_branch_20090301/ppImage

  • branches/cnb_branches/cnb_branch_20090301/ppImage/src/Makefile.am

    r20774 r23352  
    44        ppImage.h
    55
    6 ppImage_CFLAGS = $(PPIMAGE_CFLAGS) $(PPSTATS_CFLAGS) $(PSASTRO_CFLAGS) $(PSPHOT_CFLAGS) $(PSMODULE_CFLAGS) $(PSLIB_CFLAGS)
     6#PPIMAGE_VERSION=`if [ -e ../../VERSION ]; then cat ../../VERSION; else svnversion; fi`
     7#PPIMAGE_BRANCH=`if [ -e ../../BRANCH ]; then cat ../../BRANCH; else svn info | sed -n -e '/URL:/ h' -e '/Repository Root:/ { x; H; x; s|Repository Root: \(.*\)\nURL: \1\(.*\)|\2| ; s|^/|| ; s|/[a-zA-Z]*/src.*|| ; p }'; fi`
     8#PPIMAGE_SOURCE=`if [ -e ../../SOURCE ]; then cat ../../SOURCE; else svn info | sed -n -e 's/Repository UUID: // p'; fi`
     9
     10# Force recompilation of ppImageVersion.c, since it gets the version information
     11# ppImageVersion.c: FORCE
     12#       touch ppImageVersion.c
     13# FORCE: ;
     14
     15ppImage_CFLAGS = $(PPIMAGE_CFLAGS) $(PPSTATS_CFLAGS) $(PSASTRO_CFLAGS) $(PSPHOT_CFLAGS) $(PSMODULE_CFLAGS) $(PSLIB_CFLAGS) -DPPIMAGE_VERSION=$(SVN_VERSION) -DPPIMAGE_BRANCH=$(SVN_BRANCH) -DPPIMAGE_SOURCE=$(SVN_SOURCE)
    716ppImage_LDFLAGS = $(PPIMAGE_LIBS) $(PSASTRO_LIBS) $(PPSTATS_LIBS) $(PSPHOT_LIBS) $(PSMODULE_LIBS) $(PSLIB_LIBS)
    817ppImage_SOURCES = \
  • branches/cnb_branches/cnb_branch_20090301/ppImage/src/ppImage.c

    r19928 r23352  
    2121        exit(PS_EXIT_CONFIG_ERROR);
    2222    }
     23
     24    ppImageVersionPrint();
    2325
    2426    // define recipe options
  • branches/cnb_branches/cnb_branch_20090301/ppImage/src/ppImage.h

    r21364 r23352  
    8686    int remnanceSize;                   // Size for remnance detection
    8787    float remnanceThresh;               // Threshold for remnance detection
     88
     89    char *normClass;                    // class to use for per-class normalization
    8890} ppImageOptions;
    8991
     
    208210psString ppImageVersion(void);
    209211
     212/// Return software source
     213psString ppImageSource(void);
     214
    210215/// Return long version information
    211216psString ppImageVersionLong(void);
    212217
    213 /// Update the metadata with version information for all dependencies
    214 void ppImageVersionMetadata(psMetadata *metadata ///< Metadata to update with version information
    215     );
     218/// Populate the header with version information for all dependencies
     219bool ppImageVersionHeader(psMetadata *metadata ///< Header to populate
     220    );
     221
     222/// Print version information
     223void ppImageVersionPrint(void);
    216224
    217225
  • branches/cnb_branches/cnb_branch_20090301/ppImage/src/ppImageArguments.c

    r19943 r23352  
    1414    fprintf(stderr, "\t-chip CHIPNUM: Only process this chip number.\n");
    1515    fprintf(stderr, "\t-norm VALUE: Divide through by this value when done.\n");
     16    fprintf(stderr, "\t-normlist file.mdc: normalizations by class_id.\n");
    1617    fprintf(stderr, "\n");
    1718    fprintf(stderr, "Input options (single file / file list):\n");
     
    8081    if ((argnum = psArgumentGet(argc, argv, "-visual"))) {
    8182        psArgumentRemove(argnum, &argc, argv);
    82         psphotSetVisual (true);
     83        pmVisualSetVisual(true);
    8384    }
    8485
     
    8687    if ((argnum = psArgumentGet(argc, argv, "-threads"))) {
    8788        psArgumentRemove(argnum, &argc, argv);
    88         int nThreads = atoi(argv[argnum]);
     89        int nThreads = atoi(argv[argnum]);
    8990        psMetadataAddS32(config->arguments, PS_LIST_TAIL, "NTHREADS", 0, "number of warp threads", nThreads);
    9091        psArgumentRemove(argnum, &argc, argv);
    9192
    92         // create the thread pool with number of desired threads, supplying our thread launcher function
    93         // XXX need to determine the number of threads from the config data
    94         psThreadPoolInit (nThreads);
     93        // create the thread pool with number of desired threads, supplying our thread launcher function
     94        // XXX need to determine the number of threads from the config data
     95        psThreadPoolInit (nThreads);
    9596    }
    9697
     
    107108
    108109    // the input file is a required argument; if not found, we will exit
    109     bool status = pmConfigFileSetsMD (config->arguments, &argc, argv, "INPUT", "-file", "-list");
    110     if (!status) {
    111         usage ();
    112     }
     110    pmConfigFileSetsMD (config->arguments, &argc, argv, "INPUT", "-file", "-list");
    113111
    114112    // if these command-line options are supplied, load the file name lists into config->arguments
     
    128126    }
    129127
    130     // Optional normalisation factor
     128    // Optional normalization factor
    131129    if ((argnum = psArgumentGet(argc, argv, "-norm"))) {
    132130        psArgumentRemove(argnum, &argc, argv);
    133131        float norm = atof(argv[argnum]);
    134         psMetadataAddF32(config->arguments, PS_LIST_TAIL, "NORMALISATION", 0,
     132        psMetadataAddF32(config->arguments, PS_LIST_TAIL, "NORMALIZATION", 0,
    135133                         "Normalisation to apply", norm);
     134        psArgumentRemove(argnum, &argc, argv);
     135    }
     136
     137    // Optional per-class normalization table
     138    if ((argnum = psArgumentGet(argc, argv, "-normlist"))) {
     139        psArgumentRemove(argnum, &argc, argv);
     140
     141        unsigned int nFail = 0;
     142        psMetadata *normlist = psMetadataConfigRead (NULL, &nFail, argv[argnum], false);
     143        // XXX allow this file to be in nebulous?
     144
     145        psMetadataAddMetadata(config->arguments, PS_LIST_TAIL, "NORMALIZATION.TABLE", 0, "Normalization to apply", normlist);
     146        psFree (normlist);
    136147        psArgumentRemove(argnum, &argc, argv);
    137148    }
  • branches/cnb_branches/cnb_branch_20090301/ppImage/src/ppImageDefineFile.c

    r13562 r23352  
    55# include "ppImage.h"
    66
    7 bool ppImageDefineFile (pmConfig *config, pmFPA *input, char *filerule, char *argname, pmFPAfileType fileType, pmDetrendType detrendType) {
     7bool ppImageDefineFile(pmConfig *config, pmFPA *input, char *filerule, char *argname,
     8                       pmFPAfileType fileType, pmDetrendType detrendType)
     9{
     10    bool status;
     11    pmFPAfile *file = NULL;             // File to be defined
    812
    9     bool status;
    10     pmFPAfile *file;
    11 
    12     // look for the file on the argument list
    13     file = pmFPAfileDefineFromArgs  (&status, config, filerule, argname);
    14     if (!status) {
    15         psError (PS_ERR_UNKNOWN, false, "failed to load find definition");
    16         return false;
     13    if (!file) {
     14        // look for the file on the RUN metadata
     15        file = pmFPAfileDefineFromRun(&status, config, filerule);
     16        if (!status) {
     17            psError(PS_ERR_UNKNOWN, false, "failed to load file definition");
     18            return false;
     19        }
    1720    }
    18     if (file) {
    19         if (file->type != fileType) {
    20             psError(PS_ERR_IO, true, "%s is not of type %s", filerule, pmFPAfileStringFromType (fileType));
    21             return false;
    22         }
    23         return true;
     21    if (!file) {
     22        // look for the file on the argument list
     23        file = pmFPAfileDefineFromArgs(&status, config, filerule, argname);
     24        if (!status) {
     25            psError(PS_ERR_UNKNOWN, false, "failed to load file definition");
     26            return false;
     27        }
     28    }
     29    if (!file) {
     30        // look for the file in the camera config table
     31        file = pmFPAfileDefineFromConf(&status, config, filerule);
     32        if (!status) {
     33            psError(PS_ERR_UNKNOWN, false, "failed to load file definition");
     34            return false;
     35        }
     36    }
     37    if (!file) {
     38        // look for the file to be loaded from the detrend database
     39        file = pmFPAfileDefineFromDetDB(&status, config, filerule, input, detrendType);
     40        if (!status) {
     41            psError(PS_ERR_UNKNOWN, false, "failed to load file definition");
     42            return false;
     43        }
    2444    }
    2545
    26     // look for the file in the camera config table
    27     file = pmFPAfileDefineFromConf  (&status, config, filerule);
    28     if (!status) {
    29         psError (PS_ERR_UNKNOWN, false, "failed to load find definition");
    30         return false;
    31     }
    32     if (file) {
    33         if (file->type != fileType) {
    34             psError(PS_ERR_IO, true, "%s is not of type %s", filerule, pmFPAfileStringFromType (fileType));
    35             return false;
    36         }
    37         return true;
     46    if (!file) {
     47        return false;
    3848    }
    3949
    40     // look for the file to be loaded from the detrend database
    41     file = pmFPAfileDefineFromDetDB (&status, config, filerule, input, detrendType);
    42     if (!status) {
    43         psError (PS_ERR_UNKNOWN, false, "failed to load file definition");
    44         return false;
     50    if (file->type != fileType) {
     51        psError(PS_ERR_IO, true, "%s is not of type %s", filerule, pmFPAfileStringFromType(fileType));
     52        return false;
    4553    }
    46     if (file) {
    47         if (file->type != fileType) {
    48             psError(PS_ERR_IO, true, "%s is not of type %s", filerule, pmFPAfileStringFromType (fileType));
    49             return false;
    50         }
    51         return true;
    52     }
    53     return false;
     54    return true;
    5455}
    5556
  • branches/cnb_branches/cnb_branch_20090301/ppImage/src/ppImageDetrendReadout.c

    r21364 r23352  
    5454        if (!pmBiasSubtract(input, options->overscan, bias, oldDark, view)) {
    5555            psError(PS_ERR_UNKNOWN, false, "Unable to subtract bias.");
     56            psFree(detview);
    5657            return false;
    5758        }
     
    6768        if (!pmDarkApply(input, dark, options->maskValue)) {
    6869            psError(PS_ERR_UNKNOWN, false, "Unable to subtract dark.");
     70            psFree(detview);
    6971            return false;
    7072        }
     
    7577                        options->remnanceSize, options->remnanceThresh)) {
    7678            psError(PS_ERR_UNKNOWN, false, "Unable to mask remnance.");
     79            psFree(detview);
    7780            return false;
    7881        }
     
    8386        pmReadout *shutter = pmFPAfileThisReadout(config->files, detview, "PPIMAGE.SHUTTER");
    8487        if (!pmShutterCorrectionApply(input, shutter, pmConfigMaskGet("FLAT", config))) {
     88            psFree(detview);
    8589            return false;
    8690        }
     
    9195        pmReadout *flat = pmFPAfileThisReadout(config->files, detview, "PPIMAGE.FLAT");
    9296        if (!pmFlatField(input, flat, options->flatMask)) {
     97            psFree(detview);
    9398            return false;
    9499        }
    95100    }
    96101
    97     // Normalisation by a (known) constant
     102    // Normalization by a single (known) constant
    98103    bool mdok;                          // Status of MD lookup
    99     float norm = psMetadataLookupF32(&mdok, config->arguments, "NORMALISATION");
     104    float norm = psMetadataLookupF32(&mdok, config->arguments, "NORMALIZATION");
    100105    if (mdok && isfinite(norm) && norm != 1.0) {
    101106        pmHDU *hdu = pmHDUFromReadout(input); // HDU of interest
     
    108113    }
    109114
     115# if (1)
     116    // Normalization by per-class values
     117    psMetadata *normlist = psMetadataLookupMetadata(&mdok, config->arguments, "NORMALIZATION.TABLE");
     118    if (normlist) {
     119        pmFPAfile *inputFile = psMetadataLookupPtr(&mdok, config->files, "PPIMAGE.INPUT");
     120
     121        // get the menu of class IDs
     122        psMetadata *menu = psMetadataLookupMetadata(&mdok, inputFile->camera, "CLASSID");
     123        if (!menu) {
     124            psError(PS_ERR_IO, false, "Unable to find CLASSID metadata in camera configuration");
     125            psFree(detview);
     126            return false;
     127        }
     128        // get the rule for class_id for the desired class
     129        const char *rule = psMetadataLookupStr(&mdok, menu, options->normClass);
     130        if (!rule) {
     131            psError(PS_ERR_IO, false, "Unable to find NORM.CLASS value %s in CLASSID in camera configuration", options->normClass);
     132            psFree(detview);
     133            return false;
     134        }
     135        // get the class_id from the rule
     136        char *classID = pmFPAfileNameFromRule(rule, inputFile, view);
     137        if (!classID) {
     138            psError(PS_ERR_IO, false, "error converting CLASSID rule %s to name\n", rule);
     139            psFree(detview);
     140            return false;
     141        }
     142
     143        // get normalization from the class_id
     144        float norm = psMetadataLookupF32 (&mdok, normlist, classID);
     145
     146        pmHDU *hdu = pmHDUFromReadout(input); // HDU of interest
     147        psString comment = NULL;        // Comment to add
     148        psStringAppend(&comment, "Normalization: %f", norm);
     149        psMetadataAddStr(hdu->header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, comment, "");
     150        psFree(comment);
     151
     152        // apply the normalization
     153        psBinaryOp(input->image, input->image, "*", psScalarAlloc(norm, PS_TYPE_F32));
     154
     155        psFree (classID);
     156    }
     157# endif
     158
    110159    if (options->doFringe) {
    111160        pmCell *fringe = pmFPAfileThisCell(config->files, detview, "PPIMAGE.FRINGE");
    112161        if (!ppImageDetrendFringeMeasure(input, fringe, false, options)) {
     162            psFree(detview);
    113163            return false;
    114164        }
  • branches/cnb_branches/cnb_branch_20090301/ppImage/src/ppImageLoop.c

    r21183 r23352  
    2525    }
    2626
    27     psString dump_file = psMetadataLookupStr(&status, config->arguments, "DUMP_CONFIG");
    28     if (dump_file) {
    29         pmConfigCamerasCull(config, NULL);
    30         pmConfigRecipesCull(config, "PPIMAGE,PPSTATS,PSPHOT,MASKS,PSASTRO");
    31 
    32         pmConfigDump(config, input->fpa, dump_file);
    33     }
     27    pmConfigCamerasCull(config, NULL);
     28    pmConfigRecipesCull(config, "PPIMAGE,PPSTATS,PSPHOT,MASKS,PSASTRO,JPEG");
    3429
    3530    pmFPAview *view = pmFPAviewAlloc(0);// View for level of interest
     
    6358
    6459            // Put version information into the header
    65             pmHDU *hdu = pmHDUFromCell(cell);
     60            pmHDU *hdu = pmHDUGetHighest(input->fpa, chip, cell);
    6661            if (hdu && hdu != lastHDU) {
    67                 ppImageVersionMetadata(hdu->header);
     62                ppImageVersionHeader(hdu->header);
    6863                lastHDU = hdu;
    6964            }
     
    9691                }
    9792
    98                 // free detrend images potentially in use: MASK, BIAS, DARK, SHUTTER, FLAT
    99                 if (!ppImageDetrendFree (config, view)) {
    100                     ESCAPE("Unable to free detrend images");
    101                 }
     93                // free detrend images potentially in use: MASK, BIAS, DARK, SHUTTER, FLAT
     94                if (!ppImageDetrendFree (config, view)) {
     95                    ESCAPE("Unable to free detrend images");
     96                }
    10297            }
    10398
     
    105100                ppImageDetrendRecord(cell, config, options, view);
    106101            }
    107             // free detrend images potentially in use: MASK, BIAS, DARK, SHUTTER, FLAT
    108             if (!ppImageDetrendFree (config, view)) {
    109                 ESCAPE("Unable to free detrend images");
    110             }
    111         }
    112         // free detrend images potentially in use: MASK, BIAS, DARK, SHUTTER, FLAT
    113         if (!ppImageDetrendFree (config, view)) {
    114             ESCAPE("Unable to free detrend images");
    115         }
     102            // free detrend images potentially in use: MASK, BIAS, DARK, SHUTTER, FLAT
     103            if (!ppImageDetrendFree (config, view)) {
     104                ESCAPE("Unable to free detrend images");
     105            }
     106        }
     107        // free detrend images potentially in use: MASK, BIAS, DARK, SHUTTER, FLAT
     108        if (!ppImageDetrendFree (config, view)) {
     109            ESCAPE("Unable to free detrend images");
     110        }
    116111
    117112        // Apply the fringe correction
     
    121116            }
    122117        }
    123         // free detrend images potentially in use: MASK, BIAS, DARK, SHUTTER, FLAT
    124         if (!ppImageFringeFree (config, view)) {
    125             ESCAPE("Unable to free fringe images");
    126         }
     118        // free detrend images potentially in use: MASK, BIAS, DARK, SHUTTER, FLAT
     119        if (!ppImageFringeFree (config, view)) {
     120            ESCAPE("Unable to free fringe images");
     121        }
    127122
    128123        // measure various pixel-based statistics for this image
     
    152147        }
    153148
    154         // these may be used by ppImageSubtractBackground.
    155         // if these are defined as internal files, drop them here
    156         status = true;
    157         status &= pmFPAfileDropInternal (config->files, "PSPHOT.BACKMDL");
    158         status &= pmFPAfileDropInternal (config->files, "PSPHOT.BACKMDL.STDEV");
    159         status &= pmFPAfileDropInternal (config->files, "PSPHOT.BACKGND");
    160         if (!status) {
    161             psError(PSPHOT_ERR_PROG, false, "trouble dropping internal files");
    162             psFree (view);
    163             return false;
    164         }
     149        // these may be used by ppImageSubtractBackground.
     150        // if these are defined as internal files, drop them here
     151        status = true;
     152        status &= pmFPAfileDropInternal (config->files, "PSPHOT.BACKMDL");
     153        status &= pmFPAfileDropInternal (config->files, "PSPHOT.BACKMDL.STDEV");
     154        status &= pmFPAfileDropInternal (config->files, "PSPHOT.BACKGND");
     155        if (!status) {
     156            psError(PSPHOT_ERR_PROG, false, "trouble dropping internal files");
     157            psFree (view);
     158            return false;
     159        }
    165160
    166161        // binning (used for display) must take place after the background is replaced, if desired
     
    219214    }
    220215    psFree(view);
     216
     217    // Dump configuration
     218    psString dump_file = psMetadataLookupStr(&status, config->arguments, "DUMP_CONFIG");
     219    if (dump_file) {
     220        pmConfigDump(config, input->fpa, dump_file);
     221    }
    221222
    222223    // Write out summary statistics
  • branches/cnb_branches/cnb_branch_20090301/ppImage/src/ppImageOptions.c

    r21364 r23352  
    8181    options->remnanceThresh  = 25.0;    // Threshold for remnance detection
    8282
     83    // per-class normalization source
     84    options->normClass       = NULL;    // per-class normalizations refer to this class
     85
    8386    return options;
    8487}
     
    278281    options->remnanceThresh = psMetadataLookupS32(NULL, recipe, "REMNANCE.THRESH");
    279282
     283    // per-class normalization source (just a reference; don't free)
     284    options->normClass = psMetadataLookupStr(NULL, recipe, "NORM.CLASS");
     285
    280286    return options;
    281287}
  • branches/cnb_branches/cnb_branch_20090301/ppImage/src/ppImageParseCamera.c

    r21364 r23352  
    99    bool status = false;
    1010
    11     // the input image defines the camera, and all recipes and options the follow
    12     pmFPAfile *input = pmFPAfileDefineFromArgs (&status, config, "PPIMAGE.INPUT", "INPUT");
    13     if (!status || !input) {
    14         psError(PS_ERR_IO, false, "Failed to build FPA from PPIMAGE.INPUT");
    15         return NULL;
    16     }
    17     if (input->type != PM_FPA_FILE_IMAGE) {
    18         psError(PS_ERR_IO, true, "PPIMAGE.INPUT is not of type IMAGE");
    19         return NULL;
    20     }
    21 
    22     // if MASK or VARIANCE was supplied on command line, bind files to 'input'.
    23     // the mask and variance will be mosaicked with the image
    24     pmFPAfile *inputMask = pmFPAfileBindFromArgs(&status, input, config, "PPIMAGE.INPUT.MASK", "PPIMAGE.INPUT.MASK");
    25     if (!status) {
    26         psError (PS_ERR_UNKNOWN, false, "failed to load find definition");
    27         return NULL;
    28     }
    29     if (inputMask) {
    30       if (inputMask->type != PM_FPA_FILE_MASK) {
    31         psError(PS_ERR_IO, true, "PPIMAGE.INPUT.MASK is not of type MASK");
    32         return NULL;
    33       }
    34     }
    35 
    36     pmFPAfile *inputVariance = pmFPAfileBindFromArgs(&status, input, config, "PPIMAGE.INPUT.VARIANCE", "PPIMAGE.INPUT.VARIANCE");
    37     if (!status) {
    38         psError (PS_ERR_UNKNOWN, false, "failed to load find definition");
    39         return NULL;
    40     }
    41     if (inputVariance && inputVariance->type != PM_FPA_FILE_VARIANCE) {
    42         psError(PS_ERR_IO, true, "PPIMAGE.INPUT.VARIANCE is not of type VARIANCE");
    43         return NULL;
    44     }
     11    if (!ppImageDefineFile(config, NULL, "PPIMAGE.INPUT", "INPUT", PM_FPA_FILE_IMAGE, PM_DETREND_TYPE_NONE)) {
     12        psError(PS_ERR_IO, false, "Can't find an input image source");
     13        return NULL;
     14    }
     15    pmFPAfile *input = psMetadataLookupPtr(NULL, config->files, "PPIMAGE.INPUT"); // Input file
     16    psAssert(input, "We just put it there!");
    4517
    4618    // add recipe options supplied on command line
    47     psMetadata *recipe  = psMetadataLookupPtr (&status, config->recipes, RECIPE_NAME);
     19    psMetadata *recipe  = psMetadataLookupPtr(&status, config->recipes, RECIPE_NAME);
    4820
    4921    // parse the options from the metadata format to the ppImageOptions structure
    50     ppImageOptions *options = ppImageOptionsParse (config);
     22    ppImageOptions *options = ppImageOptionsParse(config);
    5123
    5224    // the following are defined from the argument list, if given,
     
    5426    // not all input or output images are used in a given recipe
    5527    if (options->doBias) {
    56         if (!ppImageDefineFile (config, input->fpa, "PPIMAGE.BIAS", "BIAS", PM_FPA_FILE_IMAGE, PM_DETREND_TYPE_BIAS)) {
    57             psError (PS_ERR_IO, false, "Can't find a bias image source");
    58             psFree (options);
     28        if (!ppImageDefineFile(config, input->fpa, "PPIMAGE.BIAS", "BIAS",
     29                               PM_FPA_FILE_IMAGE, PM_DETREND_TYPE_BIAS)) {
     30            psError(PS_ERR_IO, false, "Can't find a bias image source");
     31            psFree(options);
    5932            return NULL;
    6033        }
    6134    }
    6235    if (options->doDark) {
    63         if (!ppImageDefineFile (config, input->fpa, "PPIMAGE.DARK", "DARK", PM_FPA_FILE_DARK, PM_DETREND_TYPE_DARK)) {
    64             psError (PS_ERR_IO, false, "Can't find a dark image source");
    65             psFree (options);
     36        if (!ppImageDefineFile(config, input->fpa, "PPIMAGE.DARK", "DARK",
     37                               PM_FPA_FILE_DARK, PM_DETREND_TYPE_DARK)) {
     38            psError(PS_ERR_IO, false, "Can't find a dark image source");
     39            psFree(options);
    6640            return NULL;
    6741        }
    6842    }
    6943    if (options->doMask) {
    70 
    71         if (!ppImageDefineFile (config, input->fpa, "PPIMAGE.MASK", "MASK", PM_FPA_FILE_MASK, PM_DETREND_TYPE_MASK)) {
    72             psError (PS_ERR_IO, false, "Can't find a mask image source");
    73             psFree (options);
    74             return NULL;
    75         }
     44        if (!ppImageDefineFile(config, input->fpa, "PPIMAGE.MASK", "MASK",
     45                               PM_FPA_FILE_MASK, PM_DETREND_TYPE_MASK)) {
     46            psError(PS_ERR_IO, false, "Can't find a mask image source");
     47            psFree(options);
     48            return NULL;
     49        }
     50
     51#if 0
     52        // I think this is now done automatically in the pmFPAfileDefine and pmFPAfileIOChecks -- PAP.
     53
    7654        // XXX have ppImageDefineFile return the pmFPAfile?
    7755        pmFPAfile *mask = psMetadataLookupPtr(&status, config->files, "PPIMAGE.MASK");
    78         psAssert (mask, "mask not defined?  not possible!");
     56        psAssert(mask, "Just defined the mask!");
    7957
    8058        // Need to read the names of bit masks from the mask header and set them in the
     
    8462            // XXX need to load the mask bit names from one of the headers
    8563            // this grabs the first available hdu : no guarantee that it will be valid, though
    86             pmHDU *hdu = pmHDUGetFirst (mask->fpa);
     64            pmHDU *hdu = pmHDUGetFirst(mask->fpa);
    8765            if (!hdu) {
    8866                psError(PS_ERR_IO, true, "no valid HDU for PPIMAGE.INPUT.MASK");
     
    9068            }
    9169            // XXX is this consistent with the pmConfigMaskReadHeader call above?
    92             if (!pmConfigMaskReadHeader (config, hdu->header)) {
     70            if (!pmConfigMaskReadHeader(config, hdu->header)) {
    9371                psError(PS_ERR_IO, false, "error in mask bits");
    9472                return NULL;
    9573            }
    9674        }
     75#endif
    9776    }
    9877    if (options->doShutter) {
    99         if (!ppImageDefineFile (config, input->fpa, "PPIMAGE.SHUTTER", "SHUTTER", PM_FPA_FILE_IMAGE, PM_DETREND_TYPE_SHUTTER)) {
    100             psError (PS_ERR_IO, false, "Can't find a shutter image source");
    101             psFree (options);
     78        if (!ppImageDefineFile(config, input->fpa, "PPIMAGE.SHUTTER", "SHUTTER",
     79                               PM_FPA_FILE_IMAGE, PM_DETREND_TYPE_SHUTTER)) {
     80            psError(PS_ERR_IO, false, "Can't find a shutter image source");
     81            psFree(options);
    10282            return NULL;
    10383        }
     
    10585
    10686    if (options->doFlat) {
    107         if (!ppImageDefineFile (config, input->fpa, "PPIMAGE.FLAT", "FLAT", PM_FPA_FILE_IMAGE, PM_DETREND_TYPE_FLAT)) {
    108             psError (PS_ERR_IO, false, "Can't find a flat image source");
    109             psFree (options);
    110             return NULL;
    111         }
    112     }
    113 
    114     int nThreads = psMetadataLookupS32 (&status, config->arguments, "NTHREADS");
     87        if (!ppImageDefineFile(config, input->fpa, "PPIMAGE.FLAT", "FLAT",
     88                               PM_FPA_FILE_IMAGE, PM_DETREND_TYPE_FLAT)) {
     89            psError(PS_ERR_IO, false, "Can't find a flat image source");
     90            psFree(options);
     91            return NULL;
     92        }
     93    }
     94
     95    int nThreads = psMetadataLookupS32(&status, config->arguments, "NTHREADS");
    11596    if (nThreads > 0) {
    116         int nScanRows = psMetadataLookupS32 (&status, recipe, "SCAN.ROWS");
    117         pmDetrendSetThreadTasks (nScanRows);
     97        int nScanRows = psMetadataLookupS32(&status, recipe, "SCAN.ROWS");
     98        pmDetrendSetThreadTasks(nScanRows);
    11899    }
    119100
     
    166147skip_fringe:
    167148    if (options->doFringe) {
    168         if (!ppImageDefineFile (config, input->fpa, "PPIMAGE.FRINGE", "FRINGE", PM_FPA_FILE_FRINGE, PM_DETREND_TYPE_FRINGE)) {
     149        if (!ppImageDefineFile(config, input->fpa, "PPIMAGE.FRINGE", "FRINGE",
     150                               PM_FPA_FILE_FRINGE, PM_DETREND_TYPE_FRINGE)) {
    169151            psError (PS_ERR_IO, false, "Can't find a fringe image source");
    170152            return NULL;
     
    283265        // define associated psphot input/output files
    284266        if (!psphotDefineFiles (config, psphotInput)) {
    285             psError(PSPHOT_ERR_CONFIG, false, "Trouble defining the additional input/output files for psphot");
     267            psError(PSPHOT_ERR_CONFIG, false,
     268                    "Trouble defining the additional input/output files for psphot");
    286269            return false;
    287270        }
     
    291274    if (options->doAstromChip || options->doAstromMosaic) {
    292275        if (!options->doPhotom) {
    293             psError (PSASTRO_ERR_CONFIG, false, "photometry mode is not selected; it is required for astrometry");
     276            psError(PSASTRO_ERR_CONFIG, false,
     277                    "Photometry mode is not selected; it is required for astrometry");
    294278            return false;
    295279        }
    296280
    297         pmFPAfile *psphotOutput = psMetadataLookupPtr (&status, config->files, "PSPHOT.OUTPUT");
    298         PS_ASSERT (psphotOutput, false);
    299 
    300         pmFPAfile *psastroInput = pmFPAfileDefineInput (config, psphotOutput->fpa, NULL, "PSASTRO.INPUT");
    301         PS_ASSERT (psastroInput, false);
     281        pmFPAfile *psphotOutput = psMetadataLookupPtr(&status, config->files, "PSPHOT.OUTPUT");
     282        PS_ASSERT(psphotOutput, false);
     283
     284        pmFPAfile *psastroInput = pmFPAfileDefineInput(config, psphotOutput->fpa, NULL, "PSASTRO.INPUT");
     285        PS_ASSERT(psastroInput, false);
    302286        psastroInput->mode = PM_FPA_MODE_REFERENCE;
    303287
    304288        // define associated psphot input/output files
    305         if (!psastroDefineFiles (config, psastroInput)) {
    306             psError(PSPHOT_ERR_CONFIG, false, "Trouble defining the additional input/output files for psastro");
     289        if (!psastroDefineFiles(config, psastroInput)) {
     290            psError(PSPHOT_ERR_CONFIG, false,
     291                    "Trouble defining the additional input/output files for psastro");
    307292            return false;
    308293        }
    309294
    310295        // deactivate the psastro files, reactive when needed
    311         pmFPAfileActivate (config->files, false, "PSASTRO.OUTPUT");
     296        pmFPAfileActivate(config->files, false, "PSASTRO.OUTPUT");
    312297    }
    313298
     
    325310
    326311    // outImage is used as a carrier: input to chipImage -> require the data to remain at the CHIP level
    327     outImage->freeLevel = PS_MIN (outImage->freeLevel, PM_FPA_LEVEL_CHIP);
     312    outImage->freeLevel = PS_MIN(outImage->freeLevel, PM_FPA_LEVEL_CHIP);
    328313    outImage->dataLevel = outImage->freeLevel;
    329     outImage->fileLevel = PS_MIN (outImage->fileLevel, outImage->dataLevel);
     314    outImage->fileLevel = PS_MIN(outImage->fileLevel, outImage->dataLevel);
    330315
    331316    // outMask and outVariance must be freed at the same level as outImage (all freed by pmFPAFreeData)
     
    342327
    343328    // the input data is the same as the outImage data : force the free levels to match
    344     input->freeLevel = PS_MIN (outImage->freeLevel, input->freeLevel);
     329    input->freeLevel = PS_MIN(outImage->freeLevel, input->freeLevel);
    345330
    346331    // define the binned target files (which may just be carriers for some camera configurations)
    347     pmFPAfile *bin1 = pmFPAfileDefineFromFPA (config, chipImage->fpa, options->xBin1, options->yBin1, "PPIMAGE.BIN1");
     332    pmFPAfile *bin1 = pmFPAfileDefineFromFPA(config, chipImage->fpa, options->xBin1, options->yBin1,
     333                                             "PPIMAGE.BIN1");
    348334    if (!bin1) {
    349335        psError(PS_ERR_IO, false, _("Unable to generate new file from PPIMAGE.BIN1"));
     
    357343    }
    358344
    359     pmFPAfile *bin2 = pmFPAfileDefineFromFPA (config, chipImage->fpa, options->xBin2, options->yBin2, "PPIMAGE.BIN2");
     345    pmFPAfile *bin2 = pmFPAfileDefineFromFPA(config, chipImage->fpa, options->xBin2, options->yBin2,
     346                                             "PPIMAGE.BIN2");
    360347    if (!bin2) {
    361348        psError(PS_ERR_IO, false, _("Unable to generate new file from PPIMAGE.BIN2"));
     
    373360    bin2->freeLevel = PM_FPA_LEVEL_FPA;
    374361
    375     pmFPAfile *jpg1 = pmFPAfileDefineOutput (config, byFPA1->fpa, "PPIMAGE.JPEG1");
     362    pmFPAfile *jpg1 = pmFPAfileDefineOutput(config, byFPA1->fpa, "PPIMAGE.JPEG1");
    376363    if (!jpg1) {
    377364        psError(PS_ERR_IO, false, _("Unable to generate new file from PPIMAGE.JPEG1"));
     
    384371        return NULL;
    385372    }
    386     pmFPAfile *jpg2 = pmFPAfileDefineOutput (config, byFPA2->fpa, "PPIMAGE.JPEG2");
     373    pmFPAfile *jpg2 = pmFPAfileDefineOutput(config, byFPA2->fpa, "PPIMAGE.JPEG2");
    387374    if (!jpg2) {
    388375        psError(PS_ERR_IO, false, _("Unable to generate new file from PPIMAGE.JPEG2"));
     
    404391    // Chip selection: turn on only the chips specified (pass status to suppress missing-key log msg)
    405392    char *chipLine = psMetadataLookupStr(&status, config->arguments, "CHIP_SELECTIONS");
    406     psArray *chips = psStringSplitArray (chipLine, ",", false);
     393    psArray *chips = psStringSplitArray(chipLine, ",", false);
    407394    if (chips->n > 0) {
    408395        pmFPASelectChip (input->fpa, -1, true); // deselect all chips
     
    454441    if (psTraceGetLevel("ppImage.config") > 0) {
    455442        // Get a look inside all the files.
    456         psMetadataIterator *filesIter = psMetadataIteratorAlloc(config->files, PS_LIST_HEAD, NULL); // Iterator
     443        psMetadataIterator *filesIter = psMetadataIteratorAlloc(config->files, PS_LIST_HEAD, NULL);
    457444        psMetadataItem *item;               // Item from iteration
    458445        fprintf(stderr, "Files:\n");
  • branches/cnb_branches/cnb_branch_20090301/ppImage/src/ppImageReplaceBackground.c

    r21183 r23352  
    101101        }
    102102    }
    103     psImageBinning *binning = psMetadataLookupPtr(&status, psphotRecipe, "PSPHOT.BACKGROUND.BINNING"); // Binning for model
     103    psImageBinning *binning = psMetadataLookupPtr(&status, modelRO->analysis,
     104                                                  "PSPHOT.BACKGROUND.BINNING"); // Binning for model
    104105    if (!binning) {
    105106        psError(PS_ERR_UNEXPECTED_NULL, true, "Unable to find background binning");
  • branches/cnb_branches/cnb_branch_20090301/ppImage/src/ppImageVersion.c

    r14000 r23352  
    55#include "ppImage.h"
    66
    7 static const char *cvsTag = "$Name: not supported by cvs2svn $";// CVS tag name
     7#ifndef PPIMAGE_VERSION
     8#error "PPIMAGE_VERSION is not set"
     9#endif
     10#ifndef PPIMAGE_BRANCH
     11#error "PPIMAGE_BRANCH is not set"
     12#endif
     13#ifndef PPIMAGE_SOURCE
     14#error "PPIMAGE_SOURCE is not set"
     15#endif
     16
     17#define xstr(s) str(s)
     18#define str(s) #s
    819
    920psString ppImageVersion(void)
    1021{
    11     psString version = NULL;            // Version, to return
    12     psStringAppend(&version, "%s-%s",PACKAGE_NAME,PACKAGE_VERSION);
    13     return version;
     22    char *value = NULL;
     23    psStringAppend(&value, "%s@%s", xstr(PPIMAGE_BRANCH), xstr(PPIMAGE_VERSION));
     24    return value;
     25}
     26
     27psString ppImageSource(void)
     28{
     29    return psStringCopy (xstr(PPIMAGE_SOURCE));
    1430}
    1531
    1632psString ppImageVersionLong(void)
    1733{
    18     psString version = ppImageVersion(); // Version, to return
    19     psString tag = psStringStripCVS(cvsTag, "Name"); // CVS tag
    20     psStringAppend(&version, " (cvs tag %s) %s, %s", tag, __DATE__, __TIME__);
    21     psFree(tag);
     34    psString version = ppImageVersion();  // Version, to return
     35    psString source = ppImageSource(); // Source
     36
     37    psStringPrepend(&version, "ppImage ");
     38    psStringAppend(&version, " from %s, built %s, %s", source, __DATE__, __TIME__);
     39    psFree(source);
     40
     41#ifdef __OPTIMIZE__
     42    psStringAppend(&version, " optimised");
     43#else
     44    psStringAppend(&version, " unoptimised");
     45#endif
     46
    2247    return version;
     48};
     49
     50bool ppImageVersionHeader(psMetadata *header)
     51{
     52    PS_ASSERT_METADATA_NON_NULL(header, false);
     53
     54    psTime *time = psTimeGetNow(PS_TIME_TAI); // The time now
     55    psString timeString = psTimeToISO(time); // The time in an ISO string
     56    psFree(time);
     57    psString history = NULL;               // History string
     58    psStringAppend(&history, "ppImage at %s", timeString);
     59    psFree(timeString);
     60    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, history);
     61    psFree(history);
     62
     63    psLibVersionHeader(header);
     64    psModulesVersionHeader(header);
     65    psphotVersionHeader(header);
     66    psastroVersionHeader(header);
     67    ppStatsVersionHeader(header);
     68
     69    psString version = ppImageVersion(); // ppImage software version
     70    psString source  = ppImageSource();  // ppImage software source
     71
     72    psStringPrepend(&version, "ppImage version: ");
     73    psStringPrepend(&source, "ppImage source: ");
     74
     75    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, version);
     76    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, source);
     77
     78    psFree(version);
     79    psFree(source);
     80
     81    return true;
    2382}
    2483
    2584
    26 void ppImageVersionMetadata(psMetadata *metadata)
     85void ppImageVersionPrint(void)
    2786{
    28     PS_ASSERT_METADATA_NON_NULL(metadata,);
     87    psTime *time = psTimeGetNow(PS_TIME_TAI); // The time now
     88    psString timeString = psTimeToISO(time); // The time in an ISO string
     89    psFree(time);
     90    psLogMsg("ppImage", PS_LOG_INFO, "ppImage at %s", timeString);
     91    psFree(timeString);
    2992
    3093    psString pslib = psLibVersionLong();// psLib version
     
    3598    psString ppImage = ppImageVersionLong(); // ppImage version
    3699
    37     psTime *time = psTimeGetNow(PS_TIME_TAI); // The time now
    38     psString timeString = psTimeToISO(time); // The time in an ISO string
    39     psFree(time);
    40     psString head = NULL;               // Head string
    41     psStringAppend(&head, "ppImage processing at %s. Component information:", timeString);
    42     psFree(timeString);
     100    psLogMsg("ppImage", PS_LOG_INFO, "%s", pslib);
     101    psLogMsg("ppImage", PS_LOG_INFO, "%s", psmodules);
     102    psLogMsg("ppImage", PS_LOG_INFO, "%s", psphot);
     103    psLogMsg("ppImage", PS_LOG_INFO, "%s", psastro);
     104    psLogMsg("ppImage", PS_LOG_INFO, "%s", ppStats);
     105    psLogMsg("ppImage", PS_LOG_INFO, "%s", ppImage);
    43106
    44     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, head, "");
    45     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, pslib, "");
    46     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, psmodules, "");
    47     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, psphot, "");
    48     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, psastro, "");
    49     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, ppStats, "");
    50     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, ppImage, "");
    51 
    52     psFree(head);
    53107    psFree(pslib);
    54108    psFree(psmodules);
  • branches/cnb_branches/cnb_branch_20090301/ppMerge/src/Makefile.am

    r19586 r23352  
    11bin_PROGRAMS = ppMerge
    22
    3 ppMerge_CFLAGS = $(PPMERGE_CFLAGS) $(PPSTATS_CFLAGS) $(PSMODULE_CFLAGS) $(PSLIB_CFLAGS)
     3# PPMERGE_VERSION=`if [ -e ../../VERSION ]; then cat ../../VERSION; else svnversion; fi`
     4# PPMERGE_BRANCH=`if [ -e ../../BRANCH ]; then cat ../../BRANCH; else svn info | sed -n -e '/URL:/ h' -e '/Repository Root:/ { x; H; x; s|Repository Root: \(.*\)\nURL: \1\(.*\)|\2| ; s|^/|| ; s|/[a-zA-Z]*/src.*|| ; p }'; fi`
     5# PPMERGE_SOURCE=`if [ -e ../../SOURCE ]; then cat ../../SOURCE; else svn info | sed -n -e 's/Repository UUID: // p'; fi`
     6#
     7# # Force recompilation of ppMergeVersion.c, since it gets the version information
     8# ppMergeVersion.c: FORCE
     9#       touch ppMergeVersion.c
     10# FORCE: ;
     11
     12ppMerge_CFLAGS = $(PPMERGE_CFLAGS) $(PPSTATS_CFLAGS) $(PSMODULE_CFLAGS) $(PSLIB_CFLAGS) -DPPMERGE_VERSION=$(SVN_VERSION) -DPPMERGE_BRANCH=$(SVN_BRANCH) -DPPMERGE_SOURCE=$(SVN_SOURCE)
    413ppMerge_LDFLAGS = $(PPMERGE_LIBS) $(PPSTATS_LIBS) $(PSMODULE_LIBS) $(PSLIB_LIBS)
    514
     
    1423        ppMergeLoop_Threaded.c  \
    1524        ppMergeSetThreads.c     \
    16         ppMergeMask.c
     25        ppMergeMask.c           \
     26        ppMergeVersion.c
    1727
    1828#       ppMergeLoop.c           
  • branches/cnb_branches/cnb_branch_20090301/ppMerge/src/ppMerge.c

    r21244 r23352  
    3838        goto die;
    3939    }
     40
     41    ppMergeVersionPrint();
    4042
    4143    ppMergeType type = psMetadataLookupS32(NULL, config->arguments, "TYPE"); ///< Type of frame
  • branches/cnb_branches/cnb_branch_20090301/ppMerge/src/ppMerge.h

    r21244 r23352  
    2828/// @{
    2929
    30 #define TIMERNAME "ppMerge"             ///< Name for timer 
    31 #define PPMERGE_RECIPE "PPMERGE"        ///< Recipe name 
    32 #define THREADED 1                      ///< Compile with threads? 
     30#define TIMERNAME "ppMerge"             ///< Name for timer
     31#define PPMERGE_RECIPE "PPMERGE"        ///< Recipe name
     32#define THREADED 1                      ///< Compile with threads?
    3333
    3434/**
     
    3636 */
    3737typedef enum {
    38     PPMERGE_TYPE_UNKNOWN,               ///< Unknown type 
    39     PPMERGE_TYPE_BIAS,                  ///< Bias frame 
    40     PPMERGE_TYPE_DARK,                  ///< (Multi-)Dark frame 
    41     PPMERGE_TYPE_MASK,                  ///< Mask frame 
    42     PPMERGE_TYPE_SHUTTER,               ///< Shutter frame 
     38    PPMERGE_TYPE_UNKNOWN,               ///< Unknown type
     39    PPMERGE_TYPE_BIAS,                  ///< Bias frame
     40    PPMERGE_TYPE_DARK,                  ///< (Multi-)Dark frame
     41    PPMERGE_TYPE_MASK,                  ///< Mask frame
     42    PPMERGE_TYPE_SHUTTER,               ///< Shutter frame
    4343    PPMERGE_TYPE_FLAT,                  ///< Flat-field frame (dome or sky)
    44     PPMERGE_TYPE_FRINGE,                ///< Fringe frame 
     44    PPMERGE_TYPE_FRINGE,                ///< Fringe frame
    4545} ppMergeType;
    4646
     
    4949 */
    5050typedef enum {
    51     PPMERGE_FILES_ALL,                  ///< All files 
    52     PPMERGE_FILES_INPUT,                ///< Input files 
    53     PPMERGE_FILES_OUTPUT                ///< Output files 
     51    PPMERGE_FILES_ALL,                  ///< All files
     52    PPMERGE_FILES_INPUT,                ///< Input files
     53    PPMERGE_FILES_OUTPUT                ///< Output files
    5454} ppMergeFiles;
    5555
     
    6060 */
    6161typedef struct {
    62     psArray *readouts;                  ///< Input readouts 
    63     bool read;                          ///< Has the scan been read? 
    64     bool busy;                          ///< Is the scan being processed? 
    65     int firstScan;                      ///< First row of the chunk to be read for this group 
    66     int lastScan;                       ///< Last row of the chunk to be read for this group 
     62    psArray *readouts;                  ///< Input readouts
     63    bool read;                          ///< Has the scan been read?
     64    bool busy;                          ///< Is the scan being processed?
     65    int firstScan;                      ///< First row of the chunk to be read for this group
     66    int lastScan;                       ///< Last row of the chunk to be read for this group
    6767} ppMergeFileGroup;
    6868
     
    7171 */
    7272bool ppMergeArguments(int argc, char *argv[], ///< Command-line arguments
    73                       pmConfig *config  ///< Configuration 
     73                      pmConfig *config  ///< Configuration
    7474    );
    7575
     
    7777 * Set up camera files
    7878 */
    79 bool ppMergeCamera(pmConfig *config     ///< Configuration 
     79bool ppMergeCamera(pmConfig *config     ///< Configuration
    8080    );
    8181
     
    8383 * Measure scale and zero-points
    8484 */
    85 bool ppMergeScaleZero(pmConfig *config  ///< Configuration 
     85bool ppMergeScaleZero(pmConfig *config  ///< Configuration
    8686    );
    8787
     
    8989 * Main loop to do the merging
    9090 */
    91 bool ppMergeLoop(pmConfig *config       ///< Configuration 
     91bool ppMergeLoop(pmConfig *config       ///< Configuration
    9292    );
    9393
     
    9595 * Main loop for masks
    9696 */
    97 bool ppMergeMask(pmConfig *config       ///< Configuration 
     97bool ppMergeMask(pmConfig *config       ///< Configuration
    9898    );
    9999
     
    101101 * Read nominated input file
    102102 */
    103 bool ppMergeFileReadInput(pmConfig *config, ///< Configuration 
    104                           pmReadout *readout, ///< Readout into which to read 
    105                           int num,      ///< Number of file in sequence 
    106                           int rows      ///< Number of rows to read at once 
     103bool ppMergeFileReadInput(pmConfig *config, ///< Configuration
     104                          pmReadout *readout, ///< Readout into which to read
     105                          int num,      ///< Number of file in sequence
     106                          int rows      ///< Number of rows to read at once
    107107    );
    108108
     
    110110 * Open nominated input file
    111111 */
    112 bool ppMergeFileOpenInput(pmConfig *config, ///< Configuration 
    113                           const pmFPAview *view, ///< View to open 
    114                           int num       ///< Number of file in sequence 
     112bool ppMergeFileOpenInput(pmConfig *config, ///< Configuration
     113                          const pmFPAview *view, ///< View to open
     114                          int num       ///< Number of file in sequence
    115115    );
    116116
     
    166166bool ppMergeSetThreads(void);
    167167
     168
     169/// Return software version
     170psString ppMergeVersion(void);
     171
     172/// Return software source
     173psString ppMergeSource(void);
     174
     175/// Return detailed software version information
     176psString ppMergeVersionLong(void);
     177
     178/// Populate a FITS header with version information
     179bool ppMergeVersionHeader(
     180    psMetadata *header                  ///< Header to populate
     181    );
     182
     183/// Print version information
     184void ppMergeVersionPrint(void);
     185
     186
    168187///@}
    169188#endif
  • branches/cnb_branches/cnb_branch_20090301/ppMerge/src/ppMergeLoop_Threaded.c

    r21365 r23352  
    137137    assert(output && output->fpa);
    138138    pmFPA *outFPA = output->fpa;        ///< Output FPA
     139    pmHDU *lastHDU = NULL;              // Last HDU that was updated
    139140    int cellNum = 0;                    ///< Index of cell
    140141    if (!pmFPAfileIOChecks(config, view, PM_FPA_BEFORE)) {
     
    156157                // No data here
    157158                continue;
     159            }
     160
     161            // Update the header
     162            {
     163                pmHDU *hdu = pmHDUGetHighest(outFPA, outChip, outCell); // HDU for file
     164                if (hdu && hdu != lastHDU) {
     165                    ppMergeVersionHeader(hdu->header);
     166                    lastHDU = hdu;
     167                }
    158168            }
    159169
  • branches/cnb_branches/cnb_branch_20090301/ppMerge/src/ppMergeMask.c

    r21365 r23352  
    1616                      const pmFPAview *view, ///< View to chip
    1717                      bool writeOut,     ///< Write output?
     18                      pmHDU **lastHDU,   ///< HDU last updated
    1819                      psRandom *rng,    ///< Random number generator
    1920                      psMetadata *stats ///< Statistics output
     
    9697                    i, inView->chip, inView->cell);
    9798
     99            // Update the header
     100            {
     101                pmHDU *hdu = pmHDUGetHighest(outCell->parent->parent, outCell->parent, outCell); // File HDU
     102                if (hdu && hdu != *lastHDU) {
     103                    ppMergeVersionHeader(hdu->header);
     104                    *lastHDU = hdu;
     105                }
     106            }
     107
    98108            if (!pmFPAfileIOChecks(config, inView, PM_FPA_BEFORE)) {
    99109                psFree(inView);
     
    359369
    360370    pmFPAview *view = pmFPAviewAlloc(0); ///< View to component of interest
    361     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 0); ///< Random number generator
     371    psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS); ///< Random number generator
    362372
    363373    psMetadata *stats = NULL;           ///< Statistics for output
     
    395405    assert(output && output->fpa);
    396406    pmFPA *outFPA = output->fpa;        ///< Output FPA
     407    pmHDU *lastHDU = NULL;              // Last HDU updated
    397408
    398409    if (!pmFPAfileIOChecks(config, view, PM_FPA_BEFORE)) {
     
    409420
    410421        for (int i = 0; i < iter; i++) {
    411             if (!mergeMask(config, view, (i == iter - 1), rng, stats)) {
     422            if (!mergeMask(config, view, (i == iter - 1), &lastHDU, rng, stats)) {
    412423                psError(PS_ERR_UNKNOWN, false, "Unable to merge chip %d", view->chip);
    413424                goto PPMERGE_MASK_ERROR;
  • branches/cnb_branches/cnb_branch_20090301/ppMerge/src/ppMergeScaleZero.c

    r21365 r23352  
    5151        break;
    5252    }
    53     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 0); ///< Random number generator
     53    psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS); ///< Random number generator
    5454    pmFPAview *view = NULL;             ///< View into FPA
    5555
  • branches/cnb_branches/cnb_branch_20090301/ppMerge/src/ppMergeVersion.c

    r21244 r23352  
    2222#include "ppMergeVersion.h"
    2323
    24 static const char *cvsTag = "$Name: not supported by cvs2svn $";///< CVS tag name
     24#ifndef PPMERGE_VERSION
     25#error "PPMERGE_VERSION is not set"
     26#endif
     27#ifndef PPMERGE_BRANCH
     28#error "PPMERGE_BRANCH is not set"
     29#endif
     30#ifndef PPMERGE_SOURCE
     31#error "PPMERGE_SOURCE is not set"
     32#endif
     33
     34#define xstr(s) str(s)
     35#define str(s) #s
    2536
    2637psString ppMergeVersion(void)
    2738{
    28     psString version = NULL;            ///< Version, to return
    29     psStringAppend(&version, "%s-%s",PACKAGE_NAME,PACKAGE_VERSION);
    30     return version;
     39    char *value = NULL;
     40    psStringAppend(&value, "%s@%s", xstr(PPMERGE_BRANCH), xstr(PPMERGE_VERSION));
     41    return value;
     42}
     43
     44psString ppMergeSource(void)
     45{
     46    return psStringCopy(xstr(PPMERGE_SOURCE));
    3147}
    3248
    3349psString ppMergeVersionLong(void)
    3450{
    35     psString version = ppMergeVersion(); ///< Version, to return
    36     psString tag = psStringStripCVS(cvsTag, "Name"); ///< CVS tag
    37     psStringAppend(&version, " (cvs tag %s) %s, %s", tag, __DATE__, __TIME__);
    38     psFree(tag);
     51    psString version = ppMergeVersion();  // Version, to return
     52    psString source = ppMergeSource();    // Source
     53
     54    psStringPrepend(&version, "ppMerge ");
     55    psStringAppend(&version, " from %s, built %s, %s", source, __DATE__, __TIME__);
     56    psFree(source);
     57
     58#ifdef __OPTIMIZE__
     59    psStringAppend(&version, " optimised");
     60#else
     61    psStringAppend(&version, " unoptimised");
     62#endif
     63
    3964    return version;
     65};
     66
     67bool ppMergeVersionHeader(psMetadata *header)
     68{
     69    PS_ASSERT_METADATA_NON_NULL(header, false);
     70
     71    psTime *time = psTimeGetNow(PS_TIME_TAI); // The time now
     72    psString timeString = psTimeToISO(time); // The time in an ISO string
     73    psFree(time);
     74    psString history = NULL;               // History string
     75    psStringAppend(&history, "ppMerge at %s", timeString);
     76    psFree(timeString);
     77    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, history);
     78    psFree(history);
     79
     80    psLibVersionHeader(header);
     81    psModulesVersionHeader(header);
     82    ppStatsVersionHeader(header);
     83
     84    psString version = ppMergeVersion(); // Software version
     85    psString source  = ppMergeSource();  // Software source
     86
     87    psStringPrepend(&version, "ppMerge version: ");
     88    psStringPrepend(&source, "ppMerge source: ");
     89
     90    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, version);
     91    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, source);
     92
     93    psFree(version);
     94    psFree(source);
     95
     96    return true;
    4097}
    4198
    42 
    43 void ppMergeVersionMetadata(psMetadata *metadata)
     99void ppMergeVersionPrint(void)
    44100{
    45     PS_ASSERT_METADATA_NON_NULL(metadata,);
    46 
    47     psString pslib = psLibVersionLong();///< psLib version
    48     psString psmodules = psModulesVersionLong(); ///< psModules version
    49     psString ppStats = ppStatsVersionLong(); ///< ppStats version
    50     psString ppMerge = ppMergeVersionLong(); ///< ppMerge version
    51 
    52     psTime *time = psTimeGetNow(PS_TIME_TAI); ///< The time now
    53     psString timeString = psTimeToISO(time); ///< The time in an ISO string
     101    psTime *time = psTimeGetNow(PS_TIME_TAI); // The time now
     102    psString timeString = psTimeToISO(time); // The time in an ISO string
    54103    psFree(time);
    55     psString head = NULL;               ///< Head string
    56     psStringAppend(&head, "ppMerge processing at %s. Component information:", timeString);
     104    psLogMsg("ppMerge", PS_LOG_INFO, "ppMerge at %s", timeString);
    57105    psFree(timeString);
    58106
    59     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, head, "");
    60     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, pslib, "");
    61     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, psmodules, "");
    62     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, ppStats, "");
    63     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, ppMerge, "");
     107    psString pslib = psLibVersionLong();// psLib version
     108    psString psmodules = psModulesVersionLong(); // psModules version
     109    psString ppStats = ppStatsVersionLong(); // ppStats version
     110    psString ppMerge = ppMergeVersionLong(); // ppMerge version
    64111
    65     psFree(head);
     112    psLogMsg("ppImage", PS_LOG_INFO, "%s", pslib);
     113    psLogMsg("ppImage", PS_LOG_INFO, "%s", psmodules);
     114    psLogMsg("ppImage", PS_LOG_INFO, "%s", ppStats);
     115    psLogMsg("ppImage", PS_LOG_INFO, "%s", ppMerge);
     116
    66117    psFree(pslib);
    67118    psFree(psmodules);
  • branches/cnb_branches/cnb_branch_20090301/ppMerge/src/ppMergeVersion.h

    r21244 r23352  
    2020
    2121/**
     22 * Return software source
     23 */
     24psString ppMergeSource(void);
     25
     26/**
    2227 * Return long version information
    2328 */
  • branches/cnb_branches/cnb_branch_20090301/ppSim/src/Makefile.am

    r18011 r23352  
    11bin_PROGRAMS = ppSim ppSimSequence
    22
    3 ppSim_CPPFLAGS = $(PSLIB_CFLAGS) $(PSMODULE_CFLAGS) $(PSPHOT_CFLAGS) $(PSASTRO_CFLAGS) $(ppSim_CFLAGS)
     3# PPSIM_VERSION=`if [ -e ../../VERSION ]; then cat ../../VERSION; else svnversion; fi`
     4# PPSIM_BRANCH=`if [ -e ../../BRANCH ]; then cat ../../BRANCH; else svn info | sed -n -e '/URL:/ h' -e '/Repository Root:/ { x; H; x; s|Repository Root: \(.*\)\nURL: \1\(.*\)|\2| ; s|^/|| ; s|/[a-zA-Z]*/src.*|| ; p }'; fi`
     5# PPSIM_SOURCE=`if [ -e ../../SOURCE ]; then cat ../../SOURCE; else svn info | sed -n -e 's/Repository UUID: // p'; fi`
     6#
     7# # Force recompilation of ppSimVersion.c, since it gets the version information
     8# ppSimVersion.c: FORCE
     9#       touch ppSimVersion.c
     10# FORCE: ;
     11
     12ppSim_CPPFLAGS = $(PSLIB_CFLAGS) $(PSMODULE_CFLAGS) $(PSPHOT_CFLAGS) $(PSASTRO_CFLAGS) $(ppSim_CFLAGS) -DPPSIM_VERSION=$(SVN_VERSION) -DPPSIM_BRANCH=$(SVN_BRANCH) -DPPSIM_SOURCE=$(SVN_SOURCE)
    413ppSim_LDFLAGS = $(PSLIB_LIBS) $(PSMODULE_LIBS) $(PSPHOT_LIBS) $(PSASTRO_LIBS)
    514ppSim_SOURCES = \
     
    3544        ppSimMosaicChip.c         \
    3645        ppSimRandomGaussian.c     \
    37         ppSimBadPixels.c
     46        ppSimBadPixels.c          \
     47        ppSimVersion.c
    3848
    3949ppSimSequence_CPPFLAGS = $(PSLIB_CFLAGS) $(PSMODULE_CFLAGS) $(PSASTRO_CFLAGS) $(ppSim_CFLAGS)
  • branches/cnb_branches/cnb_branch_20090301/ppSim/src/ppSim.h

    r21183 r23352  
    1919
    2020// Compare a value with minimum and maximum values, replacing where required.
    21 #define COMPARE(VALUE,MIN,MAX) {                \
    22         if (VALUE < MIN) { MIN = VALUE; }       \
    23         if (VALUE > MAX) { MAX = VALUE; }       \
     21#define COMPARE(VALUE,MIN,MAX) {                \
     22        if (VALUE < MIN) { MIN = VALUE; }       \
     23        if (VALUE > MAX) { MAX = VALUE; }       \
    2424    }
    2525
     
    147147float ppSimMagToFlux (float mag, float zp);
    148148
    149 float ppSimArgToRecipeF32(bool *status, 
    150                           psMetadata *options,    // Target to which to add value
    151                           const char *recipeName, // Name for value in the recipe
    152                           psMetadata *arguments,  // Command-line arguments
    153                           const char *argName    // Argument name in the command-line arguments
     149float ppSimArgToRecipeF32(bool *status,
     150                          psMetadata *options,    // Target to which to add value
     151                          const char *recipeName, // Name for value in the recipe
     152                          psMetadata *arguments,  // Command-line arguments
     153                          const char *argName    // Argument name in the command-line arguments
    154154    );
    155155
    156156int ppSimArgToRecipeS32(bool *status,
    157                         psMetadata *options,    // Target to which to add value
    158                         const char *recipeName, // Name for value in the recipe
    159                         psMetadata *arguments,  // Command-line arguments
    160                         const char *argName      // Argument name in the command-line arguments
     157                        psMetadata *options,    // Target to which to add value
     158                        const char *recipeName, // Name for value in the recipe
     159                        psMetadata *arguments,  // Command-line arguments
     160                        const char *argName      // Argument name in the command-line arguments
    161161    );
    162162
    163163char *ppSimArgToRecipeStr(bool *status,
    164                           psMetadata *options,    // Target to which to add value
    165                           const char *recipeName, // Name for value in the recipe
    166                           psMetadata *arguments,  // Command-line arguments
    167                           const char *argName    // Argument name in the command-line arguments
     164                          psMetadata *options,    // Target to which to add value
     165                          const char *recipeName, // Name for value in the recipe
     166                          psMetadata *arguments,  // Command-line arguments
     167                          const char *argName    // Argument name in the command-line arguments
    168168    );
    169169
    170170bool ppSimArgToRecipeBool(bool *status,
    171                           psMetadata *options,    // Target to which to add value
    172                           const char *recipeName, // Name for value in the recipe
    173                           psMetadata *arguments,  // Command-line arguments
    174                           const char *argName       // Argument name in the command-line arguments
     171                          psMetadata *options,    // Target to which to add value
     172                          const char *recipeName, // Name for value in the recipe
     173                          psMetadata *arguments,  // Command-line arguments
     174                          const char *argName       // Argument name in the command-line arguments
    175175    );
    176176
     
    198198bool ppSimDefinePixels (psArray *sources, pmReadout *readout, psMetadata *recipe);
    199199
     200/// Return software version
     201psString ppSimVersion(void);
     202
     203/// Return software source
     204psString ppSimSource(void);
     205
     206/// Return long version information
     207psString ppSimVersionLong(void);
     208
    200209#endif
  • branches/cnb_branches/cnb_branch_20090301/ppSim/src/ppSimBadPixels.c

    r20910 r23352  
    7474    }
    7575
    76     psRandom *pseudoRNG = psRandomAlloc(PS_RANDOM_TAUS, seed); // Pseudo-random number generator
     76    psRandom *pseudoRNG = psRandomAllocSpecific(PS_RANDOM_TAUS, seed); // Pseudo-random number generator
    7777
    7878    psImage *image = readout->image;    // Image of interest
  • branches/cnb_branches/cnb_branch_20090301/ppSim/src/ppSimLoop.c

    r21365 r23352  
    2525    psMetadata *recipe = psMetadataLookupMetadata(NULL, config->recipes, PPSIM_RECIPE); // Recipe
    2626
    27     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 0); // Random number generator
     27    psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS); // Random number generator
    2828
    2929    char *typeStr = psMetadataLookupStr(NULL, recipe, "IMAGE.TYPE"); // Type of image to simulate
  • branches/cnb_branches/cnb_branch_20090301/ppSim/src/ppSimSequence.c

    r19315 r23352  
    133133    if (ppsim_recipe) psStringAppend (&ppSimCommand, " -recipe PPSIM %s", ppsim_recipe);
    134134
    135     unsigned long seed = psMetadataLookupS32 (&status, config, "RND_SEED");
    136     if (!status) seed = 0;
    137     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, seed);
     135    psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS);
    138136
    139137    psMetadataItem *item = psMetadataLookup (config, "SEQUENCE");
    140138    if (item == NULL) {
    141139        psLogMsg ("ppSimSequence", PS_LOG_WARN, "missing SEQUENCE description");
    142         exit (1);
     140        exit (PS_EXIT_CONFIG_ERROR);
    143141    }
    144142
     
    170168        }
    171169
    172         // determine the camera for the sequence and define the ppSim command
    173         if (camera == NULL) {
    174             camera = psMetadataLookupStr (&status, sequence, "CAMERA");
    175         }
    176 
    177         psString injectCommandReal = NULL;
    178         psString ppSimCommandReal = NULL;
    179 
    180         psStringAppend (&injectCommandReal, "%s --camera %s", injectCommand, camera);
    181         psStringAppend (&ppSimCommandReal, "%s -camera %s", ppSimCommand, camera);
     170        // determine the camera for the sequence and define the ppSim command
     171        if (camera == NULL) {
     172            camera = psMetadataLookupStr (&status, sequence, "CAMERA");
     173        }
     174
     175        psString injectCommandReal = NULL;
     176        psString ppSimCommandReal = NULL;
     177
     178        psStringAppend (&injectCommandReal, "%s --camera %s", injectCommand, camera);
     179        psStringAppend (&ppSimCommandReal, "%s -camera %s", ppSimCommand, camera);
    182180
    183181        if (!strcasecmp (type, "BIAS")) {
  • branches/cnb_branches/cnb_branch_20090301/ppStack

  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/Makefile.am

    r19337 r23352  
    11bin_PROGRAMS = ppStack
    22
    3 ppStack_CFLAGS  = $(PSLIB_CFLAGS) $(PSMODULE_CFLAGS) $(PSPHOT_CFLAGS) $(PPSTATS_CFLAGS) $(PPSTACK_CFLAGS)
     3# PPSTACK_VERSION=`if [ -e ../../VERSION ]; then cat ../../VERSION; else svnversion; fi`
     4# PPSTACK_BRANCH=`if [ -e ../../BRANCH ]; then cat ../../BRANCH; else svn info | sed -n -e '/URL:/ h' -e '/Repository Root:/ { x; H; x; s|Repository Root: \(.*\)\nURL: \1\(.*\)|\2| ; s|^/|| ; s|/[a-zA-Z]*/src.*|| ; p }'; fi`
     5# PPSTACK_SOURCE=`if [ -e ../../SOURCE ]; then cat ../../SOURCE; else svn info | sed -n -e 's/Repository UUID: // p'; fi`
     6#
     7# # Force recompilation of ppStackVersion.c, since it gets the version information
     8# ppStackVersion.c: FORCE
     9#       touch ppStackVersion.c
     10# FORCE: ;
     11
     12ppStack_CFLAGS  = $(PSLIB_CFLAGS) $(PSMODULE_CFLAGS) $(PSPHOT_CFLAGS) $(PPSTATS_CFLAGS) $(PPSTACK_CFLAGS) -DPPSTACK_VERSION=$(SVN_VERSION) -DPPSTACK_BRANCH=$(SVN_BRANCH) -DPPSTACK_SOURCE=$(SVN_SOURCE)
    413ppStack_LDFLAGS = $(PSLIB_LIBS)   $(PSMODULE_LIBS)   $(PSPHOT_LIBS)   $(PPSTATS_LIBS)   $(PPSTACK_LIBS)
    514
     
    817        ppStackArguments.c      \
    918        ppStackCamera.c         \
     19        ppStackFiles.c          \
    1020        ppStackLoop.c           \
    1121        ppStackPSF.c            \
    1222        ppStackReadout.c        \
    13         ppStackPhotometry.c     \
    1423        ppStackVersion.c        \
    1524        ppStackMatch.c          \
    1625        ppStackSources.c        \
    17         ppStackThread.c
     26        ppStackThread.c         \
     27        ppStackOptions.c        \
     28        ppStackSetup.c          \
     29        ppStackPrepare.c        \
     30        ppStackConvolve.c       \
     31        ppStackCombineInitial.c \
     32        ppStackReject.c         \
     33        ppStackCombineFinal.c   \
     34        ppStackCleanup.c        \
     35        ppStackPhotometry.c     \
     36        ppStackFinish.c
    1837
    1938noinst_HEADERS =                \
    20         ppStack.h
     39        ppStack.h               \
     40        ppStackLoop.h           \
     41        ppStackOptions.h        \
     42        ppStackThread.h
    2143
    2244CLEANFILES = *~
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStack.c

    r21258 r23352  
    99
    1010#include "ppStack.h"
     11#include "ppStackLoop.h"
    1112
    1213#define TIMER_NAME "PPSTACK"            // Name of timer
     
    3334        goto die;
    3435    }
     36
     37    ppStackVersionPrint();
    3538
    3639    if (!pmModelClassInit()) {
     
    7477    pmConfigDone();
    7578    psLibFinalize();
    76 
     79    pmVisualClose();
    7780    exit(exitValue);
    7881}
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStack.h

    r21477 r23352  
    1 #ifndef PP_STACK_H
    2 #define PP_STACK_H
     1#ifndef PPSTACK_H
     2#define PPSTACK_H
    33
    44#define PPSTACK_RECIPE "PPSTACK"        // Name of the recipe
     
    1010// Mask values for inputs
    1111typedef enum {
    12     PPSTACK_MASK_MATCH  = 0x01,         // PSF-matching failed
    13     PPSTACK_MASK_CHI2   = 0x02,         // Chi^2 too deviant
    14     PPSTACK_MASK_REJECT = 0x04,         // Rejection failed
    15     PPSTACK_MASK_BAD    = 0x08,         // Bad image (too many pixels rejected)
     12    PPSTACK_MASK_CAL    = 0x01,         // Photometric calibration failed
     13    PPSTACK_MASK_MATCH  = 0x02,         // PSF-matching failed
     14    PPSTACK_MASK_CHI2   = 0x04,         // Chi^2 too deviant
     15    PPSTACK_MASK_REJECT = 0x08,         // Rejection failed
     16    PPSTACK_MASK_BAD    = 0x10,         // Bad image (too many pixels rejected)
    1617    PPSTACK_MASK_ALL    = 0xff          // All errors
    1718} ppStackMask;
    1819
    19 // Thread for stacking chunks
    20 //
    21 // Each input file contributes a readout, into which is read a chunk from that file
    22 typedef struct {
    23     psArray *readouts;                  // Input readouts to read and stack
    24     bool read;                          // Has the scan been read?
    25     bool busy;                          // Is the scan being processed?
    26     int firstScan;                      // First row of the chunk to be read for this group
    27     int lastScan;                       // Last row of the chunk to be read for this group
    28 } ppStackThread;
     20// List of files
     21typedef enum {
     22    PPSTACK_FILES_PREPARE,              // Files for preparation
     23    PPSTACK_FILES_CONVOLVE,             // Files for convolution
     24    PPSTACK_FILES_COMBINE,              // Files for combination
     25    PPSTACK_FILES_PHOT                  // Files for photometry
     26} ppStackFileList;
    2927
    30 // Allocator
    31 ppStackThread *ppStackThreadAlloc(psArray *readouts // Inputs readouts to read and stack
    32     );
    33 
    34 // Data for threads
    35 typedef struct {
    36     psArray *threads;                   // Threads doing stacking
    37     int lastScan;                       // Last row that's been read
    38     psArray *imageFits;                 // FITS file pointers for images
    39     psArray *maskFits;                  // FITS file pointers for masks
    40     psArray *varianceFits;                // FITS file pointers for variances
    41 } ppStackThreadData;
    42 
    43 // Set up thread data
    44 ppStackThreadData *ppStackThreadDataSetup(const psArray *cells, // Array of input cells
    45                                           const psArray *imageNames, // Names of images to read
    46                                           const psArray *maskNames, // Names of masks to read
    47                                           const psArray *varianceNames, // Names of variance maps to read
    48                                           const psArray *covariances, // Covariance matrices (already read)
    49                                           const pmConfig *config // Configuration
    50     );
    51 
    52 // Read chunk into the first available file thread
    53 ppStackThread *ppStackThreadRead(bool *status, // Status of read
    54                                  ppStackThreadData *stack, // Stacks available for reading
    55                                  pmConfig *config, // Configuration
    56                                  int numChunk, // Chunk number (only for interest)
    57                                  int overlap // Overlap between subsequent scans
    58     );
    59 
    60 // Initialise the threads
    61 void ppStackThreadInit(void);
    6228
    6329// Setup command-line arguments
     
    7440    );
    7541
    76 // Loop over the inputs, doing the combination
    77 bool ppStackLoop(pmConfig *config       // Configuration
    78     );
    79 
    8042// Determine target PSF for input images
    8143pmPSF *ppStackPSF(const pmConfig *config, // Configuration
    8244                  int numCols, int numRows, // Size of image
    83                   const psArray *psfs   // List of input PSFs
     45                  const psArray *psfs,  // List of input PSFs
     46                  const psVector *inputMask // Mask for inputs
    8447    );
    8548
     
    12588    );
    12689
    127 // Perform photometry on stack
    128 bool ppStackPhotometry(pmConfig *config, // Configuration
    129                        const pmReadout *readout, // Readout to be photometered
    130                        const pmFPAview *view // View to readout
    131     );
    132 
    13390// Return software version
    13491psString ppStackVersion(void);
     92
     93/// Return software source
     94psString ppStackSource(void);
    13595
    13696// Return long description of software version
    13797psString ppStackVersionLong(void);
    13898
    139 // Supplement metadata with software version
    140 void ppStackVersionMetadata(psMetadata *metadata // Metadata to supplement
     99// Supplement header with software version
     100bool ppStackVersionHeader(psMetadata *header // Header to supplement
    141101    );
     102
     103/// Print version information
     104void ppStackVersionPrint(void);
    142105
    143106/// Convolve image to match specified seeing
     
    158121/// Corrects the source PSF photometry to a common system.  Return the sum of the exposure times.
    159122float ppStackSourcesTransparency(const psArray *sourceLists, // Sources for each input
     123                                 psVector *inputMask, // Indicates bad input
    160124                                 const pmFPAview *view, // View to readout
    161125                                 const pmConfig *config // Configuration
    162126    );
    163127
     128/// Dump memory debugging information
     129void ppStackMemDump(
     130    const char *name                    ///< Stage name, for inclusion in the output file name
     131    );
     132
     133/// Activate/deactivate a list of files
     134void ppStackFileActivation(
     135    pmConfig *config,                   // Configuration
     136    ppStackFileList list,               // Files to turn on/off
     137    bool state                          // Activation state
     138    );
     139
     140// Activate/deactivate a single element for a list
     141void ppStackFileActivationSingle(
     142    pmConfig *config,                   // Configuration
     143    ppStackFileList list,               // Files to turn on/off
     144    bool state,                         // Activation state
     145    int num                             // Number of file in sequence
     146    );
     147
     148/// Iterate down the hierarchy, loading files
     149///
     150/// We can get away with this simplistic treatment of the FPA hierarchy because we're working on skycells.
     151pmFPAview *ppStackFilesIterateDown(
     152    pmConfig *config                    // Configuration
     153    );
     154
     155/// Iterate up the hierarchy, writing files
     156///
     157/// We can get away with this simplistic treatment of the FPA hierarchy because we're working on skycells.
     158bool ppStackFilesIterateUp(
     159    pmConfig *config                    // Configuration
     160    );
     161
     162/// Write an image to a FITS file
     163bool ppStackWriteImage(
     164    const char *name,                   // Name of image
     165    psMetadata *header,                 // Header
     166    const psImage *image,               // Image
     167    pmConfig *config                    // Configuration
     168    );
     169
     170
    164171#endif
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackArguments.c

    r21525 r23352  
    168168                      "Play safe with small numbers of pixels to combine?", false);
    169169    psMetadataAddF32(arguments, PS_LIST_TAIL, "-zp-radius", 0, "Radius (pixels) for matching sources", NAN);
    170     psMetadataAddS32(arguments, PS_LIST_TAIL, "-zp-iter", 0, "Maximum iterations for zero point", 0);
     170    psMetadataAddS32(arguments, PS_LIST_TAIL, "-zp-iter-1", 0, "Maximum iterations for zero point; pass 1", 0);
     171    psMetadataAddS32(arguments, PS_LIST_TAIL, "-zp-iter-2", 0, "Maximum iterations for zero point; pass 2", 0);
    171172    psMetadataAddF32(arguments, PS_LIST_TAIL, "-zp-tol", 0, "Tolerance for zero point iterations", NAN);
    172173    psMetadataAddS32(arguments, PS_LIST_TAIL, "-zp-trans-iter", 0, "Iterations for transparency determination", 0);
    173174    psMetadataAddF32(arguments, PS_LIST_TAIL, "-zp-trans-rej", 0, "Rejection threshold for transparency determination", NAN);
    174175    psMetadataAddF32(arguments, PS_LIST_TAIL, "-zp-trans-thresh", 0, "Threshold for transparency determination", NAN);
    175     psMetadataAddF32(arguments, PS_LIST_TAIL, "-zp-star-rej", 0, "Rejection threshold for stars", NAN);
     176    psMetadataAddF32(arguments, PS_LIST_TAIL, "-zp-star-rej-1", 0, "Rejection threshold for stars; pass 1", NAN);
     177    psMetadataAddF32(arguments, PS_LIST_TAIL, "-zp-star-rej-2", 0, "Rejection threshold for stars; pass 2", NAN);
    176178    psMetadataAddF32(arguments, PS_LIST_TAIL, "-zp-star-limit", 0, "Limit on star rejection fraction for successful iteration", NAN);
    177     psMetadataAddF32(arguments, PS_LIST_TAIL, "-zp-star-sys", 0, "Estimated systematic error", NAN);
     179    psMetadataAddF32(arguments, PS_LIST_TAIL, "-zp-star-sys-1", 0, "Estimated systematic error; pass 1", NAN);
     180    psMetadataAddF32(arguments, PS_LIST_TAIL, "-zp-star-sys-2", 0, "Estimated systematic error; pass 2", NAN);
    178181    psMetadataAddStr(arguments, PS_LIST_TAIL, "-temp-image", 0, "Suffix for temporary images", NULL);
    179182    psMetadataAddStr(arguments, PS_LIST_TAIL, "-temp-mask", 0, "Suffix for temporary masks", NULL);
     
    182185                      "Delete temporary files on completion?", false);
    183186    psMetadataAddS32(arguments, PS_LIST_TAIL, "-threads", 0, "Number of threads to use", 0);
    184     psMetadataAddBool(arguments, PS_LIST_TAIL, "-psphot-visual", 0, "psphot visualisation", 0);
     187    psMetadataAddBool(arguments, PS_LIST_TAIL, "-visual", 0, "visualisation", false);
    185188
    186189    if (argc == 1 || !psArgumentParse(arguments, &argc, argv) || argc != 3) {
     
    242245
    243246    VALUE_ARG_RECIPE_FLOAT("-zp-radius",       "ZP.RADIUS",       F32);
    244     VALUE_ARG_RECIPE_INT("-zp-iter",           "ZP.ITER",         S32, 0);
     247    VALUE_ARG_RECIPE_INT("-zp-iter-1",         "ZP.ITER.1",       S32, 0);
     248    VALUE_ARG_RECIPE_INT("-zp-iter-2",         "ZP.ITER.2",       S32, 0);
    245249    VALUE_ARG_RECIPE_FLOAT("-zp-tol",          "ZP.TOL",          F32);
    246250    VALUE_ARG_RECIPE_INT("-zp-trans-iter",     "ZP.TRANS.ITER",   S32, 0);
    247251    VALUE_ARG_RECIPE_FLOAT("-zp-trans-rej",    "ZP.TRANS.REJ",    F32);
    248252    VALUE_ARG_RECIPE_FLOAT("-zp-trans-thresh", "ZP.TRANS.THRESH", F32);
    249     VALUE_ARG_RECIPE_FLOAT("-zp-star-rej",     "ZP.STAR.REJ",     F32);
     253    VALUE_ARG_RECIPE_FLOAT("-zp-star-rej-1",   "ZP.STAR.REJ.1",   F32);
     254    VALUE_ARG_RECIPE_FLOAT("-zp-star-rej-2",   "ZP.STAR.REJ.2",   F32);
    250255    VALUE_ARG_RECIPE_FLOAT("-zp-star-limit",   "ZP.STAR.LIMIT",   F32);
    251     VALUE_ARG_RECIPE_FLOAT("-zp-star-sys",     "ZP.STAR.SYS",     F32);
     256    VALUE_ARG_RECIPE_FLOAT("-zp-star-sys-1",   "ZP.STAR.SYS.1",   F32);
     257    VALUE_ARG_RECIPE_FLOAT("-zp-star-sys-2",   "ZP.STAR.SYS.2",   F32);
    252258
    253259    VALUE_ARG_RECIPE_INT("-psf-instances", "PSF.INSTANCES", S32, 0);
     
    255261    VALUE_ARG_RECIPE_INT("-psf-order",     "PSF.ORDER",     S32, 0);
    256262    valueArgRecipeStr(arguments, recipe, "-psf-model", "PSF.MODEL", recipe);
     263
     264    if (psMetadataLookupBool(NULL, arguments, "-visual")) {
     265        pmVisualSetVisual(true);
     266    }
    257267
    258268    if (psMetadataLookupBool(NULL, arguments, "-photometry") ||
     
    290300    if (dump_file) {
    291301        pmConfigCamerasCull(config, NULL);
    292         pmConfigRecipesCull(config, "PPSTACK,PPSUB,PPSTATS,PSPHOT,MASKS");
     302        pmConfigRecipesCull(config, "PPSTACK,PPSUB,PPSTATS,PSPHOT,MASKS,JPEG");
    293303
    294304        pmFPAfile *input = psMetadataLookupPtr(NULL, config->files, "PPSTACK.INPUT"); // Input file
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackLoop.c

    r21526 r23352  
    44
    55#include <stdio.h>
    6 #include <unistd.h>
    7 #include <string.h>
    8 #include <libgen.h>
    96#include <pslib.h>
    107#include <psmodules.h>
    11 #include <ppStats.h>
    128
    139#include "ppStack.h"
    14 
    15 //#define TESTING
    16 
    17 #define WCS_TOLERANCE 0.001             // Tolerance for WCS
    18 #define PIXELS_BUFFER 1024              // Initial size of pixel lists
    19 
    20 // Here follows lists of files for activation/deactivation at various stages.  Each must be NULL-terminated.
    21 
    22 // Files required in preparation for convolution
    23 static char *prepareFiles[] = { "PPSTACK.INPUT.PSF", "PPSTACK.INPUT.SOURCES", "PPSTACK.TARGET.PSF", NULL };
    24 
    25 // Files required for the convolution
    26 static char *convolveFiles[] = { "PPSTACK.INPUT", "PPSTACK.INPUT.MASK", "PPSTACK.INPUT.VARIANCE", NULL };
    27 
    28 // Output files for the combination
    29 static char *combineFiles[] = { "PPSTACK.OUTPUT", "PPSTACK.OUTPUT.MASK", "PPSTACK.OUTPUT.VARIANCE",
    30                                 "PPSTACK.OUTPUT.JPEG1", "PPSTACK.OUTPUT.JPEG2", NULL };
    31 
    32 // Files for photometry
    33 static char *photFiles[] = { "PSPHOT.INPUT", "PSPHOT.OUTPUT", "PSPHOT.RESID", "PSPHOT.BACKMDL",
    34                              "PSPHOT.BACKMDL.STDEV", "PSPHOT.BACKGND", "PSPHOT.BACKSUB",
    35                              "SOURCE.PLOT.MOMENTS", "SOURCE.PLOT.PSFMODEL", "SOURCE.PLOT.APRESID",
    36                              "PSPHOT.INPUT.CMF", NULL };
    37 
    38 static void memDump(const char *name)
    39 {
    40     return;
    41 
    42     static int num = 0;                 // Counter, to make files unique and give an idea of sequence
    43 
    44     psString filename = NULL;           // Name of file
    45     psStringAppend(&filename, "memdump_%s_%03d.txt", name, num);
    46     FILE *memFile = fopen(filename, "w");
    47     psFree(filename);
    48 
    49     psMemBlock **leaks = NULL;
    50     int numLeaks = psMemCheckLeaks(0, &leaks, NULL, true);
    51     fprintf(memFile, "# MemBlock Size Source\n");
    52     unsigned long total = 0;            // Total memory used
    53     for (int i = 0; i < numLeaks; i++) {
    54         psMemBlock *mb = leaks[i];
    55         fprintf(memFile, "%12lu\t%12zd\t%s:%d\n", mb->id, mb->userMemorySize,
    56                 mb->file, mb->lineno);
    57         total += mb->userMemorySize;
    58     }
    59     fclose(memFile);
    60     psFree(leaks);
    61 
    62     fprintf(stderr, "Memdump %s %d: Memory use: %ld, sbrk: %p\n", name, num, total, sbrk(0));
    63     num++;
    64 }
    65 
    66 
    67 
    68 // Activate/deactivate a list of files
    69 static void fileActivation(pmConfig *config, // Configuration
    70                            char **files, // Files to turn on/off
    71                            bool state   // Activation state
    72     )
    73 {
    74     assert(config);
    75     assert(files);
    76 
    77     for (int i = 0; files[i] != NULL; i++) {
    78         pmFPAfileActivate(config->files, state, files[i]);
    79     }
    80     return;
    81 }
    82 
    83 // Activate/deactivate a single element for a list
    84 static void fileActivationSingle(pmConfig *config, // Configuration
    85                                  char **files, // Files to turn on/off
    86                                  bool state,   // Activation state
    87                                  int num // Number of file in sequence
    88                                  )
    89 {
    90     assert(config);
    91     assert(files);
    92 
    93     for (int i = 0; files[i] != NULL; i++) {
    94         pmFPAfileActivateSingle(config->files, state, files[i], num); // Activated file
    95     }
    96     return;
    97 }
    98 
    99 // Iterate down the hierarchy, loading files; we can get away with this because we're working on skycells
    100 static pmFPAview *filesIterateDown(pmConfig *config // Configuration
    101                                   )
    102 {
    103     assert(config);
    104 
    105     pmFPAview *view = pmFPAviewAlloc(0);// Pointer into FPA hierarchy
    106     if (!pmFPAfileIOChecks(config, view, PM_FPA_BEFORE)) {
    107         return NULL;
    108     }
    109     view->chip = 0;
    110     if (!pmFPAfileIOChecks(config, view, PM_FPA_BEFORE)) {
    111         return NULL;
    112     }
    113     view->cell = 0;
    114     if (!pmFPAfileIOChecks(config, view, PM_FPA_BEFORE)) {
    115         return NULL;
    116     }
    117     view->readout = 0;
    118     if (!pmFPAfileIOChecks(config, view, PM_FPA_BEFORE)) {
    119         return NULL;
    120     }
    121     return view;
    122 }
    123 
    124 // Iterate up the hierarchy, writing files; we can get away with this because we're working on skycells
    125 static bool filesIterateUp(pmConfig *config // Configuration
    126                            )
    127 {
    128     assert(config);
    129 
    130     pmFPAview *view = pmFPAviewAlloc(0);// Pointer into FPA hierarchy
    131     view->chip = view->cell = view->readout = 0;
    132     if (!pmFPAfileIOChecks(config, view, PM_FPA_AFTER)) {
    133         return false;
    134     }
    135     view->readout = -1;
    136     if (!pmFPAfileIOChecks(config, view, PM_FPA_AFTER)) {
    137         return false;
    138     }
    139     view->cell = -1;
    140     if (!pmFPAfileIOChecks(config, view, PM_FPA_AFTER)) {
    141         return false;
    142     }
    143     view->chip = -1;
    144     if (!pmFPAfileIOChecks(config, view, PM_FPA_AFTER)) {
    145         return false;
    146     }
    147     psFree(view);
    148     return true;
    149 }
    150 
    151 // Write an image to a FITS file
    152 static bool writeImage(const char *name, // Name of image
    153                        psMetadata *header, // Header
    154                        const psImage *image, // Image
    155                        pmConfig *config // Configuration
    156                        )
    157 {
    158     assert(name);
    159     assert(image);
    160 
    161     psString resolved = pmConfigConvertFilename(name, config, true, true); // Resolved file name
    162     psFits *fits = psFitsOpen(resolved, "w");
    163     if (!fits) {
    164         psError(PS_ERR_IO, false, "Unable to open FITS file %s to write image.", resolved);
    165         psFree(resolved);
    166         return false;
    167     }
    168     if (!psFitsWriteImage(fits, header, image, 0, NULL)) {
    169         psError(PS_ERR_IO, false, "Unable to write FITS image %s.", resolved);
    170         psFitsClose(fits);
    171         psFree(resolved);
    172         return false;
    173     }
    174     psFitsClose(fits);
    175     psFree(resolved);
    176     return true;
    177 }
    178 
     10#include "ppStackLoop.h"
    17911
    18012bool ppStackLoop(pmConfig *config)
     
    18315
    18416    psTimerStart("PPSTACK_TOTAL");
     17    psTimerStart("PPSTACK_STEPS");
    18518
    186     psMetadata *recipe = psMetadataLookupMetadata(NULL, config->recipes, PPSTACK_RECIPE); // ppStack recipe
    187     psAssert(recipe, "We've thrown an error on this before.");
     19    ppStackOptions *options = ppStackOptionsAlloc(); // Options for stacking
    18820
    189     bool mdok;                          // Status of MD lookup
    190     bool tempDelete = psMetadataLookupBool(&mdok, recipe, "TEMP.DELETE"); // Delete temporary files?
    191     const char *tempDir = psMetadataLookupStr(NULL, recipe, "TEMP.DIR"); // Directory for temporary images
    192     if (!tempDir) {
    193         psError(PS_ERR_BAD_PARAMETER_VALUE, false, "Unable to find TEMP.DIR in recipe");
     21    // Setup
     22    psTrace("ppStack", 1, "Setup....\n");
     23    if (!ppStackSetup(options, config)) {
     24        psError(PS_ERR_UNKNOWN, false, "Unable to setup.");
     25        psFree(options);
     26        return false;
     27    }
     28    psLogMsg("ppStack", PS_LOG_INFO, "Stage 0: Setup: %f sec", psTimerClear("PPSTACK_STEPS"));
     29    ppStackMemDump("setup");
     30
     31
     32    // Preparation for stacking
     33    psTrace("ppStack", 1, "Preparation for stacking: merging sources, determining target PSF....\n");
     34    if (!ppStackPrepare(options, config)) {
     35        psError(PS_ERR_UNKNOWN, false, "Unable to prepare for stacking.");
     36        psFree(options);
     37        return false;
     38    }
     39    psLogMsg("ppStack", PS_LOG_INFO, "Stage 1: Load Sources and Generate Target PSF: %f sec",
     40             psTimerClear("PPSTACK_STEPS"));
     41    ppStackMemDump("prepare");
     42
     43
     44    // Convolve inputs
     45    psTrace("ppStack", 1, "Convolving inputs to target PSF....\n");
     46    if (!ppStackConvolve(options, config)) {
     47        psError(PS_ERR_UNKNOWN, false, "Unable to convolve images.");
     48        psFree(options);
     49        return false;
     50    }
     51    psLogMsg("ppStack", PS_LOG_INFO, "Stage 2: Generate Convolutions and Save: %f sec",
     52             psTimerClear("PPSTACK_STEPS"));
     53    ppStackMemDump("convolve");
     54
     55
     56    // Start threading
     57    ppStackThreadInit();
     58    ppStackThreadData *stack = ppStackThreadDataSetup(options, config);
     59    if (!stack) {
     60        psError(PS_ERR_IO, false, "Unable to initialise stack threads.");
     61        psFree(options);
    19462        return false;
    19563    }
    19664
    197     psString outputName = psStringCopy(psMetadataLookupStr(NULL, config->arguments, "OUTPUT")); // Name for temporary files
    198     const char *tempName = basename(outputName);
    199     if (!tempName) {
    200         psError(PS_ERR_BAD_PARAMETER_VALUE, false, "Unable to construct basename for temporary files.");
     65    // Initial combination
     66    psTrace("ppStack", 1, "Initial stack of convolved images....\n");
     67    if (!ppStackCombineInitial(stack, options, config)) {
     68        psError(PS_ERR_UNKNOWN, false, "Unable to perform initial combination.");
     69        psFree(stack);
     70        psFree(options);
    20171        return false;
    20272    }
     73    psLogMsg("ppStack", PS_LOG_INFO, "Stage 2: Generate Convolutions and Save: %f sec",
     74             psTimerClear("PPSTACK_STEPS"));
     75    ppStackMemDump("convolve");
     76    psLogMsg("ppStack", PS_LOG_INFO, "Stage 4: Make Initial Stack: %f sec", psTimerClear("PPSTACK_STEPS"));
    20377
    204     const char *tempImage = psMetadataLookupStr(NULL, recipe, "TEMP.IMAGE"); // Suffix for temporary images
    205     const char *tempMask = psMetadataLookupStr(NULL, recipe, "TEMP.MASK"); // Suffix for temporary masks
    206     const char *tempVariance = psMetadataLookupStr(NULL, recipe, "TEMP.VARIANCE"); // Suffix for temp variance maps
    207     if (!tempImage || !tempMask || !tempVariance) {
    208         psError(PS_ERR_BAD_PARAMETER_VALUE, false,
    209                 "Unable to find TEMP.IMAGE, TEMP.MASK and TEMP.VARIANCE in recipe");
     78
     79    // Pixel rejection
     80    psTrace("ppStack", 1, "Reject pixels....\n");
     81    if (!ppStackReject(options, config)) {
     82        psError(PS_ERR_UNKNOWN, false, "Unable to reject pixels.");
     83        psFree(stack);
     84        psFree(options);
    21085        return false;
    21186    }
     87    psLogMsg("ppStack", PS_LOG_INFO, "Stage 5: Pixel Rejection: %f sec", psTimerClear("PPSTACK_STEPS"));
     88    ppStackMemDump("reject");
    21289
    213     float threshold = psMetadataLookupF32(NULL, recipe, "THRESHOLD.MASK"); // Threshold for mask deconvolution
    214     float imageRej = psMetadataLookupF32(NULL, recipe, "IMAGE.REJ"); // Maximum fraction of image to reject
    215                                                                      // before rejecting entire image
    216     float poorFrac = psMetadataLookupF32(&mdok, recipe, "POOR.FRACTION"); // Fraction for "poor"
    217 
    218     const char *statsName = psMetadataLookupStr(&mdok, config->arguments, "STATS"); // Filename for statistics
    219     psMetadata *stats = NULL;           // Container for statistics
    220     FILE *statsFile = NULL;             // File stream for statistics
    221     if (statsName && strlen(statsName) > 0) {
    222         psString resolved = pmConfigConvertFilename(statsName, config, true, true); // Resolved filename
    223         statsFile = fopen(resolved, "w");
    224         if (!statsFile) {
    225             psError(PS_ERR_IO, true, "Unable to open statistics file %s for writing.\n", resolved);
    226             psFree(resolved);
    227             return false;
    228         } else {
    229             stats = psMetadataAlloc();
    230         }
    231         psFree(resolved);
    232     }
    233 
    234     pmFPAfile *output = psMetadataLookupPtr(NULL, config->files, "PPSTACK.OUTPUT"); // Output file
    235     if (!output) {
    236         psError(PS_ERR_UNEXPECTED_NULL, false, "Can't find output data!");
    237         return false;
    238     }
    239     int num = psMetadataLookupS32(NULL, config->arguments, "INPUTS.NUM"); // Number of inputs
    240 
    241     psMetadata *ppsub = psMetadataLookupMetadata(NULL, config->recipes, "PPSUB"); // PPSUB recipe
    242     int overlap = 2 * psMetadataLookupS32(NULL, ppsub,
    243                                           "KERNEL.SIZE"); // Overlap by kernel size between consecutive scans
    244 
    245     if (!pmConfigMaskSetBits(NULL, NULL, config)) {
    246         psError(PS_ERR_UNKNOWN, false, "Unable to determine mask value.");
    247         return false;
    248     }
    249 
    250     memDump("start");
    251 
    252     psLogMsg("ppStack", PS_LOG_INFO, "Stage 0 : Initialization and Configuration : %f sec", psTimerClear("PPSTACK_STEPS"));
    253 
    254     // Preparation iteration: Load the sources, and get a target PSF model
    255     psTrace("ppStack", 1, "Determining target PSF....\n");
    256     psArray *sourceLists = psArrayAlloc(num); // Individual lists of sources for matching
    257     pmPSF *targetPSF = NULL;            // Target PSF
    258     float sumExposure = NAN;            // Sum of exposure times
    259     if (psMetadataLookupBool(NULL, config->arguments, "HAVE.PSF")) {
    260         pmFPAfileActivate(config->files, false, NULL);
    261         fileActivation(config, prepareFiles, true);
    262         pmFPAview *view = filesIterateDown(config);
    263         if (!view) {
    264             return false;
    265         }
    266 
    267         // Generate list of PSFs
    268         psMetadataIterator *fileIter = psMetadataIteratorAlloc(config->files, PS_LIST_HEAD,
    269                                                                "^PPSTACK.INPUT$"); // Iterator
    270         psMetadataItem *fileItem; // Item from iteration
    271         psArray *psfs = psArrayAlloc(num); // PSFs for PSF envelope
    272         int numCols = 0, numRows = 0;   // Size of image
    273         int index = 0;                  // Index for file
    274         while ((fileItem = psMetadataGetAndIncrement(fileIter))) {
    275             assert(fileItem->type == PS_DATA_UNKNOWN);
    276             pmFPAfile *inputFile = fileItem->data.V; // An input file
    277             pmChip *chip = pmFPAviewThisChip(view, inputFile->fpa); // The chip: holds the PSF
    278             pmPSF *psf = psMetadataLookupPtr(NULL, chip->analysis, "PSPHOT.PSF"); // PSF
    279             if (!psf) {
    280                 psError(PS_ERR_UNKNOWN, false, "Unable to find PSF.");
    281                 psFree(view);
    282                 psFree(sourceLists);
    283                 psFree(fileIter);
    284                 psFree(psfs);
    285                 return false;
    286             }
    287             psfs->data[index] = psMemIncrRefCounter(psf);
    288             psMetadataRemoveKey(chip->analysis, "PSPHOT.PSF");
    289 
    290             pmCell *cell = pmFPAviewThisCell(view, inputFile->fpa); // Cell of interest
    291             pmHDU *hdu = pmHDUFromCell(cell);
    292             assert(hdu && hdu->header);
    293             int naxis1 = psMetadataLookupS32(NULL, hdu->header, "NAXIS1"); // Number of columns
    294             int naxis2 = psMetadataLookupS32(NULL, hdu->header, "NAXIS2"); // Number of rows
    295             if (naxis1 <= 0 || naxis2 <= 0) {
    296                 psError(PS_ERR_UNKNOWN, false, "Unable to determine size of image from PSF.");
    297                 psFree(view);
    298                 psFree(sourceLists);
    299                 psFree(fileIter);
    300                 psFree(psfs);
    301                 return false;
    302             }
    303             if (numCols == 0 && numRows == 0) {
    304                 numCols = naxis1;
    305                 numRows = naxis2;
    306             }
    307 
    308             pmReadout *ro = pmFPAviewThisReadout(view, inputFile->fpa); // Readout with sources
    309             psArray *sources = psMetadataLookupPtr(NULL, ro->analysis, "PSPHOT.SOURCES"); // Sources
    310             if (!sources) {
    311                 psError(PS_ERR_UNEXPECTED_NULL, false, "Unable to find sources in readout.");
    312                 return NULL;
    313             }
    314             sourceLists->data[index] = psMemIncrRefCounter(sources);
    315 
    316             // Re-do photometry if we don't trust the source lists
    317             if (psMetadataLookupBool(NULL, recipe, "PHOT")) {
    318                 psTrace("ppStack", 2, "Photometering input %d of %d....\n", index, num);
    319                 pmFPAfileActivate(config->files, false, NULL);
    320                 fileActivationSingle(config, convolveFiles, true, index);
    321                 pmFPAfile *file = pmFPAfileSelectSingle(config->files, "PPSTACK.INPUT", index); // File
    322                 pmFPAview *view = filesIterateDown(config);
    323                 if (!view) {
    324                     psFree(sourceLists);
    325                     psFree(targetPSF);
    326                     return false;
    327                 }
    328 
    329                 pmReadout *ro = pmFPAviewThisReadout(view, file->fpa); // Readout of interest
    330 
    331                 if (!ppStackInputPhotometry(ro, sources, config)) {
    332                     psError(PS_ERR_UNKNOWN, false, "Unable to do photometry on input sources");
    333                     psFree(sourceLists);
    334                     psFree(targetPSF);
    335                     return false;
    336                 }
    337 
    338                 psFree(view);
    339                 if (!filesIterateUp(config)) {
    340                     psFree(sourceLists);
    341                     psFree(targetPSF);
    342                     return false;
    343                 }
    344                 pmFPAfileActivate(config->files, false, NULL);
    345                 fileActivation(config, prepareFiles, true);
    346             }
    347 
    348             index++;
    349         }
    350         psFree(fileIter);
    351 
    352         // Zero point calibration
    353         sumExposure = ppStackSourcesTransparency(sourceLists, view, config);
    354         if (!isfinite(sumExposure) || sumExposure <= 0) {
    355             psError(PS_ERR_UNKNOWN, false, "Unable to calculate transparency differences");
    356             psFree(sourceLists);
    357             psFree(targetPSF);
    358             return false;
    359         }
    360 
    361         // Generate target PSF
    362         targetPSF = ppStackPSF(config, numCols, numRows, psfs);
    363         psFree(psfs);
    364         if (!targetPSF) {
    365             psError(PS_ERR_UNKNOWN, false, "Unable to determine output PSF.");
    366             psFree(sourceLists);
    367             psFree(view);
    368             return false;
    369         }
    370         psMetadataAddPtr(config->arguments, PS_LIST_TAIL, "PSF.TARGET", PS_DATA_UNKNOWN,
    371                          "Target PSF for stack", targetPSF);
    372 
    373         pmChip *outChip = pmFPAviewThisChip(view, output->fpa); // Output chip
    374         psMetadataAddPtr(outChip->analysis, PS_LIST_TAIL, "PSPHOT.PSF", PS_DATA_UNKNOWN,
    375                          "Target PSF", targetPSF);
    376         outChip->data_exists = true;
    377 
    378         psFree(view);
    379         if (!filesIterateUp(config)) {
    380             return false;
    381         }
    382     }
    383 
    384     psLogMsg("ppStack", PS_LOG_INFO, "Stage 1 : Load Sources and Generate Target PSF : %f sec", psTimerClear("PPSTACK_STEPS"));
    385     memDump("psf");
    386 
    387     psArray *imageNames = psArrayAlloc(num);
    388     psArray *maskNames = psArrayAlloc(num);
    389     psArray *varianceNames = psArrayAlloc(num);
    390     for (int i = 0; i < num; i++) {
    391         psString imageName = NULL, maskName = NULL, varianceName = NULL; // Names for convolved images
    392         psStringAppend(&imageName, "%s/%s.%d.%s", tempDir, tempName, i, tempImage);
    393         psStringAppend(&maskName, "%s/%s.%d.%s", tempDir, tempName, i, tempMask);
    394         psStringAppend(&varianceName, "%s/%s.%d.%s", tempDir, tempName, i, tempVariance);
    395         psTrace("ppStack", 5, "Temporary files: %s %s %s\n", imageName, maskName, varianceName);
    396         imageNames->data[i] = imageName;
    397         maskNames->data[i] = maskName;
    398         varianceNames->data[i] = varianceName;
    399     }
    400     // Free the outputName that we grabbed above to set up tempName.
    401     psFree(outputName);
    402 
    403     // Generate convolutions and write them to disk
    404     psTrace("ppStack", 1, "Convolving inputs to target PSF....\n");
    405     psArray *cells = psArrayAlloc(num); // Cells for convolved images --- a handle for reading again
    406     psArray *subKernels = psArrayAlloc(num); // Subtraction kernels --- required in the stacking
    407     psArray *subRegions = psArrayAlloc(num); // Subtraction regions --- required in the stacking
    408     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 0); // Random number generator
    409     int numGood = 0;                    // Number of good frames
    410     int numCols = 0, numRows = 0;       // Size of image
    411     psVector *inputMask = psVectorAlloc(num, PS_TYPE_VECTOR_MASK); // Mask for inputs
    412     psVectorInit(inputMask, 0);
    413     psVector *matchChi2 = psVectorAlloc(num, PS_TYPE_F32); // chi^2 for stamps when matching
    414     psVectorInit(matchChi2, NAN);
    415     psVector *weightings = psVectorAlloc(num, PS_TYPE_F32); // Combination weightings for images (1/noise^2)
    416     psVectorInit(weightings, NAN);
    417     psList *fpaList = psListAlloc(NULL); // List of input FPAs, for concept averaging
    418     psList *cellList = psListAlloc(NULL); // List of input cells, for concept averaging
    419     psArray *covariances = psArrayAlloc(num); // Covariance matrices
    420     for (int i = 0; i < num; i++) {
    421         psTrace("ppStack", 2, "Convolving input %d of %d to target PSF....\n", i, num);
    422         pmFPAfileActivate(config->files, false, NULL);
    423         fileActivationSingle(config, convolveFiles, true, i);
    424         pmFPAfile *file = pmFPAfileSelectSingle(config->files, "PPSTACK.INPUT", i); // File of interest
    425         pmFPAview *view = filesIterateDown(config);
    426         if (!view) {
    427             psFree(sourceLists);
    428             psFree(targetPSF);
    429             psFree(rng);
    430             psFree(inputMask);
    431             psFree(matchChi2);
    432             psFree(fpaList);
    433             psFree(cellList);
    434             psFree(covariances);
    435             return false;
    436         }
    437 
    438         pmReadout *readout = pmFPAviewThisReadout(view, file->fpa); // Input readout
    439         psFree(view);
    440 
    441         if (numCols == 0 && numRows == 0) {
    442             numCols = readout->image->numCols;
    443             numRows = readout->image->numRows;
    444         } else if (numCols != readout->image->numCols || numRows != readout->image->numRows) {
    445             psError(PS_ERR_UNKNOWN, true, "Sizes of input images don't match: %dx%d vs %dx%d",
    446                     readout->image->numCols, readout->image->numRows, numCols, numRows);
    447             psFree(sourceLists);
    448             psFree(targetPSF);
    449             psFree(rng);
    450             psFree(inputMask);
    451             psFree(matchChi2);
    452             psFree(fpaList);
    453             psFree(cellList);
    454             psFree(covariances);
    455             return false;
    456         }
    457 
    458         // Background subtraction, scaling and normalisation is performed automatically by the image matching
    459         psArray *regions = NULL, *kernels = NULL; // Regions and kernels used in subtraction
    460         psTimerStart("PPSTACK_MATCH");
    461 
    462         if (!ppStackMatch(readout, &regions, &kernels, &matchChi2->data.F32[i], &weightings->data.F32[i],
    463                           sourceLists->data[i], targetPSF, rng, config)) {
    464             psErrorStackPrint(stderr, "Unable to match image %d --- ignoring.", i);
    465             inputMask->data.PS_TYPE_VECTOR_MASK_DATA[i] = PPSTACK_MASK_MATCH;
    466             psErrorClear();
    467             continue;
    468         }
    469         covariances->data[i] = psMemIncrRefCounter(readout->covariance);
    470 
    471         if (stats) {
    472             pmSubtractionKernels *kernels = psMetadataLookupPtr(NULL, readout->analysis,
    473                                                                 PM_SUBTRACTION_ANALYSIS_KERNEL);// Conv kernel
    474             psMetadataAddF32(stats, PS_LIST_TAIL, "TIME_MATCH", PS_META_DUPLICATE_OK,
    475                              "Time to match PSF", psTimerMark("PPSTACK_MATCH"));
    476             psMetadataAddF32(stats, PS_LIST_TAIL, "STAMP.MEAN", PS_META_DUPLICATE_OK,
    477                              "Mean deviation for stamps", kernels->mean);
    478             psMetadataAddF32(stats, PS_LIST_TAIL, "STAMP.RMS", PS_META_DUPLICATE_OK,
    479                              "RMS deviation for stamps", kernels->rms);
    480             psMetadataAddF32(stats, PS_LIST_TAIL, "STAMP.NUM", PS_META_DUPLICATE_OK,
    481                              "Number of stamps", kernels->numStamps);
    482             float deconv = psMetadataLookupF32(NULL, readout->analysis,
    483                                                PM_SUBTRACTION_ANALYSIS_DECONV_MAX); // Deconvolution fraction
    484             psMetadataAddF32(stats, PS_LIST_TAIL, "KERNEL.DECONV", PS_META_DUPLICATE_OK,
    485                              "Deconvolution fraction for kernel", deconv);
    486             psMetadataAddF32(stats, PS_LIST_TAIL, "PPSTACK.WEIGHTING", PS_META_DUPLICATE_OK,
    487                              "Weighting for image", weightings->data.F32[i]);
    488         }
    489         psLogMsg("ppStack", PS_LOG_INFO, "Time to match image %d: %f sec", i, psTimerClear("PPSTACK_MATCH"));
    490 
    491         subRegions->data[i] = regions;
    492         subKernels->data[i] = kernels;
    493 
    494         // Write the temporary convolved files
    495         pmHDU *hdu = readout->parent->parent->parent->hdu; // HDU for convolved image
    496         assert(hdu);
    497         writeImage(imageNames->data[i], hdu->header, readout->image, config);
    498         psMetadata *maskHeader = psMetadataCopy(NULL, hdu->header); // Copy of header, for mask
    499         pmConfigMaskWriteHeader(config, maskHeader);
    500         writeImage(maskNames->data[i], maskHeader, readout->mask, config);
    501         psFree(maskHeader);
    502         psImageCovarianceTransfer(readout->variance, readout->covariance);
    503         writeImage(varianceNames->data[i], hdu->header, readout->variance, config);
    504 #ifdef TESTING
    505         {
    506             psString name = NULL;
    507             psStringAppend(&name, "covariance_%d.fits", i);
    508             writeImage(name, hdu->header, readout->covariance->image, config);
    509             psFree(name);
    510         }
    511 #endif
    512 
    513         pmCell *inCell = readout->parent; // Input cell
    514 
    515         psListAdd(cellList, PS_LIST_TAIL, inCell);
    516         psListAdd(fpaList, PS_LIST_TAIL, inCell->parent->parent);
    517 
    518         cells->data[i] = psMemIncrRefCounter(inCell);
    519         if (!filesIterateUp(config)) {
    520             psFree(fpaList);
    521             psFree(cellList);
    522             psFree(covariances);
    523             return false;
    524         }
    525         numGood++;
    526 
    527         memDump("match");
    528     }
    529     psFree(sourceLists);
    530     psFree(targetPSF);
    531     psFree(rng);
    532 
    533     psLogMsg("ppStack", PS_LOG_INFO, "Stage 2 : Generate Convolutions and Save : %f sec", psTimerClear("PPSTACK_STEPS"));
    534 
    535     if (numGood == 0) {
    536         psError(PS_ERR_UNKNOWN, false, "No good images to combine.");
    537         psFree(subKernels);
    538         psFree(subRegions);
    539         psFree(cells);
    540         psFree(inputMask);
    541         psFree(matchChi2);
    542         psFree(fpaList);
    543         psFree(cellList);
    544         psFree(covariances);
    545         return false;
    546     }
    547 
    548 
    549     // Update concepts for output
    550     {
    551         pmFPAview view;                 // View for output
    552         view.chip = view.cell = view.readout = 0;
    553         pmCell *outCell = pmFPAfileThisCell(config->files, &view, "PPSTACK.OUTPUT"); // Output cell
    554         pmFPA *outFPA = outCell->parent->parent; // Output FPA
    555         pmConceptsAverageFPAs(outFPA, fpaList);
    556         pmConceptsAverageCells(outCell, cellList, NULL, NULL, true);
    557         psFree(fpaList);
    558         psFree(cellList);
    559 
    560         // Update the value of a concept
    561 #define UPDATE_CONCEPT(SOURCE, NAME, VALUE) { \
    562             psMetadataItem *item = psMetadataLookup(SOURCE->concepts, NAME); \
    563             psAssert(item, "Concept should be present"); \
    564             psAssert(item->type == PS_TYPE_F32, "Concept should be F32"); \
    565             item->data.F32 = VALUE; \
    566         }
    567 
    568         UPDATE_CONCEPT(outFPA,  "FPA.EXPOSURE",  sumExposure);
    569         UPDATE_CONCEPT(outCell, "CELL.EXPOSURE", sumExposure);
    570         UPDATE_CONCEPT(outCell, "CELL.DARKTIME", NAN);
    571     }
    572 
    573 
    574     // Reject images out-of-hand on the basis of their match chi^2
    575     {
    576         psVector *values = psVectorAllocEmpty(num, PS_TYPE_F32); // Values to sort
    577         for (int i = 0; i < num; i++) {
    578             if (inputMask->data.PS_TYPE_VECTOR_MASK_DATA[i] & PPSTACK_MASK_ALL) {
    579                 continue;
    580             }
    581             values->data.F32[values->n++] = matchChi2->data.F32[i];
    582         }
    583         assert(values->n == numGood);
    584         if (!psVectorSortInPlace(values)) {
    585             psError(PS_ERR_UNKNOWN, false, "Unable to sort vector.");
    586             psFree(subKernels);
    587             psFree(subRegions);
    588             psFree(cells);
    589             psFree(inputMask);
    590             psFree(matchChi2);
    591             psFree(values);
    592             psFree(covariances);
    593             return false;
    594         }
    595         float median = numGood % 2 ? values->data.F32[numGood / 2] :
    596             0.5 * (values->data.F32[numGood / 2 - 1] + values->data.F32[numGood / 2]);
    597 
    598         float rms = 0.74 * (values->data.F32[numGood * 3 / 4] -
    599                             values->data.F32[numGood / 4]); // Estimated RMS from interquartile range
    600 
    601         psFree(values);
    602 
    603         float rej = psMetadataLookupF32(NULL, recipe, "MATCH.REJ"); // Rejection threshold (stdevs)
    604         if (isfinite(rej)) {
    605             float thresh = median + rej * rms; // Threshold for rejection
    606             psLogMsg("ppStack", PS_LOG_INFO, "chi^2 rejection threshold = %f + %f * %f = %f",
    607                      median, rej, rms, thresh);
    608 
    609             int numRej = 0;                 // Number rejected
    610             numGood = 0;                    // Number of good images
    611             for (int i = 0; i < num; i++) {
    612               if (inputMask->data.PS_TYPE_VECTOR_MASK_DATA[i] & PPSTACK_MASK_ALL) {
    613                     continue;
    614                 }
    615                 if (matchChi2->data.F32[i] > thresh) {
    616                     numRej++;
    617                     inputMask->data.PS_TYPE_VECTOR_MASK_DATA[i] |= PPSTACK_MASK_CHI2;
    618                     psLogMsg("ppStack", PS_LOG_INFO, "Rejecting image %d because of large matching chi^2: %f",
    619                              i, matchChi2->data.F32[i]);
    620                 } else {
    621                     psLogMsg("ppStack", PS_LOG_INFO, "Image %d has matching chi^2: %f",
    622                              i, matchChi2->data.F32[i]);
    623                     numGood++;
    624                 }
    625             }
    626         }
    627     }
    628 
    629     if (numGood == 0) {
    630         psError(PS_ERR_UNKNOWN, false, "No good images to combine.");
    631         psFree(subKernels);
    632         psFree(subRegions);
    633         psFree(cells);
    634         psFree(inputMask);
    635         psFree(matchChi2);
    636         psFree(covariances);
    637         return false;
    638     }
    639 
    640 #ifdef TESTING
    641     psTraceSetLevel("psModules.imcombine", 7);
    642 #endif
    643 
    644     psLogMsg("ppStack", PS_LOG_INFO, "Stage 3 : Basic Image Rejection  : %f sec", psTimerClear("PPSTACK_STEPS"));
    645 
    646     // Start threading
    647     ppStackThreadInit();
    648     ppStackThreadData *stack = ppStackThreadDataSetup(cells, imageNames, maskNames, varianceNames,
    649                                                       covariances, config);
    650     if (!stack) {
    651         psError(PS_ERR_IO, false, "Unable to initialise stack threads.");
    652         psFree(subKernels);
    653         psFree(subRegions);
    654         psFree(inputMask);
    655         psFree(matchChi2);
    656         psFree(cells);
    657         psFree(covariances);
    658         return false;
    659     }
    660 
    661     psTimerStart("PPSTACK_INITIAL");
    662 
    663     memDump("preinitial");
    664 
    665     // Stack the convolved files
    666     psTrace("ppStack", 1, "Initial stack of convolved images....\n");
    667     pmReadout *outRO = NULL;            // Output readout
    668     pmFPAview *view = NULL;             // View to readout
    669     psArray *inspect = NULL;            // Array of arrays of pixels to inspect
    670     {
    671         int row0, col0;                 // Offset for readout
    672         int numCols, numRows;           // Size of readout
    673         ppStackThread *thread = stack->threads->data[0]; // Representative thread
    674         if (!pmReadoutStackSetOutputSize(&col0, &row0, &numCols, &numRows, thread->readouts)) {
    675             psError(PS_ERR_UNKNOWN, false, "problem setting output readout size.");
    676             psFree(subKernels);
    677             psFree(subRegions);
    678             psFree(stack);
    679             psFree(inputMask);
    680             psFree(matchChi2);
    681             psFree(cells);
    682             psFree(covariances);
    683             return false;
    684         }
    685 
    686         pmFPAfileActivate(config->files, false, NULL);
    687         fileActivation(config, combineFiles, true);
    688         view = filesIterateDown(config);
    689         if (!view) {
    690             psFree(subKernels);
    691             psFree(subRegions);
    692             psFree(stack);
    693             psFree(inputMask);
    694             psFree(matchChi2);
    695             psFree(cells);
    696             psFree(covariances);
    697             return false;
    698         }
    699 
    700         pmCell *outCell = pmFPAfileThisCell(config->files, view, "PPSTACK.OUTPUT"); // Output cell
    701         outRO = pmReadoutAlloc(outCell); // Output readout
    702 
    703         psString maskBadStr = psMetadataLookupStr(NULL, recipe, "MASK.BAD"); // Name of bits to mask for bad
    704         psImageMaskType maskBad = pmConfigMaskGet(maskBadStr, config); // Bits to mask for bad pixels
    705         if (!pmReadoutStackDefineOutput(outRO, col0, row0, numCols, numRows, true, true, maskBad)) {
    706             psError(PS_ERR_UNKNOWN, false, "Unable to prepare output.");
    707             psFree(subKernels);
    708             psFree(subRegions);
    709             psFree(stack);
    710             psFree(inputMask);
    711             psFree(matchChi2);
    712             psFree(view);
    713             psFree(outRO);
    714             psFree(cells);
    715             psFree(covariances);
    716             return false;
    717         }
    718 
    719         psFree(cells);
    720 
    721         bool status;                    // Status of read
    722         int numChunk;                   // Number of chunks
    723         for (numChunk = 0; true; numChunk++) {
    724             ppStackThread *thread = ppStackThreadRead(&status, stack, config, numChunk, overlap);
    725             if (!status) {
    726                 // Something went wrong
    727                 psError(PS_ERR_UNKNOWN, false, "Unable to read chunk %d", numChunk);
    728                 psFree(subKernels);
    729                 psFree(subRegions);
    730                 psFree(stack);
    731                 psFree(inputMask);
    732                 psFree(matchChi2);
    733                 psFree(view);
    734                 psFree(outRO);
    735                 psFree(covariances);
    736                 return false;
    737             }
    738             if (!thread) {
    739                 // Nothing more to read
    740                 break;
    741             }
    742 
    743             // call: ppStackReadoutInitial(config, outRO, readouts, subRegions, subKernels)
    744             psThreadJob *job = psThreadJobAlloc("PPSTACK_INITIAL_COMBINE"); // Job to start
    745             psArrayAdd(job->args, 1, thread);
    746             psArrayAdd(job->args, 1, config);
    747             psArrayAdd(job->args, 1, outRO);
    748             psArrayAdd(job->args, 1, inputMask);
    749             psArrayAdd(job->args, 1, weightings);
    750             psArrayAdd(job->args, 1, matchChi2);
    751             if (!psThreadJobAddPending(job)) {
    752                 psFree(job);
    753                 psFree(subKernels);
    754                 psFree(subRegions);
    755                 psFree(stack);
    756                 psFree(inputMask);
    757                 psFree(weightings);
    758                 psFree(matchChi2);
    759                 psFree(view);
    760                 psFree(outRO);
    761                 psFree(covariances);
    762                 return false;
    763             }
    764             psFree(job);
    765         }
    766 
    767         if (!psThreadPoolWait(false)) {
    768             psError(PS_ERR_UNKNOWN, false, "Unable to do initial combination.");
    769             psFree(subKernels);
    770             psFree(subRegions);
    771             psFree(stack);
    772             psFree(inputMask);
    773             psFree(matchChi2);
    774             psFree(view);
    775             psFree(outRO);
    776             psFree(covariances);
    777             return false;
    778         }
    779 
    780         // Harvest the jobs, gathering the inspection lists
    781         inspect = psArrayAlloc(num);
    782         for (int i = 0; i < num; i++) {
    783             if (inputMask->data.PS_TYPE_VECTOR_MASK_DATA[i]) {
    784                 continue;
    785             }
    786             inspect->data[i] = psArrayAllocEmpty(numChunk);
    787         }
    788         psThreadJob *job;               // Completed job
    789         while ((job = psThreadJobGetDone())) {
    790             psAssert(strcmp(job->type, "PPSTACK_INITIAL_COMBINE") == 0,
    791                      "Job has incorrect type: %s", job->type);
    792             psArray *results = job->results; // Results of job
    793             for (int i = 0; i < num; i++) {
    794                 if (inputMask->data.PS_TYPE_VECTOR_MASK_DATA[i]) {
    795                     continue;
    796                 }
    797                 inspect->data[i] = psArrayAdd(inspect->data[i], 1, results->data[i]);
    798             }
    799             psFree(job);
    800         }
    801 
    802         memDump("initial");
    803     }
    804 
    805 #ifdef TESTING
    806     writeImage("combined_initial.fits", NULL, outRO->image, config);
    807 #endif
    808 
    809     if (stats) {
    810         psMetadataAddF32(stats, PS_LIST_TAIL, "TIME_INITIAL", 0,
    811                          "Time to make initial stack", psTimerMark("PPSTACK_INITIAL"));
    812     }
    813     psLogMsg("ppStack", PS_LOG_INFO, "Stage 4 : Make Initial Stack : %f sec", psTimerClear("PPSTACK_STEPS"));
    814     psLogMsg("ppStack", PS_LOG_INFO, "Time to make initial stack: %f sec", psTimerClear("PPSTACK_INITIAL"));
    815 
    816     psTimerStart("PPSTACK_REJECT");
    817 
    818     // Pixel rejection
    819     psArray *rejected = psArrayAlloc(num);
    820     {
    821         int numRejected = 0;        // Number of inputs rejected completely
    822 
    823         // Count images rejected out of hand
    824         for (int i = 0; i < num; i++) {
    825             if (inputMask->data.PS_TYPE_VECTOR_MASK_DATA[i]) {
    826                 numRejected++;
    827             }
    828         }
    829 
    830         for (int i = 0; i < num; i++) {
    831             if (inputMask->data.PS_TYPE_VECTOR_MASK_DATA[i]) {
    832                 continue;
    833             }
    834 
    835             psThreadJob *job = psThreadJobAlloc("PPSTACK_INSPECT"); // Job to start
    836             psArrayAdd(job->args, 1, inspect);
    837             PS_ARRAY_ADD_SCALAR(job->args, i, PS_TYPE_S32);
    838             if (!psThreadJobAddPending(job)) {
    839                 psFree(job);
    840                 psFree(subKernels);
    841                 psFree(subRegions);
    842                 psFree(stack);
    843                 psFree(inputMask);
    844                 psFree(view);
    845                 psFree(outRO);
    846                 psFree(inspect);
    847                 psFree(rejected);
    848                 psFree(covariances);
    849                 psFree(matchChi2);
    850                 return false;
    851             }
    852             psFree(job);
    853         }
    854 
    855         if (!psThreadPoolWait(true)) {
    856             psError(PS_ERR_UNKNOWN, false, "Unable to concatenate inspection lists.");
    857             psFree(subKernels);
    858             psFree(subRegions);
    859             psFree(stack);
    860             psFree(inputMask);
    861             psFree(view);
    862             psFree(outRO);
    863             psFree(inspect);
    864             psFree(rejected);
    865             psFree(covariances);
    866             psFree(matchChi2);
    867             return false;
    868         }
    869 
    870         if (psMetadataLookupS32(NULL, config->arguments, "-threads") > 0) {
    871             pmStackRejectThreadsInit();
    872         }
    873 
    874         int stride = psMetadataLookupS32(NULL, ppsub, "STRIDE"); // Size of convolution patches
    875 
    876         // Reject bad pixels
    877         for (int i = 0; i < num; i++) {
    878             if (inputMask->data.PS_TYPE_VECTOR_MASK_DATA[i]) {
    879                 continue;
    880             }
    881             psTimerStart("PPSTACK_REJECT");
    882 
    883 #ifdef TESTING
    884             {
    885                 psImage *mask = psPixelsToMask(NULL, inspect->data[i],
    886                                                psRegionSet(0, numCols - 1, 0, numRows - 1),
    887                                                0xff); // Mask image
    888                 psString name = NULL;           // Name of image
    889                 psStringAppend(&name, "inspect_%03d.fits", i);
    890                 psFits *fits = psFitsOpen(name, "w");
    891                 psFree(name);
    892                 psFitsWriteImage(fits, NULL, mask, 0, NULL);
    893                 psFree(mask);
    894                 psFitsClose(fits);
    895             }
    896 #endif
    897 
    898             psPixels *reject = pmStackReject(inspect->data[i], numCols, numRows, threshold, poorFrac, stride,
    899                                              subRegions->data[i], subKernels->data[i]); // Rejected pixels
    900 
    901 #ifdef TESTING
    902             {
    903                 psImage *mask = psPixelsToMask(NULL, reject, psRegionSet(0, numCols - 1, 0, numRows - 1),
    904                                                0xff); // Mask image
    905                 psString name = NULL;           // Name of image
    906                 psStringAppend(&name, "reject_%03d.fits", i);
    907                 psFits *fits = psFitsOpen(name, "w");
    908                 psFree(name);
    909                 psFitsWriteImage(fits, NULL, mask, 0, NULL);
    910                 psFree(mask);
    911                 psFitsClose(fits);
    912             }
    913 #endif
    914 
    915             psFree(inspect->data[i]);
    916             inspect->data[i] = NULL;
    917 
    918             if (!reject) {
    919                 psWarning("Rejection on image %d didn't work --- reject entire image.", i);
    920                 numRejected++;
    921                 inputMask->data.PS_TYPE_VECTOR_MASK_DATA[i] = PPSTACK_MASK_REJECT;
    922             } else {
    923                 float frac = reject->n / (float)(numCols * numRows); // Pixel fraction
    924                 psLogMsg("ppStack", PS_LOG_INFO, "%ld pixels rejected from image %d (%.1f%%)",
    925                          reject->n, i, frac * 100.0);
    926                 if (frac > imageRej) {
    927                     psWarning("Image %d rejected completely because rejection fraction (%.3f) "
    928                               "exceeds limit (%.3f)", i, frac, imageRej);
    929                     psFree(reject);
    930                     // reject == NULL means reject image completely
    931                     reject = NULL;
    932                     inputMask->data.PS_TYPE_VECTOR_MASK_DATA[i] = PPSTACK_MASK_BAD;
    933                     numRejected++;
    934                 }
    935             }
    936 
    937             // Images without a list of rejected pixels (the list may be empty) are rejected completely
    938             rejected->data[i] = reject;
    939 
    940             if (stats) {
    941                 psMetadataAddF32(stats, PS_LIST_TAIL, "TIME_REJECT", PS_META_DUPLICATE_OK,
    942                                  "Time to perform rejection", psTimerMark("PPSTACK_REJECT"));
    943                 psMetadataAddS32(stats, PS_LIST_TAIL, "REJECT_PIXELS", PS_META_DUPLICATE_OK,
    944                                  "Number of pixels rejected", reject ? reject->n : 0);
    945             }
    946             psLogMsg("ppStack", PS_LOG_INFO, "Time to perform rejection on image %d: %f sec", i,
    947                      psTimerClear("PPSTACK_REJECT"));
    948         }
    949 
    950         psFree(inspect);
    951         psFree(subKernels);
    952         psFree(subRegions);
    953 
    954         if (numRejected >= num - 1) {
    955             psError(PS_ERR_UNKNOWN, true, "All inputs completely rejected; unable to proceed.");
    956             psFree(stack);
    957             psFree(rejected);
    958             psFree(inputMask);
    959             psFree(view);
    960             psFree(outRO);
    961             psFree(covariances);
    962             psFree(matchChi2);
    963             return false;
    964         }
    965 
    966         if (stats) {
    967             psMetadataAddS32(stats, PS_LIST_TAIL, "REJECT_IMAGES", 0,
    968                              "Number of images rejected completely", numRejected);
    969         }
    970     }
    971 
    972     psLogMsg("ppStack", PS_LOG_INFO, "Stage 5 : Pixel Rejection : %f sec", psTimerClear("PPSTACK_STEPS"));
    973     psTimerStart("PPSTACK_FINAL");
    974 
    975     memDump("reject");
    97690
    97791    // Final combination
    97892    psTrace("ppStack", 2, "Final stack of convolved images....\n");
    979     {
    980         stack->lastScan = 0;            // Reset read
    981         bool status;                    // Status of read
    982         for (int numChunk = 0; true; numChunk++) {
    983             ppStackThread *thread = ppStackThreadRead(&status, stack, config, numChunk, 0);
    984             if (!status) {
    985                 // Something went wrong
    986                 psError(PS_ERR_UNKNOWN, false, "Unable to read chunk %d", numChunk);
    987                 psFree(stack);
    988                 psFree(rejected);
    989                 psFree(inputMask);
    990                 psFree(view);
    991                 psFree(outRO);
    992                 psFree(covariances);
    993                 psFree(matchChi2);
    994                 return false;
    995             }
    996             if (!thread) {
    997                 // Nothing more to read
    998                 break;
    999             }
     93    if (!ppStackCombineFinal(stack, options, config)) {
     94        psError(PS_ERR_UNKNOWN, false, "Unable to perform final combination.");
     95        psFree(stack);
     96        psFree(options);
     97        return false;
     98    }
     99    psLogMsg("ppStack", PS_LOG_INFO, "Stage 6: Final Stack: %f sec", psTimerClear("PPSTACK_STEPS"));
     100    ppStackMemDump("final");
    1000101
    1001             // call: ppStackReadoutFinal(config, outRO, readouts, rejected)
    1002             psThreadJob *job = psThreadJobAlloc("PPSTACK_FINAL_COMBINE"); // Job to start
    1003             psArrayAdd(job->args, 1, thread);
    1004             psArrayAdd(job->args, 1, config);
    1005             psArrayAdd(job->args, 1, outRO);
    1006             psArrayAdd(job->args, 1, inputMask);
    1007             psArrayAdd(job->args, 1, rejected);
    1008             psArrayAdd(job->args, 1, weightings);
    1009             psArrayAdd(job->args, 1, matchChi2);
    1010             if (!psThreadJobAddPending(job)) {
    1011                 psFree(job);
    1012                 psFree(stack);
    1013                 psFree(rejected);
    1014                 psFree(inputMask);
    1015                 psFree(view);
    1016                 psFree(outRO);
    1017                 psFree(covariances);
    1018                 psFree(matchChi2);
    1019                 return false;
    1020             }
    1021             psFree(job);
    1022         }
    1023102
    1024         if (!psThreadPoolWait(true)) {
    1025             psError(PS_ERR_UNKNOWN, false, "Unable to do final combination.");
    1026             psFree(stack);
    1027             psFree(inputMask);
    1028             psFree(rejected);
    1029             psFree(view);
    1030             psFree(outRO);
    1031             psFree(covariances);
    1032             psFree(matchChi2);
    1033             return false;
    1034         }
     103    // Clean up
     104    psTrace("ppStack", 2, "Cleaning up after combination....\n");
     105    if (!ppStackCombineFinal(stack, options, config)) {
     106        psError(PS_ERR_UNKNOWN, false, "Unable to clean up.");
     107        psFree(stack);
     108        psFree(options);
     109        return false;
    1035110    }
     111    psLogMsg("ppStack", PS_LOG_INFO, "Stage 7: WCS & JPEGS: %f sec", psTimerClear("PPSTACK_STEPS"));
     112    ppStackMemDump("cleanup");
    1036113
    1037     memDump("final");
    1038 
    1039 #ifdef TESTING
    1040     writeImage("combined_final.fits", NULL, outRO->image, config);
    1041 #endif
    1042 
    1043     // Sum covariance matrices
    1044     for (int i = 0; i < num; i++) {
    1045         if (inputMask->data.U8[i]) {
    1046             psFree(covariances->data[i]);
    1047             covariances->data[i] = NULL;
    1048         }
    1049     }
    1050     outRO->covariance = psImageCovarianceSum(covariances);
    1051     psFree(covariances);
    1052     psFree(matchChi2);
    1053 
    1054     if (stats) {
    1055         psMetadataAddF32(stats, PS_LIST_TAIL, "TIME_FINAL", 0,
    1056                          "Time to make final stack", psTimerMark("PPSTACK_FINAL"));
    1057     }
    1058 
    1059     psLogMsg("ppStack", PS_LOG_INFO, "Stage 6 : Final Stack : %f sec", psTimerClear("PPSTACK_STEPS"));
    1060     psLogMsg("ppStack", PS_LOG_INFO, "Time to make final stack: %f sec", psTimerClear("PPSTACK_FINAL"));
    1061 
    1062     psTrace("ppStack", 2, "Cleaning up after combination....\n");
    1063 
    1064 #if 0
    1065     // Ensure masked regions really look masked
    1066     {
    1067         psString maskBadStr = psMetadataLookupStr(NULL, recipe, "MASK.BAD"); // Name of bits for bad
    1068         psImageMaskType maskBad = pmConfigMaskGet(maskBadStr, config); // Bits to mask for bad pixels
    1069         if (!pmReadoutMaskApply(outRO, maskBad)) {
    1070             psWarning("Unable to apply mask");
    1071         }
    1072     }
    1073 #endif
    1074 
    1075     // Close up
    1076     bool wcsDone = false;           // Have we done the WCS?
    1077     for (int i = 0; i < num; i++) {
    1078         if (inputMask->data.PS_TYPE_VECTOR_MASK_DATA[i]) {
    1079             continue;
    1080         }
    1081 
    1082         ppStackThread *thread = stack->threads->data[0]; // Representative stack
    1083         pmReadout *inRO = thread->readouts->data[i]; // Template readout
    1084         if (inRO && !wcsDone) {
    1085             // Copy astrometry over
    1086             wcsDone = true;
    1087             pmHDU *inHDU = pmHDUFromCell(inRO->parent); // Template HDU
    1088             pmHDU *outHDU = pmHDUFromCell(outRO->parent); // Output HDU
    1089             pmChip *outChip = outRO->parent->parent; // Output chip
    1090             pmFPA *outFPA = outChip->parent; // Output FPA
    1091             if (!outHDU || !inHDU) {
    1092                 psWarning("Unable to find HDU at FPA level to copy astrometry.");
    1093             } else {
    1094                 if (!pmAstromReadWCS(outFPA, outChip, inHDU->header, 1.0)) {
    1095                     psErrorClear();
    1096                     psWarning("Unable to read WCS astrometry from input FPA.");
    1097                     wcsDone = false;
    1098                 } else {
    1099                     if (!outHDU->header) {
    1100                         outHDU->header = psMetadataAlloc();
    1101                     }
    1102                     if (!pmAstromWriteWCS(outHDU->header, outFPA, outChip, WCS_TOLERANCE)) {
    1103                         psErrorClear();
    1104                         psWarning("Unable to write WCS astrometry to output FPA.");
    1105                         wcsDone = false;
    1106                     }
    1107                 }
    1108             }
    1109         }
    1110 
    1111         if (tempDelete) {
    1112             psString imageResolved = pmConfigConvertFilename(imageNames->data[i], config, false, false);
    1113             psString maskResolved = pmConfigConvertFilename(maskNames->data[i], config, false, false);
    1114             psString varianceResolved = pmConfigConvertFilename(varianceNames->data[i], config, false, false);
    1115             if (unlink(imageResolved) == -1 || unlink(maskResolved) == -1 ||
    1116                 unlink(varianceResolved) == -1) {
    1117                 psWarning("Unable to delete temporary files for image %d", i);
    1118             }
    1119             psFree(imageResolved);
    1120             psFree(maskResolved);
    1121             psFree(varianceResolved);
    1122         }
    1123     }
    1124     psFree(imageNames);
    1125     psFree(maskNames);
    1126     psFree(varianceNames);
    1127 
    1128     psFree(inputMask);
    1129114    psFree(stack);
    1130115
    1131     memDump("cleanup");
    1132116
    1133     // Generate binned JPEGs
    1134     {
    1135         int bin1 = psMetadataLookupS32(NULL, recipe, "BIN1"); // First binning level
    1136         int bin2 = psMetadataLookupS32(NULL, recipe, "BIN2"); // Second binning level
    1137 
    1138         // Target cells
    1139         pmCell *cell1 = pmFPAfileThisCell(config->files, view, "PPSTACK.OUTPUT.JPEG1");
    1140         pmCell *cell2 = pmFPAfileThisCell(config->files, view, "PPSTACK.OUTPUT.JPEG2");
    1141         psImageMaskType maskValue = pmConfigMaskGet("BLANK", config); // Bits to mask
    1142 
    1143         pmReadout *ro1 = pmReadoutAlloc(cell1), *ro2 = pmReadoutAlloc(cell2); // Binned readouts
    1144         if (!pmReadoutRebin(ro1, outRO, maskValue, bin1, bin1) || !pmReadoutRebin(ro2, ro1, 0, bin2, bin2)) {
    1145             psError(PS_ERR_UNKNOWN, false, "Unable to bin output.");
    1146             psFree(ro1);
    1147             psFree(ro2);
    1148             psFree(outRO);
    1149             return false;
    1150         }
    1151         psFree(ro1);
    1152         psFree(ro2);
    1153     }
    1154 
    1155     psLogMsg("ppStack", PS_LOG_INFO, "Stage 7 : WCS & JPEGS : %f sec", psTimerClear("PPSTACK_STEPS"));
    1156 
    1157     if (psMetadataLookupBool(&mdok, recipe, "PHOTOMETRY")) {
    1158         psTrace("ppStack", 1, "Photometering stacked image....\n");
    1159 
    1160         psTimerStart("PPSTACK_PHOT");
    1161 
    1162         fileActivation(config, combineFiles, false);
    1163         fileActivation(config, photFiles, true);
    1164         pmFPAview *photView = filesIterateDown(config);
    1165         if (!ppStackPhotometry(config, outRO, photView)) {
    1166             psError(PS_ERR_UNKNOWN, false, "Unable to perform photometry on output.");
    1167             psFree(outRO);
    1168             psFree(photView);
    1169             return false;
    1170         }
    1171         psFree(photView);
    1172 
    1173         fileActivation(config, combineFiles, true);
    1174 
    1175         if (stats) {
    1176             pmFPAfile *photFile = psMetadataLookupPtr(NULL, config->files, "PSPHOT.INPUT"); // File
    1177             pmReadout *photRO = pmFPAviewThisReadout(view, photFile->fpa); // Readout with the sources
    1178             psArray *sources = psMetadataLookupPtr(NULL, photRO->analysis, "PSPHOT.SOURCES"); // Sources
    1179             psMetadataAddS32(stats, PS_LIST_TAIL, "NUM_SOURCES", 0, "Number of sources detected", sources->n);
    1180             psMetadataAddF32(stats, PS_LIST_TAIL, "TIME_PHOT", 0,
    1181                              "Time to do photometry", psTimerMark("PPSTACK_PHOT"));
    1182         }
    1183         psLogMsg("ppStack", PS_LOG_INFO, "Time to do photometry: %f sec", psTimerClear("PPSTACK_PHOT"));
    1184     }
    1185 
    1186     psLogMsg("ppStack", PS_LOG_INFO, "Stage 8 : Photometry Analysis : %f sec", psTimerClear("PPSTACK_STEPS"));
    1187 
    1188     psThreadPoolFinalize();
    1189 
    1190     memDump("phot");
    1191 
    1192     // Statistics on output
    1193     if (stats) {
    1194         psTrace("ppStack", 1, "Gathering statistics on stacked image....\n");
    1195         psString maskBadStr = psMetadataLookupStr(NULL, recipe, "MASK.BAD"); // Name of bits for bad
    1196         psImageMaskType maskBad = pmConfigMaskGet(maskBadStr, config); // Bits to mask for bad pixels
    1197 
    1198         ppStatsFPA(stats, outRO->parent->parent->parent, view, maskBad, config);
    1199     }
    1200 
    1201     memDump("stats");
    1202 
    1203     // Put version information into the header
    1204     pmHDU *hdu = pmHDUFromCell(outRO->parent);
    1205     if (!hdu) {
    1206         psError(PS_ERR_UNKNOWN, false, "Unable to find HDU for output.");
    1207         psFree(outRO);
    1208         psFree(view);
     117    // Photometry
     118    psTrace("ppStack", 1, "Photometering stacked image....\n");
     119    if (!ppStackPhotometry(options, config)) {
     120        psError(PS_ERR_UNKNOWN, false, "Unable to perform photometry.");
     121        psFree(options);
    1209122        return false;
    1210123    }
    1211     if (!hdu->header) {
    1212         hdu->header = psMetadataAlloc();
    1213     }
    1214     ppStackVersionMetadata(hdu->header);
     124    psLogMsg("ppStack", PS_LOG_INFO, "Stage 8: Photometry Analysis: %f sec", psTimerClear("PPSTACK_STEPS"));
     125    ppStackMemDump("photometry");
    1215126
    1216     psFree(outRO);
    1217     psFree(view);
    1218127
    1219     // Write out summary statistics
    1220     if (stats) {
    1221         psMetadataAddF32(stats, PS_LIST_TAIL, "TIME_STACK", 0,
    1222                          "Time to do photometry", psTimerClear("PPSTACK_TOTAL"));
    1223 
    1224         const char *statsMDC = psMetadataConfigFormat(stats);
    1225         if (!statsMDC || strlen(statsMDC) == 0) {
    1226             psError(PS_ERR_IO, false, "Unable to get statistics MDC file.\n");
    1227         } else {
    1228             fprintf(statsFile, "%s", statsMDC);
    1229         }
    1230         psFree((void *)statsMDC);
    1231         fclose(statsFile);
    1232 
    1233         psFree(stats);
    1234     }
    1235 
    1236     // Write out the output files
    1237     if (!filesIterateUp(config)) {
     128    // Finish up
     129    psTrace("ppStack", 1, "Finishing up....\n");
     130    if (!ppStackFinish(options, config)) {
     131        psError(PS_ERR_UNKNOWN, false, "Unable to finish up.");
     132        psFree(options);
    1238133        return false;
    1239134    }
     135    psLogMsg("ppStack", PS_LOG_INFO, "Stage 9: Final output: %f sec", psTimerClear("PPSTACK_STEPS"));
     136    ppStackMemDump("finish");
    1240137
    1241     psLogMsg("ppStack", PS_LOG_INFO, "Stage 9 : Final Output : %f sec", psTimerClear("PPSTACK_STEPS"));
    1242 
    1243     memDump("finish");
    1244 
     138    psFree(options);
    1245139    return true;
    1246140}
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackMatch.c

    r21525 r23352  
    145145
    146146    psImage *binned = psphotBackgroundModel(ro, config); // Binned background model
    147     psImageBinning *binning = psMetadataLookupPtr(NULL, psphotRecipe,
     147    psImageBinning *binning = psMetadataLookupPtr(NULL, ro->analysis,
    148148                                                  "PSPHOT.BACKGROUND.BINNING"); // Binning for model
    149149    psAssert(binning, "Need binning parameters");
     
    358358                psString name = NULL;
    359359                psStringAppend(&name, "fake_%03d.fits", numInput);
     360                pmStackVisualPlotTestImage(fake->image, name);
    360361                psFits *fits = psFitsOpen(name, "w");
    361362                psFree(name);
     
    367368                psString name = NULL;
    368369                psStringAppend(&name, "real_%03d.fits", numInput);
     370                pmStackVisualPlotTestImage(readout->image, name);
    369371                psFits *fits = psFitsOpen(name, "w");
    370372                psFree(name);
     
    397399                psString name = NULL;
    398400                psStringAppend(&name, "conv_%03d.fits", numInput);
     401                pmStackVisualPlotTestImage(output->image, name);
    399402                psFits *fits = psFitsOpen(name, "w");
    400403                psFree(name);
     
    406409                psString name = NULL;
    407410                psStringAppend(&name, "diff_%03d.fits", numInput);
     411                pmStackVisualPlotTestImage(fake->image, name);
    408412                psFits *fits = psFitsOpen(name, "w");
    409413                psFree(name);
     
    633637        psString name = NULL;
    634638        psStringAppend(&name, "convolved_%03d.fits", numInput);
     639        pmStackVisualPlotTestImage(output->image, name);
    635640        psFits *fits = psFitsOpen(name, "w");
    636641        psFree(name);
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackPSF.c

    r18918 r23352  
    99#include "ppStack.h"
    1010
    11 pmPSF *ppStackPSF(const pmConfig *config, int numCols, int numRows, const psArray *psfs)
     11pmPSF *ppStackPSF(const pmConfig *config, int numCols, int numRows,
     12                  const psArray *psfs, const psVector *inputMask)
    1213{
    1314    // Get the recipe values
     
    1920    const char *psfModel = psMetadataLookupStr(NULL, recipe, "PSF.MODEL"); // Model for PSF
    2021    int psfOrder = psMetadataLookupS32(NULL, recipe, "PSF.ORDER"); // Spatial order for PSF
     22
     23    for (int i = 0; i < psfs->n; i++) {
     24        if (inputMask->data.U8[i]) {
     25            psFree(psfs->data[i]);
     26            psfs->data[i] = NULL;
     27        }
     28    }
    2129
    2230    // Solve for the target PSF
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackPhotometry.c

    r21259 r23352  
    99
    1010#include "ppStack.h"
     11#include "ppStackLoop.h"
    1112
    12 #define PHOT_SOURCE_MASK (PM_SOURCE_MODE_FAIL | PM_SOURCE_MODE_SATSTAR | PM_SOURCE_MODE_BLEND | \
    13                           PM_SOURCE_MODE_BADPSF | PM_SOURCE_MODE_DEFECT | PM_SOURCE_MODE_SATURATED | \
    14                           PM_SOURCE_MODE_CR_LIMIT | PM_SOURCE_MODE_EXT_LIMIT) // Mask to apply to sources
    15 
    16 bool ppStackInputPhotometry(const pmReadout *ro, const psArray *sources, const pmConfig *config)
     13bool ppStackPhotometry(ppStackOptions *options, pmConfig *config)
    1714{
    18     PM_ASSERT_READOUT_NON_NULL(ro, false);
    19     PS_ASSERT_ARRAY_NON_NULL(sources, false);
     15    psAssert(options, "Require options");
     16    psAssert(config, "Require configuration");
    2017
    2118    psMetadata *recipe = psMetadataLookupMetadata(NULL, config->recipes, PPSTACK_RECIPE); // ppStack recipe
     
    2320
    2421    bool mdok;                          // Status of MD lookup
    25 
    26     float zpRadius = psMetadataLookupS32(&mdok, recipe, "PHOT.RADIUS"); // Radius for PHOT measurement
    27     if (!mdok) {
    28         psError(PS_ERR_UNKNOWN, true, "Unable to find PHOT.RADIUS in recipe");
    29         return false;
    30     }
    31     float zpSigma = psMetadataLookupF32(&mdok, recipe, "PHOT.SIGMA"); // Gaussian sigma for photometry
    32     if (!mdok) {
    33         psError(PS_ERR_UNKNOWN, true, "Unable to find PHOT.SIGMA in recipe");
    34         return false;
    35     }
    36     float zpFrac = psMetadataLookupF32(&mdok, recipe, "PHOT.FRAC"); // Fraction of good pixels for photometry
    37     if (!mdok) {
    38         psError(PS_ERR_UNKNOWN, true, "Unable to find PHOT.FRAC in recipe");
    39         return false;
     22    if (!psMetadataLookupBool(&mdok, recipe, "PHOTOMETRY")) {
     23        // Nothing to do
     24        return true;
    4025    }
    4126
    42     psString maskValStr = psMetadataLookupStr(&mdok, recipe, "MASK.VAL"); // Name of bits to mask going in
    43     if (!mdok || !maskValStr) {
    44         psError(PS_ERR_UNKNOWN, false, "Unable to find MASK.VAL in recipe");
    45         return false;
    46     }
    47     psImageMaskType maskVal = pmConfigMaskGet(maskValStr, config); // Bits to mask
     27    psTimerStart("PPSTACK_PHOT");
    4828
    49     psImage *image = ro->image, *mask = ro->mask; // Image and mask from readout
     29    ppStackFileActivation(config, PPSTACK_FILES_COMBINE, false);
     30    ppStackFileActivation(config, PPSTACK_FILES_PHOT, true);
     31    pmFPAview *photView = ppStackFilesIterateDown(config); // View to readout
     32    ppStackFileActivation(config, PPSTACK_FILES_COMBINE, true);
    5033
    51     // Measure background
    52     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 0); // Random number generator
    53     psStats *stats = psStatsAlloc(PS_STAT_ROBUST_MEDIAN | PS_STAT_ROBUST_STDEV); // Statistics
    54     if (!psImageBackground(stats, NULL, image, mask, maskVal, rng)) {
    55         psError(PS_ERR_UNKNOWN, false, "Unable to measure background for image");
    56         psFree(stats);
    57         psFree(rng);
    58         return false;
    59     }
    60     float bg = stats->robustMedian; // Background level
    61     psFree(stats);
    62     psFree(rng);
     34    pmFPAfile *photFile = psMetadataLookupPtr(NULL, config->files, "PSPHOT.INPUT"); // File for photometry
     35    pmFPACopy(photFile->fpa, options->outRO->parent->parent->parent);
    6336
    64     // Photometer sources
    65     int numCols = image->numCols, numRows = image->numRows; // Size of image
    66     int numSources = sources->n; // Number of sources
    67     int numGood = 0;            // Number of good sources
    68     float maxMag = -INFINITY;   // Maximum magnitude
    69     for (int j = 0; j < numSources; j++) {
    70         pmSource *source = sources->data[j]; // Source of interest
    71         if (source->mode & PHOT_SOURCE_MASK || !isfinite(source->psfMag)) {
    72             source->psfMag = NAN;
    73             continue;
    74         }
    75         float x = source->peak->xf, y = source->peak->yf; // Coordinates of source
    76         int xCentral = x + 0.5, yCentral = y + 0.5; // Central pixel
    77         // Range of integration
    78         int xMin = PS_MAX(0, xCentral - zpRadius), xMax = PS_MIN(numCols - 1, xCentral + zpRadius);
    79         int yMin = PS_MAX(0, yCentral - zpRadius), yMax = PS_MIN(numRows - 1, yCentral + zpRadius);
    80 
    81         // Integrate
    82         double sumImage = 0.0, sumKernel = 0.0; // Sums from integration
    83         int numBadPix = 0;         // Number of bad pixels
    84         for (int v = yMin; v <= yMax; v++) {
    85             float dy2 = PS_SQR(y - v); // Distance from centroid
    86             for (int u = xMin; u <= xMax; u++) {
    87                 if (mask->data.PS_TYPE_IMAGE_MASK_DATA[v][u] & maskVal) {
    88                     numBadPix++;
    89                     continue;
    90                 }
    91                 float dx2 = PS_SQR(x - u); // Distance from centroid
    92                 double kernel = exp(-0.5 * (dx2 + dy2) / PS_SQR(zpSigma)); // Kernel value
    93                 sumImage += (image->data.F32[v][u] - bg) * kernel;
    94                 sumKernel += kernel;
    95             }
    96         }
    97 
    98         if (numBadPix > zpFrac * M_PI * PS_SQR(zpRadius) || !isfinite(sumImage)) {
    99             source->psfMag = NAN;
    100         } else {
    101             source->psfMag = - 2.5 * log10(sumImage / sumKernel * M_PI * PS_SQR(zpRadius));
    102             if (isfinite(source->psfMag)) {
    103                 numGood++;
    104                 maxMag = PS_MAX(maxMag, source->psfMag);
    105             }
    106         }
    107     }
    108     psLogMsg("ppStack", PS_LOG_INFO, "Photometered %d good sources in image; max mag %f", numGood, maxMag);
    109 
    110     return true;
    111 }
    112 
    113 
    114 
    115 bool ppStackPhotometry(pmConfig *config, const pmReadout *readout, const pmFPAview *view)
    116 {
    117     pmFPAfile *photFile = psMetadataLookupPtr(NULL, config->files, "PSPHOT.INPUT");
    118     pmFPACopy(photFile->fpa, readout->parent->parent->parent);
    119 
    120     if (psMetadataLookupBool(NULL, config->arguments, "-psphot-visual")) {
    121         psphotSetVisual(true);
     37    if (psMetadataLookupBool(NULL, config->arguments, "-visual")) {
     38        pmVisualSetVisual(true);
    12239    }
    12340
     41    psMetadata *psphot = psMetadataLookupMetadata(NULL, config->recipes, PSPHOT_RECIPE); // Recipe
     42
     43#if 0
    12444    // Need to ensure aperture residual is not calculated
    125     psMetadata *recipe = psMetadataLookupMetadata(NULL, config->recipes, PSPHOT_RECIPE); // Recipe
    12645    psMetadataItem *item = psMetadataLookup(recipe, "MEASURE.APTREND"); // Item determining aptrend
    12746    if (!item) {
     
    13150        item->data.B = false;
    13251    }
     52#endif
    13353
    13454    // set maskValue and markValue in the psphot recipe
    13555    psImageMaskType maskValue = pmConfigMaskGet("BLANK", config); // Bits to mask
    13656    psImageMaskType markValue = pmConfigMaskGet("MARK.VALUE", config); // Bits to use for marking
    137     psMetadataAddImageMask (recipe, PS_LIST_TAIL, "MASK.PSPHOT", PS_META_REPLACE, "Bits to mask", maskValue);
    138     psMetadataAddImageMask (recipe, PS_LIST_TAIL, "MARK.PSPHOT", PS_META_REPLACE, "Bits to use for mark", markValue);
     57    psMetadataAddImageMask(psphot, PS_LIST_TAIL, "MASK.PSPHOT", PS_META_REPLACE,
     58                            "Bits to mask", maskValue);
     59    psMetadataAddImageMask(psphot, PS_LIST_TAIL, "MARK.PSPHOT", PS_META_REPLACE,
     60                           "Bits to use for mark", markValue);
    13961
    140     // XXX replace with psphotReadoutKnownSources (config, view)
    141     // XXX this function requires that we construct the input source list and place it on PSPHOT.INPUT.CMF
    142     pmCell *sourcesCell = pmFPAfileThisCell(config->files, view, "PPSTACK.OUTPUT");
    143     psArray *inSources = psMetadataLookupPtr (NULL, sourcesCell->analysis, "PSPHOT.SOURCES");
     62    pmCell *sourcesCell = pmFPAfileThisCell(config->files, photView, "PPSTACK.OUTPUT");
     63    psArray *inSources = psMetadataLookupPtr(NULL, sourcesCell->analysis, "PSPHOT.SOURCES");
    14464    if (!inSources) {
    14565        psError(PS_ERR_UNKNOWN, false, "Unable to find input sources");
     66        psFree(photView);
    14667        return false;
    14768    }
    14869
    149     if (!psphotReadoutKnownSources(config, view, inSources)) {
     70    if (!psphotReadoutKnownSources(config, photView, inSources)) {
    15071        // Clear the error, so that the output files are written.
    151         psWarning("Unable to perform photometry on stacked image.");
    152         psErrorStackPrint(stderr, "Error stack from photometry:");
    153         psErrorClear();
     72        psError(PS_ERR_UNKNOWN, false, "Unable to perform photometry on stacked image.");
     73        psFree(photView);
     74        return false;
    15475    }
     76    psFree(photView);
    15577
    15678    if (!pmFPAfileDropInternal(config->files, "PSPHOT.BACKMDL") ||
     
    16385    pmFPAfileActivate(config->files, false, "PSPHOT.INPUT");
    16486
     87    if (options->stats) {
     88        pmReadout *photRO = pmFPAviewThisReadout(photView, photFile->fpa); // Readout with the sources
     89        psArray *sources = psMetadataLookupPtr(NULL, photRO->analysis, "PSPHOT.SOURCES"); // Sources
     90        psMetadataAddS32(options->stats, PS_LIST_TAIL, "NUM_SOURCES", 0,
     91                         "Number of sources detected", sources->n);
     92        psMetadataAddF32(options->stats, PS_LIST_TAIL, "TIME_PHOT", 0,
     93                         "Time to do photometry", psTimerMark("PPSTACK_PHOT"));
     94    }
     95    psLogMsg("ppStack", PS_LOG_INFO, "Time to do photometry: %f sec", psTimerClear("PPSTACK_PHOT"));
     96
    16597    return true;
    16698}
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackReadout.c

    r21477 r23352  
    88#include <psphot.h>
    99
     10#include "ppStackThread.h"
    1011#include "ppStack.h"
    1112
     
    1617    psArray *args = job->args;          // Arguments
    1718    ppStackThread *thread = args->data[0]; // Thread
    18     pmConfig *config = args->data[1];   // Configuration
    19     pmReadout *outRO = args->data[2];   // Output readout
    20     psVector *mask = args->data[3];     // Mask for inputs
    21     psVector *weightings = args->data[4]; // Weightings (1/noise^2) for each image
    22     psVector *addVariance = args->data[5]; // Additional variance when rejecting
     19    ppStackOptions *options = args->data[1]; // Options
     20    pmConfig *config = args->data[2];   // Configuration
     21
     22    pmReadout *outRO = options->outRO;  // Output readout
     23    psVector *mask = options->inputMask; // Mask for inputs
     24    psVector *weightings = options->weightings; // Weightings (1/noise^2) for each image
     25    psVector *addVariance = options->matchChi2; // Additional variance when rejecting
    2326
    2427    psArray *inspect = ppStackReadoutInitial(config, outRO, thread->readouts, mask,
     
    3740    psArray *args = job->args;          // Arguments
    3841    ppStackThread *thread = args->data[0]; // Thread
    39     pmConfig *config = args->data[1];   // Configuration
    40     pmReadout *outRO = args->data[2];   // Output readout
    41     psVector *mask = args->data[3];     // Mask for inputs
    42     psArray *rejected = args->data[4];  // Rejected pixels
    43     psVector *weightings = args->data[5];  // Weighting (1/noise^2) for each image
    44     psVector *addVariance = args->data[6];  // Weighting (1/noise^2) for each image
     42    ppStackOptions *options = args->data[1]; // Options
     43    pmConfig *config = args->data[2];   // Configuration
     44
     45    pmReadout *outRO = options->outRO;  // Output readout
     46    psVector *mask = options->inputMask; // Mask for inputs
     47    psArray *rejected = options->rejected; // Rejected pixels
     48    psVector *weightings = options->weightings; // Weightings (1/noise^2) for each image
     49    psVector *addVariance = options->matchChi2; // Additional variance when rejecting
    4550
    4651    bool status = ppStackReadoutFinal(config, outRO, thread->readouts, mask, rejected,
     
    227232        }
    228233
    229         pmStackData *data = pmStackDataAlloc(ro, weightings->data.F32[i], addVariance->data.F32[i]);
     234        pmStackData *data = pmStackDataAlloc(ro, weightings->data.F32[i],
     235                                             addVariance ? addVariance->data.F32[i] : NAN);
    230236        data->reject = psMemIncrRefCounter(rejected->data[i]);
    231237        stack->data[i] = data;
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackSources.c

    r21260 r23352  
    1313#define FAKE_ROWS 4913
    1414
    15 float ppStackSourcesTransparency(const psArray *sourceLists, const pmFPAview *view, const pmConfig *config)
     15#ifdef TESTING
     16// Dump matches to a file
     17static void dumpMatches(const char *filename, // File to which to dump
     18                        int num,        // Number of inputs
     19                        psArray *matches, // Star matches
     20                        psVector *zp,   // Zero points
     21                        psVector *trans // Transparencies
     22                        )
     23{
     24    FILE *outMatches = fopen(filename, "w"); // Output matches
     25    psVector *mag = psVectorAlloc(num, PS_TYPE_F32); // Magnitudes for each star
     26    psVector *magErr = psVectorAlloc(num, PS_TYPE_F32); // Errors for each star
     27    for (int i = 0; i < matches->n; i++) {
     28        pmSourceMatch *match = matches->data[i]; // Match of interest
     29        psVectorInit(mag, NAN);
     30        psVectorInit(magErr, NAN);
     31        for (int j = 0; j < match->num; j++) {
     32            if (match->mask->data.PS_TYPE_VECTOR_MASK_DATA[j]) {
     33                continue;
     34            }
     35            int index = match->image->data.U32[j]; // Image index
     36            mag->data.F32[index] = match->mag->data.F32[j] - zp->data.F32[index];
     37            if (trans) {
     38                mag->data.F32[index] -= trans->data.F32[index];
     39            }
     40            magErr->data.F32[index] = match->magErr->data.F32[j];
     41        }
     42        for (int j = 0; j < num; j++) {
     43            fprintf(outMatches, "%f (%f) ", mag->data.F32[j], magErr->data.F32[j]);
     44        }
     45        fprintf(outMatches, "\n");
     46    }
     47    psFree(mag);
     48    psFree(magErr);
     49    fclose(outMatches);
     50    return;
     51}
     52#endif
     53
     54
     55float ppStackSourcesTransparency(const psArray *sourceLists, psVector *inputMask,
     56                                 const pmFPAview *view, const pmConfig *config)
    1657{
    1758    PS_ASSERT_ARRAY_NON_NULL(sourceLists, NAN);
     59    PS_ASSERT_VECTOR_NON_NULL(inputMask, NAN);
     60    PS_ASSERT_VECTOR_TYPE(inputMask, PS_TYPE_U8, NAN);
     61    PS_ASSERT_VECTOR_SIZE(inputMask, sourceLists->n, NAN);
    1862    PS_ASSERT_PTR_NON_NULL(view, NAN);
    1963    PS_ASSERT_PTR_NON_NULL(config, NAN);
    2064
    21 #ifdef TESTING
     65#if defined(TESTING) && 0
    2266    {
    2367        // Deliberately induce a major transparency difference
     
    3781
    3882    float radius = psMetadataLookupF32(NULL, recipe, "ZP.RADIUS"); // Radius (pixels) for matching sources
    39     int iter = psMetadataLookupS32(NULL, recipe, "ZP.ITER"); // Maximum iterations
     83    int iter1 = psMetadataLookupS32(NULL, recipe, "ZP.ITER.1"); // Maximum iterations for pass 1
     84    int iter2 = psMetadataLookupS32(NULL, recipe, "ZP.ITER.2"); // Maximum iterations for pass 2
    4085    float tol = psMetadataLookupF32(NULL, recipe, "ZP.TOL"); // Tolerance for zero point iterations
    4186    int transIter = psMetadataLookupS32(NULL, recipe, "ZP.TRANS.ITER"); // Iterations for transparency
    4287    float transRej = psMetadataLookupF32(NULL, recipe, "ZP.TRANS.REJ");// Rejection threshold for transparency
    4388    float transThresh = psMetadataLookupF32(NULL, recipe, "ZP.TRANS.THRESH"); // Threshold for transparency
    44     float starRej = psMetadataLookupF32(NULL, recipe, "ZP.STAR.REJ"); // Rejection threshold for stars
     89
     90    float starRej1 = psMetadataLookupF32(NULL, recipe, "ZP.STAR.REJ.1"); // Rejection threshold for stars
     91    float starSys1 = psMetadataLookupF32(NULL, recipe, "ZP.STAR.SYS.1"); // Estimated systematic error
     92    float starRej2 = psMetadataLookupF32(NULL, recipe, "ZP.STAR.REJ.2"); // Rejection threshold for stars
     93    float starSys2 = psMetadataLookupF32(NULL, recipe, "ZP.STAR.SYS.2"); // Estimated systematic error
     94
    4595    float starLimit = psMetadataLookupF32(NULL, recipe, "ZP.STAR.LIMIT"); // Limit on star rejection fraction
    46     float starSys = psMetadataLookupF32(NULL, recipe, "ZP.STAR.SYS"); // Estimated systematic error
     96
     97    float fracMatch = psMetadataLookupF32(NULL, recipe, "ZP.MATCH"); // Fraction of images to match for star
    4798
    4899    psMetadata *airmassZP = psMetadataLookupMetadata(NULL, recipe, "ZP.AIRMASS"); // Airmass terms
     
    63114        pmCell *cell = pmFPAviewThisCell(view, file->fpa); // Cell of interest
    64115
    65 #ifdef TESTING
     116#if defined(TESTING) && 0
    66117        pmReadout *fake = pmReadoutAlloc(NULL); // Fake readout
    67118        pmPSF *psf = psMetadataLookupPtr(NULL, config->arguments, "PSF.TARGET"); // PSF for fake image
    68         pmReadoutFakeFromSources(fake, FAKE_COLS, FAKE_ROWS, sourceLists->data[i], NULL, NULL, psf, 5, 0, false, true);
     119        pmReadoutFakeFromSources(fake, FAKE_COLS, FAKE_ROWS, sourceLists->data[i],
     120                                 NULL, NULL, psf, 5, 0, false, true);
    69121        psString name = NULL;
    70122        psStringAppend(&name, "start_%03d.fits", i);
     123        pmStackVisualPlotTestImage(fake->image, name);
    71124        psFits *fits = psFitsOpen(name, "w");
    72125        psFree(name);
     
    108161    }
    109162
    110     psArray *matches = pmSourceMatchSources(sourceLists, radius); // List of matches
     163    psArray *matches = pmSourceMatchSources(sourceLists, radius, true); // List of matches
    111164    if (!matches) {
    112165        psError(PS_ERR_UNKNOWN, false, "Unable to match sources");
     
    114167        return NAN;
    115168    }
    116     psVector *trans = pmSourceMatchRelphot(matches, zp, iter, tol, starLimit, transIter, transRej,
    117                                            transThresh, starRej, starSys); // Transparencies for each image
    118 
    119 #ifdef TESTING
    120     {
    121         // Dump the corrected magnitudes
    122         FILE *outMatches = fopen("source_match.dat", "w"); // Output matches
    123         psVector *mag = psVectorAlloc(num, PS_TYPE_F32); // Magnitudes for each star
    124         psVector *magErr = psVectorAlloc(num, PS_TYPE_F32); // Errors for each star
    125         for (int i = 0; i < matches->n; i++) {
    126             pmSourceMatch *match = matches->data[i]; // Match of interest
    127             psVectorInit(mag, NAN);
    128             psVectorInit(magErr, NAN);
    129             for (int j = 0; j < match->num; j++) {
    130                 if (match->mask->data.PS_TYPE_VECTOR_MASK_DATA[j]) {
    131                     continue;
    132                 }
    133                 int index = match->image->data.U32[j]; // Image index
    134                 mag->data.F32[index] = match->mag->data.F32[j] - zp->data.F32[index] - trans->data.F32[index];
    135                 magErr->data.F32[index] = match->magErr->data.F32[j];
    136             }
    137             for (int j = 0; j < num; j++) {
    138                 fprintf(outMatches, "%f (%f) ", mag->data.F32[j], magErr->data.F32[j]);
    139             }
    140             fprintf(outMatches, "\n");
    141         }
    142         psFree(mag);
    143         psFree(magErr);
    144         fclose(outMatches);
    145     }
    146 #endif
     169
     170#ifdef TESTING
     171    dumpMatches("source_match.dat", num, matches, zp, NULL);
     172#endif
     173
     174    psVector *trans = pmSourceMatchRelphot(matches, zp, tol, iter1, starRej1, starSys1,
     175                                           iter2, starRej2, starSys2, starLimit,
     176                                           transIter, transRej, transThresh); // Transparencies for each image
     177    if (!trans) {
     178        psError(PS_ERR_UNKNOWN, false, "Unable to measure transparencies");
     179        return NAN;
     180    }
     181
     182#ifdef TESTING
     183    dumpMatches("source_mags.dat", num, matches, zp, trans);
     184#endif
     185
     186    for (int i = 0; i < trans->n; i++) {
     187        if (!isfinite(trans->data.F32[i])) {
     188            inputMask->data.U8[i] = PPSTACK_MASK_CAL;
     189        }
     190    }
    147191
    148192    // Save best matches SOMEWHERE for future photometry
    149193    // XXX this is a really poor output location; clean up the pmFPAfiles used in ppStack
    150194    pmCell *sourcesCell = pmFPAfileThisCell(config->files, view, "PPSTACK.OUTPUT");
    151     psArray *sourcesBest = psArrayAllocEmpty (100);
    152 
    153     // XXX something of a hack: require at 2 detections or 1/2 of the max possible
    154     int minMatches = PS_MAX (2, 0.5*num);
     195    psArray *sourcesBest = psArrayAllocEmpty(matches->n);
     196
     197    // XXX something of a hack: require at least 2 detections or the nominated fraction of the max possible
     198    int minMatches = PS_MAX(2, fracMatch * num);// Minimum number of matches required
    155199    for (int i = 0; i < matches->n; i++) {
    156         pmSourceMatch *match = matches->data[i]; // Match of interest
    157         if (match->num < minMatches) continue;
    158 
    159         // We need to grab a single instance of this source: just take the first available
    160         int nImage = match->image->data.S32[0];
    161         int nIndex = match->index->data.S32[0];
    162         psArray *sources = sourceLists->data[nImage];
    163         pmSource *source = sources->data[nIndex];
    164        
    165         // stick this sample source on sourcesBest
    166         psArrayAdd (sourcesBest, 100, source);
    167     }
    168     psMetadataAdd (sourcesCell->analysis, PS_LIST_TAIL, "PSPHOT.SOURCES", PS_DATA_ARRAY | PS_META_REPLACE, "psphot sources", sourcesBest);
    169     psLogMsg("ppStack", PS_LOG_INFO, "Selected %ld sources for photometry analysis\n", sourcesBest->n);
    170     psFree (sourcesBest);
     200        pmSourceMatch *match = matches->data[i]; // Match of interest
     201        if (match->num < minMatches) {
     202            continue;
     203        }
     204
     205        // We need to grab a single instance of this source: just take the first available
     206        int image = match->image->data.S32[0]; // Index of image
     207        int index = match->index->data.S32[0]; // Index of source within image
     208        psArray *sources = sourceLists->data[image]; // Sources for image
     209        pmSource *source = sources->data[index]; // Source of interest
     210
     211        psArrayAdd(sourcesBest, sourcesBest->n, source);
     212    }
     213    psMetadataAdd(sourcesCell->analysis, PS_LIST_TAIL, "PSPHOT.SOURCES", PS_DATA_ARRAY | PS_META_REPLACE,
     214                  "psphot sources", sourcesBest);
     215    psLogMsg("ppStack", PS_LOG_INFO, "Selected %ld sources for photometry analysis", sourcesBest->n);
     216    psFree(sourcesBest);
    171217
    172218    psFree(matches);
    173     if (!trans) {
    174         psError(PS_ERR_UNKNOWN, false, "Unable to measure transparencies");
    175         return NAN;
    176     }
    177219
    178220    // M = m + c0 + c1 * airmass - 2.5log(t) + transparency
     
    182224    // We don't need to know the magnitude zero point for the filter, since it cancels out
    183225    for (int i = 0; i < num; i++) {
     226        if (!isfinite(trans->data.F32[i])) {
     227            continue;
     228        }
    184229        psArray *sources = sourceLists->data[i]; // Sources of interest
    185230        float magCorr = airmassTerm - 2.5*log10(sumExpTime) - zp->data.F32[i] - trans->data.F32[i];
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackThread.c

    r21477 r23352  
    99
    1010#include "ppStack.h"
     11#include "ppStackOptions.h"
     12#include "ppStackThread.h"
     13
    1114
    1215#define THREAD_WAIT 10000               // Microseconds to wait if thread is not available
     
    3639    psFree(stack->threads);
    3740    for (int i = 0; i < stack->imageFits->n; i++) {
    38         psFitsClose(stack->imageFits->data[i]);
    39         psFitsClose(stack->maskFits->data[i]);
    40         psFitsClose(stack->varianceFits->data[i]);
     41        if (stack->imageFits->data[i]) {
     42            psFitsClose(stack->imageFits->data[i]);
     43        }
     44        if (stack->maskFits->data[i]) {
     45            psFitsClose(stack->maskFits->data[i]);
     46        }
     47        if (stack->varianceFits->data[i]) {
     48            psFitsClose(stack->varianceFits->data[i]);
     49        }
    4150        stack->imageFits->data[i] = stack->maskFits->data[i] = stack->varianceFits->data[i] = NULL;
    4251    }
     
    4756}
    4857
    49 ppStackThreadData *ppStackThreadDataSetup(const psArray *cells, const psArray *imageNames,
    50                                           const psArray *maskNames, const psArray *varianceNames,
    51                                           const psArray *covariances, const pmConfig *config)
    52 {
     58ppStackThreadData *ppStackThreadDataSetup(const ppStackOptions *options, const pmConfig *config)
     59{
     60    psAssert(options, "Require options");
     61    psAssert(config, "Require configuration");
     62
     63    const psArray *cells = options->cells; // Array of input cells
     64    const psArray *imageNames = options->imageNames; // Names of images to read
     65    const psArray *maskNames = options->maskNames; // Names of masks to read
     66    const psArray *varianceNames = options->varianceNames; // Names of variance maps to read
     67    const psArray *covariances = options->covariances; // Covariance matrices (already read)
     68
    5369    PS_ASSERT_ARRAY_NON_NULL(cells, NULL);
    5470    PS_ASSERT_ARRAYS_SIZE_EQUAL(cells, imageNames, NULL);
     
    239255
    240256    {
    241         psThreadTask *task = psThreadTaskAlloc("PPSTACK_INITIAL_COMBINE", 6);
     257        psThreadTask *task = psThreadTaskAlloc("PPSTACK_INITIAL_COMBINE", 3);
    242258        task->function = &ppStackReadoutInitialThread;
    243259        psThreadTaskAdd(task);
     
    253269
    254270    {
    255         psThreadTask *task = psThreadTaskAlloc("PPSTACK_FINAL_COMBINE", 7);
     271        psThreadTask *task = psThreadTaskAlloc("PPSTACK_FINAL_COMBINE", 3);
    256272        task->function = &ppStackReadoutFinalThread;
    257273        psThreadTaskAdd(task);
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackVersion.c

    r18419 r23352  
    77#include <psmodules.h>
    88#include <ppStats.h>
     9#include <psphot.h>
    910
    1011#include "ppStack.h"
    1112
    12 static const char *cvsTag = "$Name: not supported by cvs2svn $";// CVS tag name
     13#ifndef PPSTACK_VERSION
     14#error "PPSTACK_VERSION is not set"
     15#endif
     16#ifndef PPSTACK_BRANCH
     17#error "PPSTACK_BRANCH is not set"
     18#endif
     19#ifndef PPSTACK_SOURCE
     20#error "PPSTACK_SOURCE is not set"
     21#endif
     22
     23#define xstr(s) str(s)
     24#define str(s) #s
    1325
    1426psString ppStackVersion(void)
    1527{
    16     psString version = NULL;            // Version, to return
    17     psStringAppend(&version, "%s-%s",PACKAGE_NAME,PACKAGE_VERSION);
    18     return version;
     28    char *value = NULL;
     29    psStringAppend(&value, "%s@%s", xstr(PPSTACK_BRANCH), xstr(PPSTACK_VERSION));
     30    return value;
     31}
     32
     33psString ppStackSource(void)
     34{
     35    return psStringCopy(xstr(PPSTACK_SOURCE));
    1936}
    2037
    2138psString ppStackVersionLong(void)
    2239{
    23     psString version = ppStackVersion(); // Version, to return
    24     psString tag = psStringStripCVS(cvsTag, "Name"); // CVS tag
    25     psStringAppend(&version, " (cvs tag %s) %s, %s", tag, __DATE__, __TIME__);
    26     psFree(tag);
     40    psString version = ppStackVersion();  // Version, to return
     41    psString source = ppStackSource();    // Source
     42
     43    psStringPrepend(&version, "ppStack ");
     44    psStringAppend(&version, " from %s, built %s, %s", source, __DATE__, __TIME__);
     45    psFree(source);
     46
     47#ifdef __OPTIMIZE__
     48    psStringAppend(&version, " optimised");
     49#else
     50    psStringAppend(&version, " unoptimised");
     51#endif
     52
    2753    return version;
    28 }
     54};
    2955
    3056
    31 void ppStackVersionMetadata(psMetadata *metadata)
     57bool ppStackVersionHeader(psMetadata *header)
    3258{
    33     PS_ASSERT_METADATA_NON_NULL(metadata,);
    34 
    35     psString pslib = psLibVersionLong();// psLib version
    36     psString psmodules = psModulesVersionLong(); // psModules version
    37     psString ppStats = ppStatsVersionLong(); // ppStats version
    38     psString ppStack = ppStackVersionLong(); // ppStack version
     59    PS_ASSERT_METADATA_NON_NULL(header, false);
    3960
    4061    psTime *time = psTimeGetNow(PS_TIME_TAI); // The time now
    4162    psString timeString = psTimeToISO(time); // The time in an ISO string
    4263    psFree(time);
    43     psString head = NULL;               // Head string
    44     psStringAppend(&head, "ppStack processing at %s. Component information:", timeString);
     64    psString history = NULL;               // History string
     65    psStringAppend(&history, "ppStack at %s", timeString);
     66    psFree(timeString);
     67    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, history);
     68    psFree(history);
     69
     70    psLibVersionHeader(header);
     71    psModulesVersionHeader(header);
     72    psphotVersionHeader(header);
     73    ppStatsVersionHeader(header);
     74
     75    psString version = ppStackVersion(); // Software version
     76    psString source  = ppStackSource();  // Software source
     77
     78    psStringPrepend(&version, "ppStack version: ");
     79    psStringPrepend(&source, "ppStack source: ");
     80
     81    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, version);
     82    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, source);
     83
     84    psFree(version);
     85    psFree(source);
     86
     87    return true;
     88}
     89
     90void ppStackVersionPrint(void)
     91{
     92    psTime *time = psTimeGetNow(PS_TIME_TAI); // The time now
     93    psString timeString = psTimeToISO(time); // The time in an ISO string
     94    psFree(time);
     95    psLogMsg("ppStack", PS_LOG_INFO, "ppStack at %s", timeString);
    4596    psFree(timeString);
    4697
    47     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, "", head);
    48     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, "", pslib);
    49     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, "", psmodules);
    50     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, "", ppStats);
    51     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, "", ppStack);
     98    psString pslib = psLibVersionLong();// psLib version
     99    psString psmodules = psModulesVersionLong(); // psModules version
     100    psString psphot = psphotVersionLong(); // psphot version
     101    psString ppStats = ppStatsVersionLong(); // psastro version
     102    psString ppStack = ppStackVersionLong(); // ppStack version
    52103
    53     psFree(head);
     104    psLogMsg("ppStack", PS_LOG_INFO, "%s", pslib);
     105    psLogMsg("ppStack", PS_LOG_INFO, "%s", psmodules);
     106    psLogMsg("ppStack", PS_LOG_INFO, "%s", psphot);
     107    psLogMsg("ppStack", PS_LOG_INFO, "%s", ppStats);
     108    psLogMsg("ppStack", PS_LOG_INFO, "%s", ppStack);
     109
    54110    psFree(pslib);
    55111    psFree(psmodules);
     112    psFree(psphot);
    56113    psFree(ppStats);
    57114    psFree(ppStack);
  • branches/cnb_branches/cnb_branch_20090301/ppStats/src/Makefile.am

    r19626 r23352  
    11lib_LTLIBRARIES = libppStats.la
    2 libppStats_la_CFLAGS = $(PPSTATS_CFLAGS) $(PSMODULE_CFLAGS) $(PSLIB_CFLAGS)
     2
     3# PPSTATS_VERSION=`if [ -e ../../VERSION ]; then cat ../../VERSION; else svnversion; fi`
     4# PPSTATS_BRANCH=`if [ -e ../../BRANCH ]; then cat ../../BRANCH; else svn info | sed -n -e '/URL:/ h' -e '/Repository Root:/ { x; H; x; s|Repository Root: \(.*\)\nURL: \1\(.*\)|\2| ; s|^/|| ; s|/[a-zA-Z]*/src.*|| ; p }'; fi`
     5# PPSTATS_SOURCE=`if [ -e ../../SOURCE ]; then cat ../../SOURCE; else svn info | sed -n -e 's/Repository UUID: // p'; fi`
     6#
     7# # Force recompilation of ppStatsVersion.c, since it gets the version information
     8# ppStatsVersion.c: FORCE
     9#       touch ppStatsVersion.c
     10# FORCE: ;
     11
     12libppStats_la_CFLAGS = $(PPSTATS_CFLAGS) $(PSMODULE_CFLAGS) $(PSLIB_CFLAGS) -DPPSTATS_VERSION=$(SVN_VERSION) -DPPSTATS_BRANCH=$(SVN_BRANCH) -DPPSTATS_SOURCE=$(SVN_SOURCE)
    313libppStats_la_LDFLAGS = $(PPSTATS_LIBS) $(PSMODULE_LIBS) $(PSLIB_LIBS)
    414
  • branches/cnb_branches/cnb_branch_20090301/ppStats/src/ppStats.h

    r21183 r23352  
    2222    psList *summary;                    // Summary statistics to calculate
    2323    // Options for input data
    24     bool doFirstReadout3D;              // for 3D data, use the first readout?
     24    bool doFirstReadout3D;              // for 3D data, use the first readout?
    2525    float sample;                       // Fraction of cell to sample for statistics
    26     psImageMaskType maskVal;            // Mask value for images
     26    psImageMaskType maskVal;            // Mask value for images
    2727    psList *chips;                      // Chips to look at
    2828    psList *cells;                      // Cells to look at
     
    108108psString ppStatsVersion(void);
    109109
     110/// Return source information
     111psString ppStatsSource(void);
     112
    110113/// Return long version information
    111114psString ppStatsVersionLong(void);
     115
     116/// Populate header with version information
     117bool ppStatsVersionHeader(
     118    psMetadata *header                  ///< Header to populate
     119    );
     120
    112121
    113122void p_ppStatsGetMetadata(psMetadata *target, // Target for metadata
  • branches/cnb_branches/cnb_branch_20090301/ppStats/src/ppStatsFromMetadataPrint.c

    r20305 r23352  
    4141            VALUE_NUMERICAL_CASE(F64, "lf",   F64);
    4242          case PS_DATA_STRING:
    43             fprintf(f, "%s '%s' ", entry->flag, entry->value->data.str);
     43            if (entry->value->data.str) {
     44                fprintf(f, "%s '%s' ", entry->flag, entry->value->data.str);
     45            }
    4446            break;
    4547          case PS_DATA_BOOL:
     
    5052          case PS_DATA_TIME: {
    5153              psTime *t = (psTime*)entry->value->data.V;
    52               psString str = psTimeToISO(t);
    53               fprintf(f, "%s %.19sZ ", entry->flag, str);
    54               psFree(str);
     54              if (t) {
     55                  psString str = psTimeToISO(t);
     56                  fprintf(f, "%s %.19sZ ", entry->flag, str);
     57                  psFree(str);
     58              }
    5559              break;
    5660          }
  • branches/cnb_branches/cnb_branch_20090301/ppStats/src/ppStatsVersion.c

    r13993 r23352  
    11#include "ppStatsInternal.h"
    22
    3 static const char *cvsTag = "$Name: not supported by cvs2svn $";// CVS tag name
     3#ifndef PPSTATS_VERSION
     4#error "PPSTATS_VERSION is not set"
     5#endif
     6#ifndef PPSTATS_BRANCH
     7#error "PPSTATS_BRANCH is not set"
     8#endif
     9#ifndef PPSTATS_SOURCE
     10#error "PPSTATS_SOURCE is not set"
     11#endif
     12
     13#define xstr(s) str(s)
     14#define str(s) #s
    415
    516psString ppStatsVersion(void)
    617{
    7     psString version = NULL;            // Version, to return
    8     psStringAppend(&version, "%s-%s",PACKAGE_NAME,PACKAGE_VERSION);
    9     return version;
     18    char *value = NULL;
     19    psStringAppend(&value, "%s@%s", xstr(PPSTATS_BRANCH), xstr(PPSTATS_VERSION));
     20    return value;
     21}
     22
     23psString ppStatsSource(void)
     24{
     25    return psStringCopy(xstr(PPSTATS_SOURCE));
    1026}
    1127
    1228psString ppStatsVersionLong(void)
    1329{
    14     psString version = ppStatsVersion(); // Version, to return
    15     psString tag = psStringStripCVS(cvsTag, "Name"); // CVS tag
    16     psStringAppend(&version, " (cvs tag %s) %s, %s", tag, __DATE__, __TIME__);
    17     psFree(tag);
     30    psString version = ppStatsVersion();  // Version, to return
     31    psString source = ppStatsSource();    // Source
     32
     33    psStringPrepend(&version, "ppStats ");
     34    psStringAppend(&version, " from %s, built %s, %s", source, __DATE__, __TIME__);
     35    psFree(source);
     36
     37#ifdef __OPTIMIZE__
     38    psStringAppend(&version, " optimised");
     39#else
     40    psStringAppend(&version, " unoptimised");
     41#endif
     42
    1843    return version;
     44};
     45
     46bool ppStatsVersionHeader(psMetadata *header)
     47{
     48    PS_ASSERT_METADATA_NON_NULL(header, false);
     49
     50    psString version = ppStatsVersion(); // Software version
     51    psString source = ppStatsSource();   // Software source
     52
     53    psStringPrepend(&version, "ppStats version: ");
     54    psStringPrepend(&source, "ppStats source: ");
     55
     56    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, version);
     57    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, source);
     58
     59    psFree(version);
     60    psFree(source);
     61
     62    return true;
    1963}
  • branches/cnb_branches/cnb_branch_20090301/ppSub

  • branches/cnb_branches/cnb_branch_20090301/ppSub/src/Makefile.am

    r21257 r23352  
    11bin_PROGRAMS = ppSub ppSubKernel
    22
    3 ppSub_CPPFLAGS = $(PSLIB_CFLAGS) $(PSMODULE_CFLAGS) $(PPSTATS_CFLAGS) $(PSPHOT_CFLAGS) $(PPSUB_CFLAGS)
     3# PPSUB_VERSION=`if [ -e ../../VERSION ]; then cat ../../VERSION; else svnversion; fi`
     4# PPSUB_BRANCH=`if [ -e ../../BRANCH ]; then cat ../../BRANCH; else svn info | sed -n -e '/URL:/ h' -e '/Repository Root:/ { x; H; x; s|Repository Root: \(.*\)\nURL: \1\(.*\)|\2| ; s|^/|| ; s|/[a-zA-Z]*/src.*|| ; p }'; fi`
     5# PPSUB_SOURCE=`if [ -e ../../SOURCE ]; then cat ../../SOURCE; else svn info | sed -n -e 's/Repository UUID: // p'; fi`
     6#
     7# # Force recompilation of ppSubVersion.c, since it gets the version information
     8# ppSubVersion.c: FORCE
     9#       touch ppSubVersion.c
     10# FORCE: ;
     11
     12ppSub_CPPFLAGS = $(PSLIB_CFLAGS) $(PSMODULE_CFLAGS) $(PPSTATS_CFLAGS) $(PSPHOT_CFLAGS) $(PPSUB_CFLAGS) -DPPSUB_VERSION=$(SVN_VERSION) -DPPSUB_BRANCH=$(SVN_BRANCH) -DPPSUB_SOURCE=$(SVN_SOURCE)
    413ppSub_LDFLAGS  = $(PSLIB_LIBS)   $(PSMODULE_LIBS)   $(PPSTATS_LIBS)   $(PSPHOT_LIBS)   $(PPSUB_LIBS)
    514
  • branches/cnb_branches/cnb_branch_20090301/ppSub/src/ppSub.c

    r21524 r23352  
    3434        goto die;
    3535    }
     36
     37    ppSubVersionPrint();
    3638
    3739    if (!pmModelClassInit()) {
     
    7577    psTimerStop();
    7678
    77     pmSubtractionVisualClose(); //close plot windows, if -visual is set
     79    pmVisualClose(); //close plot windows, if -visual is set
    7880    psFree(config);
    7981    pmModelClassCleanup();
  • branches/cnb_branches/cnb_branch_20090301/ppSub/src/ppSub.h

    r21524 r23352  
    8989    );
    9090
    91 /// Put the program version information into a metadata
    92 void ppSubVersionMetadata(psMetadata *metadata ///< Metadata to populate
     91/// Put the program version information into a header
     92bool ppSubVersionHeader(psMetadata *header ///< Header to populate
    9393    );
     94
     95/// Print version information
     96void ppSubVersionPrint(void);
    9497
    9598
  • branches/cnb_branches/cnb_branch_20090301/ppSub/src/ppSubArguments.c

    r21524 r23352  
    2929{
    3030    fprintf(stderr, "\nPan-STARRS PSF-matched image subtraction\n\n");
    31     fprintf(stderr, "Usage: %s INPUT.fits REFERENCE.fits OUTPUT_ROOT \n"
    32             "\t[-psf REFERENCE.psf.fits] [-sources REFERENCE.cmf]\n\n"
     31    fprintf(stderr, "Usage: %s OUTPUT_ROOT \n"
     32            "\t[-psf REFERENCE.psf.fits]\n\n"
    3333            "This subtracts the convolved REFERENCE from the INPUT, by default.\n",
    3434            program);
     
    191191bool ppSubArgumentsSetup(int argc, char *argv[], pmConfig *config)
    192192{
    193     int argnum;                         // Argument Number
     193    //    int argnum;                         // Argument Number
    194194    assert(config);
    195195
     
    200200    }
    201201
    202     if ((argnum = psArgumentGet(argc, argv, "-psphot-visual"))) {
    203         psArgumentRemove(argnum, &argc, argv);
    204         psphotSetVisual(true);
    205     }
    206 
    207     pmConfigFileSetsMD(config->arguments, &argc, argv, "PPSUB.SOURCES", "-sources", NULL);
    208202
    209203    psMetadata *arguments = config->arguments; // Command-line arguments
     204    psMetadataAddStr(arguments, PS_LIST_TAIL, "-inimage", 0, "Input image", NULL);
    210205    psMetadataAddStr(arguments, PS_LIST_TAIL, "-inmask", 0, "Input mask image", NULL);
    211206    psMetadataAddStr(arguments, PS_LIST_TAIL, "-invariance", 0, "Input variance image", NULL);
     207    psMetadataAddStr(arguments, PS_LIST_TAIL, "-insources", 0, "Input source list", NULL);
     208    psMetadataAddStr(arguments, PS_LIST_TAIL, "-refimage", 0, "Reference image", NULL);
    212209    psMetadataAddStr(arguments, PS_LIST_TAIL, "-refmask", 0, "Reference mask image", NULL);
    213210    psMetadataAddStr(arguments, PS_LIST_TAIL, "-refvariance", 0, "Reference variance image", NULL);
     211    psMetadataAddStr(arguments, PS_LIST_TAIL, "-refsources", 0, "Reference source list", NULL);
     212    psMetadataAddStr(arguments, PS_LIST_TAIL, "-kernel", 0, "Precalculated kernel to apply", NULL);
    214213    psMetadataAddStr(arguments, PS_LIST_TAIL, "-stats", 0, "Statistics file", NULL);
    215214    psMetadataAddF32(arguments, PS_LIST_TAIL, "-region", 0, "Size of iso-kernel region", NAN);
     
    228227    psMetadataAddF32(arguments, PS_LIST_TAIL, "-spacing", 0, "Typical stamp spacing (pixels)", NAN);
    229228    psMetadataAddS32(arguments, PS_LIST_TAIL, "-footprint", 0, "Stamp footprint half-size (pixels)", -1);
     229    psMetadataAddF32(arguments, PS_LIST_TAIL, "-source-radius", 0, "Source matching radius (pixels)", NAN);
    230230    psMetadataAddS32(arguments, PS_LIST_TAIL, "-stride", 0, "Size of convolution patches (pixels)", -1);
    231231    psMetadataAddF32(arguments, PS_LIST_TAIL, "-threshold", 0, "Minimum threshold for stamps (ADU)", NAN);
     
    256256    psMetadataAddBool(arguments, PS_LIST_TAIL, "-visual", 0, "Show diagnostic plots", NULL);
    257257
    258     if (argc == 1 || !psArgumentParse(arguments, &argc, argv) || argc != 4) {
     258    if (argc == 1 || !psArgumentParse(arguments, &argc, argv) || argc != 2) {
    259259        usage(argv[0], arguments, config);
    260260    }
    261261
    262     fileList("INPUT", argv[1], "Name of the input image",     config);
    263     fileList("REF",   argv[2], "Name of the reference image", config);
    264262    psMetadataAddStr(config->arguments, PS_LIST_TAIL, "OUTPUT", 0, "Name of the output image", argv[3]);
    265263
     264
     265    const char *inImage = psMetadataLookupStr(NULL, arguments, "-inimage"); // Name of input image
     266    if (inImage && strlen(inImage) > 0) {
     267        fileList("INPUT", inImage, "Name of the input image", config);
     268    }
    266269    const char *inMask = psMetadataLookupStr(NULL, arguments, "-inmask"); // Name of input mask
    267270    if (inMask && strlen(inMask) > 0) {
     
    272275        fileList("INPUT.VARIANCE", inVariance, "Name of the input variance image", config);
    273276    }
    274 
     277    const char *inSources = psMetadataLookupStr(NULL, arguments, "-insources"); // Name of input source list
     278    if (inSources && strlen(inSources) > 0) {
     279        fileList("INPUT.SOURCES", inSources, "Name of the input source list", config);
     280    }
     281
     282    const char *refImage = psMetadataLookupStr(NULL, arguments, "-refimage"); // Name of reference image
     283    if (refImage && strlen(refImage) > 0) {
     284        fileList("INPUT", refImage, "Name of the reference image", config);
     285    }
    275286    const char *refMask = psMetadataLookupStr(NULL, arguments, "-refmask"); // Name of reference mask
    276287    if (refMask && strlen(refMask) > 0) {
     
    280291    if (refVariance && strlen(refVariance) > 0) {
    281292        fileList("REF.VARIANCE", refVariance, "Name of the reference variance image", config);
     293    }
     294    const char *refSources = psMetadataLookupStr(NULL, arguments, "-refsources"); // Name of ref source list
     295    if (refSources && strlen(refSources) > 0) {
     296        fileList("REF.SOURCES", refSources, "Name of the reference source list", config);
     297    }
     298
     299    const char *kernel = psMetadataLookupStr(NULL, arguments, "-kernel"); // Name of kernel
     300    if (kernel && strlen(kernel) > 0) {
     301        fileList("KERNEL", kernel, "Name of the kernel to apply", config);
    282302    }
    283303
     
    304324    }
    305325
    306     VALUE_ARG_RECIPE_FLOAT("-region",     "REGION.SIZE",     F32);
    307     VALUE_ARG_RECIPE_INT("-size",         "KERNEL.SIZE",     S32, 0);
    308     VALUE_ARG_RECIPE_INT("-order",        "SPATIAL.ORDER",   S32, -1);
    309     VALUE_ARG_RECIPE_FLOAT("-spacing",    "STAMP.SPACING",   F32);
    310     VALUE_ARG_RECIPE_INT("-rings-order",  "RINGS.ORDER",     S32, -1);
    311     VALUE_ARG_RECIPE_INT("-inner",        "INNER",           S32, -1);
    312     VALUE_ARG_RECIPE_INT("-spam-binning", "SPAM.BINNING",    S32, 0);
    313     VALUE_ARG_RECIPE_INT("-footprint",    "STAMP.FOOTPRINT", S32, -1);
    314     VALUE_ARG_RECIPE_INT("-stride",       "STRIDE",          S32, -1);
    315     VALUE_ARG_RECIPE_FLOAT("-threshold",  "STAMP.THRESHOLD", F32);
    316     VALUE_ARG_RECIPE_INT("-iter",         "ITER",            S32, -1);
    317     VALUE_ARG_RECIPE_FLOAT("-rej",        "REJ",             F32);
    318     VALUE_ARG_RECIPE_FLOAT("-sys",        "SYS",             F32);
    319     VALUE_ARG_RECIPE_FLOAT("-badfrac",    "BADFRAC",         F32);
    320     VALUE_ARG_RECIPE_FLOAT("-penalty",    "PENALTY",         F32);
    321     VALUE_ARG_RECIPE_FLOAT("-poor-frac",  "POOR.FRACTION",   F32);
    322     VALUE_ARG_RECIPE_INT("-bin1",         "BIN1",            S32, 0);
    323     VALUE_ARG_RECIPE_INT("-bin2",         "BIN2",            S32, 0);
     326    VALUE_ARG_RECIPE_FLOAT("-region",        "REGION.SIZE",     F32);
     327    VALUE_ARG_RECIPE_INT("-size",            "KERNEL.SIZE",     S32, 0);
     328    VALUE_ARG_RECIPE_INT("-order",           "SPATIAL.ORDER",   S32, -1);
     329    VALUE_ARG_RECIPE_FLOAT("-spacing",       "STAMP.SPACING",   F32);
     330    VALUE_ARG_RECIPE_INT("-rings-order",     "RINGS.ORDER",     S32, -1);
     331    VALUE_ARG_RECIPE_INT("-inner",           "INNER",           S32, -1);
     332    VALUE_ARG_RECIPE_INT("-spam-binning",    "SPAM.BINNING",    S32, 0);
     333    VALUE_ARG_RECIPE_INT("-footprint",       "STAMP.FOOTPRINT", S32, -1);
     334    VALUE_ARG_RECIPE_FLOAT("-source-radius", "SOURCE.RADIUS",   F32);
     335    VALUE_ARG_RECIPE_INT("-stride",          "STRIDE",          S32, -1);
     336    VALUE_ARG_RECIPE_FLOAT("-threshold",     "STAMP.THRESHOLD", F32);
     337    VALUE_ARG_RECIPE_INT("-iter",            "ITER",            S32, -1);
     338    VALUE_ARG_RECIPE_FLOAT("-rej",           "REJ",             F32);
     339    VALUE_ARG_RECIPE_FLOAT("-sys",           "SYS",             F32);
     340    VALUE_ARG_RECIPE_FLOAT("-badfrac",       "BADFRAC",         F32);
     341    VALUE_ARG_RECIPE_FLOAT("-penalty",       "PENALTY",         F32);
     342    VALUE_ARG_RECIPE_FLOAT("-poor-frac",     "POOR.FRACTION",   F32);
     343    VALUE_ARG_RECIPE_INT("-bin1",            "BIN1",            S32, 0);
     344    VALUE_ARG_RECIPE_INT("-bin2",            "BIN2",            S32, 0);
    324345
    325346    valueArgRecipeStr(arguments, recipe, "-mask-in",   "MASK.IN",  recipe);
     
    360381
    361382    if (psMetadataLookupBool(NULL, arguments, "-visual")) {
    362         pmSubtractionSetVisual(true);
     383        pmVisualSetVisual(true);
    363384    }
    364385
     
    376397    psTrace("ppSub", 1, "Done reading command-line arguments\n");
    377398
    378     // Dump configuration, now that's it's settled
    379     psBool status;
    380     psString dump_file =  psMetadataLookupStr(&status, config->arguments, "-dumpconfig");
    381     if (dump_file) {
    382         pmConfigCamerasCull(config, NULL);
    383         pmConfigRecipesCull(config, "PPSUB,PPSTATS,PSPHOT,MASKS");
    384 
    385         pmFPAfile *input = psMetadataLookupPtr(NULL, config->files, "PPSUB.INPUT"); // Input file
    386         pmConfigDump(config, input->fpa, dump_file);
    387     }
    388 
    389399    // XXX move this to ppSubArguments
    390400    int threads = psMetadataLookupS32(NULL, config->arguments, "-threads"); // Number of threads
  • branches/cnb_branches/cnb_branch_20090301/ppSub/src/ppSubBackground.c

    r21524 r23352  
    5353        }
    5454    }
    55     psImageBinning *binning = psMetadataLookupPtr(&mdok, psphotRecipe,
     55    psImageBinning *binning = psMetadataLookupPtr(&mdok, modelRO->analysis,
    5656                                                  "PSPHOT.BACKGROUND.BINNING"); // Binning for model
    5757    psImage *modelImage = modelRO->image; // Background model
  • branches/cnb_branches/cnb_branch_20090301/ppSub/src/ppSubCamera.c

    r21524 r23352  
    2222#include "ppSub.h"
    2323
     24// Define an input file
     25static pmFPAfile *defineInputFile(pmConfig *config,// Configuration
     26                                  pmFPAfile *bind,    // File to which to bind, or NULL
     27                                  char *filerule,     // Name of file rule
     28                                  char *argname,      // Argument name
     29                                  pmFPAfileType fileType // Type of file
     30    )
     31{
     32    bool status;
     33
     34    // look for the file on the RUN metadata
     35    pmFPAfile *file = pmFPAfileDefineFromRun(&status, config, filerule); // File to return
     36    if (!status) {
     37        psError(PS_ERR_UNKNOWN, false, "Failed to load file definition for %s", filerule);
     38        return NULL;
     39    }
     40    if (!file) {
     41        // look for the file on the argument list
     42        if (bind) {
     43            file = pmFPAfileBindFromArgs(&status, bind, config, filerule, argname);
     44        } else {
     45            file = pmFPAfileDefineFromArgs(&status, config, filerule, argname);
     46        }
     47        if (!status) {
     48            psError(PS_ERR_UNKNOWN, false, "Failed to load file definition for %s", filerule);
     49            return false;
     50        }
     51    }
     52
     53    if (!file) {
     54        return NULL;
     55    }
     56
     57    if (file->type != fileType) {
     58        psError(PS_ERR_UNKNOWN, true, "%s is not of type %s", filerule, pmFPAfileStringFromType(fileType));
     59        return NULL;
     60    }
     61
     62    return file;
     63}
     64
     65// Define an output file
     66static pmFPAfile *defineOutputFile(pmConfig *config, // Configuration
     67                                   pmFPAfile *template,    // File to use as basis for definition
     68                                   char *filerule,     // Name of file rule
     69                                   pmFPAfileType fileType // Type of file
     70    )
     71{
     72
     73    pmFPAfile *file = pmFPAfileDefineFromFile(config, template, 1, 1, filerule);
     74    if (!file) {
     75        psError(PS_ERR_IO, false, _("Unable to generate output file from %s"), filerule);
     76        return NULL;
     77    }
     78    if (file->type != fileType) {
     79        psError(PS_ERR_IO, true, "%s is not of type %s", filerule, pmFPAfileStringFromType(fileType));
     80        return NULL;
     81    }
     82
     83    return file;
     84}
     85
     86
     87// Define an output file that will be used in a calculation
     88// This means it might already be available in the RUN metadata
     89static pmFPAfile *defineCalcFile(pmConfig *config, // Configuration
     90                                 pmFPAfile *bind,    // File to which to bind, or NULL
     91                                 char *filerule,     // Name of file rule
     92                                 pmFPAfileType fileType // Type of file
     93    )
     94{
     95    bool status;
     96
     97    // look for the file on the RUN metadata
     98    pmFPAfile *file = pmFPAfileDefineFromRun(&status, config, filerule); // File to return
     99    if (!status) {
     100        psError(PS_ERR_UNKNOWN, false, "Failed to load file definition for %s", filerule);
     101        return NULL;
     102    }
     103    if (file) {
     104        // It's an input
     105        file->save = false;
     106    }
     107
     108    // define new version of file
     109    if (!file) {
     110        pmFPAfileDefineOutput(config, bind ? bind->fpa : NULL, filerule);
     111        if (!status) {
     112            psError(PS_ERR_UNKNOWN, false, "Failed to load file definition for %s", filerule);
     113            return false;
     114        }
     115        if (file) {
     116            // It's an output
     117            file->save = true;
     118        }
     119    }
     120
     121    if (!file) {
     122        return NULL;
     123    }
     124
     125    if (file->type != fileType) {
     126        psError(PS_ERR_UNKNOWN, true, "%s is not of type %s", filerule, pmFPAfileStringFromType(fileType));
     127        return NULL;
     128    }
     129
     130    return file;
     131}
     132
     133
    24134bool ppSubCamera(pmConfig *config)
    25135{
    26     bool status = false;                // result from pmFPAfileDefine operations
     136    psAssert(config, "Require configuration");
    27137
    28138    // Input image
    29     pmFPAfile *input = pmFPAfileDefineFromArgs(&status, config, "PPSUB.INPUT", "INPUT");
    30     if (!status || !input) {
     139    pmFPAfile *input = defineInputFile(config, NULL, "PPSUB.INPUT", "INPUT", PM_FPA_FILE_IMAGE);
     140    if (!input) {
    31141        psError(PS_ERR_IO, false, "Failed to build FPA from PPSUB.INPUT");
    32142        return false;
    33143    }
    34     if (input->type != PM_FPA_FILE_IMAGE) {
    35         psError(PS_ERR_IO, true, "PPSUB.INPUT is not of type IMAGE");
    36         return false;
    37     }
    38 
    39     // Input mask
    40     pmFPAfile *inputMask = pmFPAfileBindFromArgs(&status, input, config, "PPSUB.INPUT.MASK", "INPUT.MASK");
    41     if (!status) {
    42         psError (PS_ERR_UNKNOWN, false, "Failed to load file definition PPSUB.INPUT.MASK");
    43         return NULL;
    44     }
    45     if (inputMask && inputMask->type != PM_FPA_FILE_MASK) {
    46         psError(PS_ERR_IO, true, "PPSUB.INPUT.MASK is not of type MASK");
    47         return false;
    48     }
    49 
    50     // Input variance map
    51     pmFPAfile *inputVariance = pmFPAfileBindFromArgs(&status, input, config, "PPSUB.INPUT.VARIANCE", "INPUT.VARIANCE");
    52     if (!status) {
    53         psError (PS_ERR_UNKNOWN, false, "Failed to load file definition PPSUB.INPUT.VARIANCE");
    54         return NULL;
    55     }
    56     if (inputVariance && inputVariance->type != PM_FPA_FILE_VARIANCE) {
    57         psError(PS_ERR_IO, true, "PPSUB.INPUT.VARIANCE is not of type VARIANCE");
    58         return false;
    59     }
     144    defineInputFile(config, input, "PPSUB.INPUT.MASK", "INPUT.MASK", PM_FPA_FILE_MASK);
     145    pmFPAfile *inVar = defineInputFile(config, input, "PPSUB.INPUT.VARIANCE", "INPUT.VARIANCE",
     146                                       PM_FPA_FILE_VARIANCE);
     147    defineInputFile(config, input, "PPSUB.INPUT.SOURCES", "INPUT.SOURCES", PM_FPA_FILE_CMF);
    60148
    61149    // Reference image
    62     status = false;
    63     pmFPAfile *ref = pmFPAfileDefineFromArgs(&status, config, "PPSUB.REF", "REF");
     150    pmFPAfile *ref = defineInputFile(config, NULL, "PPSUB.REF", "REF", PM_FPA_FILE_IMAGE);
    64151    if (!ref) {
    65152        psError(PS_ERR_IO, false, "Failed to build FPA from PPSUB.REF");
    66153        return false;
    67154    }
    68     if (ref->type != PM_FPA_FILE_IMAGE) {
    69         psError(PS_ERR_IO, true, "PPSUB.REF is not of type IMAGE");
    70         return false;
    71     }
    72 
    73     // Reference mask
    74     pmFPAfile *refMask = pmFPAfileBindFromArgs(&status, ref, config, "PPSUB.REF.MASK", "REF.MASK");
    75     if (!status) {
    76         psError (PS_ERR_UNKNOWN, false, "Failed to load file definition PPSUB.REF.MASK");
    77         return NULL;
    78     }
    79     if (refMask && refMask->type != PM_FPA_FILE_MASK) {
    80         psError(PS_ERR_IO, true, "PPSUB.REF.MASK is not of type MASK");
    81         return false;
    82     }
    83 
    84     // Reference variance map
    85     pmFPAfile *refVariance = pmFPAfileBindFromArgs(&status, ref, config, "PPSUB.REF.VARIANCE", "REF.VARIANCE");
    86     if (!status) {
    87         psError (PS_ERR_UNKNOWN, false, "Failed to load file definition PPSUB.REF.VARIANCE");
    88         return NULL;
    89     }
    90     if (refVariance && refVariance->type != PM_FPA_FILE_VARIANCE) {
    91         psError(PS_ERR_IO, true, "PPSUB.REF.VARIANCE is not of type VARIANCE");
    92         return false;
    93     }
     155    defineInputFile(config, ref, "PPSUB.REF.MASK", "REF.MASK", PM_FPA_FILE_MASK);
     156    pmFPAfile *refVar = defineInputFile(config, ref, "PPSUB.REF.VARIANCE", "REF.VARIANCE",
     157                                        PM_FPA_FILE_VARIANCE);
     158    defineInputFile(config, ref, "PPSUB.REF.SOURCES", "REF.SOURCES", PM_FPA_FILE_CMF);
     159
    94160
    95161    // Output image
    96     pmFPAfile *output = pmFPAfileDefineFromFile(config, input, 1, 1, "PPSUB.OUTPUT");
    97     if (!output) {
    98         psError(PS_ERR_IO, false, _("Unable to generate output file from PPSUB.OUTPUT"));
    99         return false;
    100     }
    101     if (output->type != PM_FPA_FILE_IMAGE) {
    102         psError(PS_ERR_IO, true, "PPSUB.OUTPUT is not of type IMAGE");
     162    pmFPAfile *output = defineOutputFile(config, input, "PPSUB.OUTPUT", PM_FPA_FILE_IMAGE);
     163    pmFPAfile *outMask = defineOutputFile(config, output, "PPSUB.OUTPUT.MASK", PM_FPA_FILE_MASK);
     164    if (!output || !outMask) {
     165        psError(PS_ERR_UNKNOWN, false, "Unable to define output files");
    103166        return false;
    104167    }
    105168    output->save = true;
    106 
    107     // Output mask
    108     pmFPAfile *outMask = pmFPAfileDefineOutput(config, output->fpa, "PPSUB.OUTPUT.MASK");
    109     if (!outMask) {
    110         psError(PS_ERR_IO, false, _("Unable to generate output file from PPSUB.OUTPUT.MASK"));
    111         return false;
    112     }
    113     if (outMask->type != PM_FPA_FILE_MASK) {
    114         psError(PS_ERR_IO, true, "PPSUB.OUTPUT.MASK is not of type MASK");
    115         return false;
    116     }
    117169    outMask->save = true;
    118 
    119     // Output variance
    120     if (inputVariance && refVariance) {
    121         pmFPAfile *outVariance = pmFPAfileDefineOutput(config, output->fpa, "PPSUB.OUTPUT.VARIANCE");
    122         if (!outVariance) {
    123             psError(PS_ERR_IO, false, _("Unable to generate output file from PPSUB.OUTPUT.VARIANCE"));
    124             return false;
    125         }
    126         if (outVariance->type != PM_FPA_FILE_VARIANCE) {
    127             psError(PS_ERR_IO, true, "PPSUB.OUTPUT.VARIANCE is not of type VARIANCE");
    128             return false;
    129         }
    130         outVariance->save = true;
    131     }
     170    pmFPAfile *outVar = NULL;
     171    if (inVar && refVar) {
     172        outVar = defineOutputFile(config, output, "PPSUB.OUTPUT.VARIANCE", PM_FPA_FILE_VARIANCE);
     173        if (!outVar) {
     174            psError(PS_ERR_UNKNOWN, false, "Unable to define output files");
     175            return false;
     176        }
     177        outVar->save = true;
     178    }
     179
    132180
    133181    // Convolved input image
    134     pmFPAfile *inConv = pmFPAfileDefineFromFile(config, input, 1, 1, "PPSUB.INPUT.CONV");
    135     if (!inConv) {
    136         psError(PS_ERR_IO, false, _("Unable to generate output file for PPSUB.INPUT.CONV"));
    137         return false;
    138     }
    139     if (output->type != PM_FPA_FILE_IMAGE) {
    140         psError(PS_ERR_IO, true, "PPSUB.INPUT.CONV is not of type IMAGE");
    141         return false;
    142     }
    143     // XXX should be based on recipe : inConv->save = true;
    144 
    145     // Convolved input mask
    146     pmFPAfile *inConvMask = pmFPAfileDefineOutput(config, inConv->fpa, "PPSUB.INPUT.CONV.MASK");
    147     if (!inConvMask) {
    148         psError(PS_ERR_IO, false, _("Unable to generate output file from PPSUB.INPUT.CONV.MASK"));
    149         return false;
    150     }
    151     if (inConvMask->type != PM_FPA_FILE_MASK) {
    152         psError(PS_ERR_IO, true, "PPSUB.INPUT.CONV.MASK is not of type MASK");
    153         return false;
    154     }
    155     // XXX should be based on recipe : inConvMask->save = true;
    156 
    157     // Convolved input variance
    158     if (inputVariance) {
    159         pmFPAfile *inConvVariance = pmFPAfileDefineOutput(config, inConv->fpa, "PPSUB.INPUT.CONV.VARIANCE");
    160         if (!inConvVariance) {
    161             psError(PS_ERR_IO, false, _("Unable to generate output file from PPSUB.OUTPUT.VARIANCE"));
    162             return false;
    163         }
    164         if (inConvVariance->type != PM_FPA_FILE_VARIANCE) {
    165             psError(PS_ERR_IO, true, "PPSUB.INPUT.CONV.VARIANCE is not of type VARIANCE");
    166             return false;
    167         }
    168         // XXX should be based on recipe : inConvVariance->save = true;
     182    pmFPAfile *inConvImage = defineOutputFile(config, input, "PPSUB.INPUT.CONV", PM_FPA_FILE_IMAGE);
     183    pmFPAfile *inConvMask = defineOutputFile(config, input, "PPSUB.INPUT.CONV.MASK", PM_FPA_FILE_MASK);
     184    if (!inConvImage || !inConvMask) {
     185        psError(PS_ERR_UNKNOWN, false, "Unable to define output files");
     186        return false;
     187    }
     188    if (inVar) {
     189        pmFPAfile *inConvVar = defineOutputFile(config, input, "PPSUB.INPUT.CONV.VARIANCE",
     190                                                PM_FPA_FILE_VARIANCE);
     191        if (!inConvVar) {
     192            psError(PS_ERR_UNKNOWN, false, "Unable to define output files");
     193            return false;
     194        }
    169195    }
    170196
    171197    // Convolved ref image
    172     pmFPAfile *refConv = pmFPAfileDefineFromFile(config, ref, 1, 1, "PPSUB.REF.CONV");
    173     if (!refConv) {
    174         psError(PS_ERR_IO, false, _("Unable to generate output file for PPSUB.REF.CONV"));
    175         return false;
    176     }
    177     if (output->type != PM_FPA_FILE_IMAGE) {
    178         psError(PS_ERR_IO, true, "PPSUB.REF.CONV is not of type IMAGE");
    179         return false;
    180     }
    181     // XXX should be based on recipe : refConv->save = true;
    182 
    183     // Convolved ref mask
    184     pmFPAfile *refConvMask = pmFPAfileDefineOutput(config, refConv->fpa, "PPSUB.REF.CONV.MASK");
    185     if (!refConvMask) {
    186         psError(PS_ERR_IO, false, _("Unable to generate output file from PPSUB.REF.CONV.MASK"));
    187         return false;
    188     }
    189     if (refConvMask->type != PM_FPA_FILE_MASK) {
    190         psError(PS_ERR_IO, true, "PPSUB.REF.CONV.MASK is not of type MASK");
    191         return false;
    192     }
    193     // XXX should be based on recipe : refConvMask->save = true;
    194 
    195     // Convolved ref variance
    196     if (refVariance) {
    197         pmFPAfile *refConvVariance = pmFPAfileDefineOutput(config, refConv->fpa, "PPSUB.REF.CONV.VARIANCE");
    198         if (!refConvVariance) {
    199             psError(PS_ERR_IO, false, _("Unable to generate output file from PPSUB.OUTPUT.VARIANCE"));
    200             return false;
    201         }
    202         if (refConvVariance->type != PM_FPA_FILE_VARIANCE) {
    203             psError(PS_ERR_IO, true, "PPSUB.REF.CONV.VARIANCE is not of type VARIANCE");
    204             return false;
    205         }
    206         // XXX should be based on recipe : refConvVariance->save = true;
    207     }
     198    pmFPAfile *refConvImage = defineOutputFile(config, input, "PPSUB.REF.CONV", PM_FPA_FILE_IMAGE);
     199    pmFPAfile *refConvMask = defineOutputFile(config, input, "PPSUB.REF.CONV.MASK", PM_FPA_FILE_MASK);
     200    if (!refConvImage || !refConvMask) {
     201        psError(PS_ERR_UNKNOWN, false, "Unable to define output files");
     202        return false;
     203    }
     204    if (refVar) {
     205        pmFPAfile *refConvVar = defineOutputFile(config, input, "PPSUB.REF.CONV.VARIANCE",
     206                                                 PM_FPA_FILE_VARIANCE);
     207        if (!refConvVar) {
     208            psError(PS_ERR_UNKNOWN, false, "Unable to define output files");
     209            return false;
     210        }
     211    }
     212
    208213
    209214    // Output JPEGs
     
    230235
    231236    // Output subtraction kernel
    232     pmFPAfile *outKernels = pmFPAfileDefineOutput(config, output->fpa, "PPSUB.OUTPUT.KERNELS");
    233     if (!outKernels) {
    234         psError(PS_ERR_IO, false, _("Unable to generate output file from PPSUB.OUTPUT.KERNELS"));
    235         return false;
    236     }
    237     if (outKernels->type != PM_FPA_FILE_SUBKERNEL) {
    238         psError(PS_ERR_IO, true, "PPSUB.OUTPUT.KERNELS is not of type SUBKERNEL");
    239         return false;
    240     }
    241     outKernels->save = true;
    242 
    243 #if 0
    244     if (!pmFPAAddSourceFromFormat(output->fpa, "Subtraction", output->format)) {
    245         psError(PS_ERR_UNKNOWN, false, "Unable to generate output FPA.");
    246         return false;
    247     }
    248 #endif
    249 
    250     pmFPAfile *sources = pmFPAfileDefineFromArgs(&status, config, "PPSUB.SOURCES", "PPSUB.SOURCES");
    251     if (!status) {
    252         psError(PS_ERR_IO, false, "Failed to load file definition PPSUB.SOURCES");
    253         return false;
    254     }
    255     if (sources && sources->type != PM_FPA_FILE_CMF) {
    256         psError(PS_ERR_IO, true, "PPSUB.SOURCES is not of type CMF");
     237    pmFPAfile *kernel = defineCalcFile(config, output, "PPSUB.OUTPUT.KERNELS", PM_FPA_FILE_SUBKERNEL);
     238    if (!kernel) {
     239        psError(PS_ERR_UNEXPECTED_NULL, false, "Unable to define file PPSUB.OUTPUT.KERNELS");
    257240        return false;
    258241    }
  • branches/cnb_branches/cnb_branch_20090301/ppSub/src/ppSubLoop.c

    r21524 r23352  
    2323bool ppSubLoop(pmConfig *config)
    2424{
     25    psAssert(config, "Require configuration.");
     26
     27    pmConfigCamerasCull(config, NULL);
     28    pmConfigRecipesCull(config, "PPSUB,PPSTATS,PSPHOT,MASKS,JPEG");
     29
    2530    bool mdok;                          // Status of MD lookup
    2631    const char *statsName = psMetadataLookupStr(&mdok, config->arguments, "STATS"); // Filename for statistics
     
    5964
    6065    pmFPAview *view = pmFPAviewAlloc(0); // Pointer into FPA hierarchy
    61     pmHDU *lastHDU = NULL;              // Last HDU that was updated
    6266
    6367    // Iterate over the FPA hierarchy
     
    99103            if (!pmFPAfileIOChecks(config, view, PM_FPA_BEFORE)) {
    100104                return false;
    101             }
    102 
    103             // Put version information into the header
    104             pmHDU *hdu = pmHDUFromCell(inCell);
    105             if (hdu && hdu != lastHDU) {
    106                 if (!hdu->header) {
    107                     hdu->header = psMetadataAlloc();
    108                 }
    109                 ppSubVersionMetadata(hdu->header);
    110                 lastHDU = hdu;
    111105            }
    112106
     
    183177    }
    184178
     179    psString dump_file = psMetadataLookupStr(&mdok, config->arguments, "-dumpconfig");
     180    if (dump_file) {
     181
     182        pmFPAfile *input = psMetadataLookupPtr(NULL, config->files, "PPSUB.INPUT"); // Input file
     183        pmConfigDump(config, input->fpa, dump_file);
     184    }
     185
    185186    return true;
    186187}
  • branches/cnb_branches/cnb_branch_20090301/ppSub/src/ppSubMakePSF.c

    r21524 r23352  
    8181    // Extract the loaded sources from the associated readout, and generate PSF
    8282    // Here, we assume the image is background-subtracted
    83     pmReadout *sourcesRO = pmFPAfileThisReadout(config->files, view, "PPSUB.SOURCES");
    84     psArray *sources = psMetadataLookupPtr(&mdok, sourcesRO->analysis, "PSPHOT.SOURCES");
     83    psArray *sources = psMetadataLookupPtr(&mdok, minuend->analysis, "PSPHOT.SOURCES");
    8584    if (!psphotReadoutFindPSF(config, view, sources)) {
    8685        psError(PS_ERR_UNKNOWN, false, "Unable to perform photometry on subtracted image.");
  • branches/cnb_branches/cnb_branch_20090301/ppSub/src/ppSubMatchPSFs.c

    r21524 r23352  
    4949    bool mdok;                          // Status of MD lookup
    5050
     51    // Load pre-calculated kernel, if available
     52    pmReadout *kernelRO = pmFPAfileThisReadout(config->files, view, "PPSUB.OUTPUT.KERNEL"); // RO with kernel
     53
    5154    // Sources in image, used for stamps: these must be loaded from previous analysis stages
    52     pmReadout *sourcesRO = pmFPAfileThisReadout(config->files, view, "PPSUB.SOURCES"); // Readout with sources
    53     psArray *sources = NULL;            // Sources in image; used for stamps
    54     if (sourcesRO) {
    55         sources = psMetadataLookupPtr(&mdok, sourcesRO->analysis, "PSPHOT.SOURCES");
     55    psArray *inSources = psMetadataLookupPtr(&mdok, inRO->analysis, "PSPHOT.SOURCES"); // Input source list
     56    psArray *refSources = psMetadataLookupPtr(&mdok, refRO->analysis, "PSPHOT.SOURCES"); // Ref source list
     57
     58    psArray *sources = NULL;            // Merged list of sources
     59    if (inSources && refSources) {
     60        float radius = psMetadataLookupF32(NULL, recipe, "SOURCE.RADIUS"); // Matching radius
     61        psArray *lists = psArrayAlloc(2); // Source lists
     62        lists->data[0] = psMemIncrRefCounter(inSources);
     63        lists->data[1] = psMemIncrRefCounter(refSources);
     64        sources = pmSourceMatchMerge(lists, radius);
     65        psFree(lists);
     66        if (!sources) {
     67            psError(PS_ERR_UNKNOWN, false, "Unable to merge source lists");
     68            return false;
     69        }
     70    } else if (inSources) {
     71        sources = psMemIncrRefCounter(inSources);
     72    } else if (refSources) {
     73        sources = psMemIncrRefCounter(refSources);
    5674    }
     75
     76    psMetadataAddArray(inConv->analysis, PS_LIST_TAIL, "PSPHOT.SOURCES", PS_META_REPLACE,
     77                       "Merged source list", sources);
     78    psMetadataAddArray(refConv->analysis, PS_LIST_TAIL, "PSPHOT.SOURCES", PS_META_REPLACE,
     79                       "Merged source list", sources);
     80    psFree(sources);                    // Drop reference
    5781
    5882    int footprint = psMetadataLookupS32(NULL, recipe, "STAMP.FOOTPRINT"); // Stamp half-size
     
    113137
    114138    // Match the PSFs
    115     if (!pmSubtractionMatch(inConv, refConv, inRO, refRO, footprint, stride, regionSize, spacing, threshold,
    116                             sources, stampsName, type, size, order, widths, orders, inner, ringsOrder,
    117                             binning, penalty, optimum, optWidths, optOrder, optThresh, iter, rej, sys,
    118                             maskVal, maskBad, maskPoor, poorFrac, badFrac, subMode)) {
    119         psError(PS_ERR_UNKNOWN, false, "Unable to match images.");
    120         return false;
     139    if (kernelRO) {
     140        if (!pmSubtractionMatchPrecalc(inConv, refConv, inRO, refRO, kernelRO->analysis,
     141                                       stride, sys, maskVal, maskBad, maskPoor, poorFrac, badFrac)) {
     142            psError(PS_ERR_UNKNOWN, false, "Unable to convolve images.");
     143            return false;
     144        }
     145    } else {
     146        if (!pmSubtractionMatch(inConv, refConv, inRO, refRO, footprint, stride, regionSize, spacing,
     147                                threshold, sources, stampsName, type, size, order, widths, orders, inner,
     148                                ringsOrder, binning, penalty, optimum, optWidths, optOrder, optThresh, iter,
     149                                rej, sys, maskVal, maskBad, maskPoor, poorFrac, badFrac, subMode)) {
     150            psError(PS_ERR_UNKNOWN, false, "Unable to match images.");
     151            return false;
     152        }
    121153    }
    122154
     
    129161
    130162    // XXX drop the pixels associated with inRO and refRO (now that we have inConv and refConf)
    131 
     163#ifdef TESTING
    132164    psphotSaveImage (NULL, inRO->image, "inRO.fits");
    133165    psphotSaveImage (NULL, refRO->image, "refRO.fits");
    134166    psphotSaveImage (NULL, inConv->image, "inConv.fits");
    135167    psphotSaveImage (NULL, refConv->image, "refConv.fits");
     168#endif
    136169
    137170    return true;
  • branches/cnb_branches/cnb_branch_20090301/ppSub/src/ppSubReadoutUpdate.c

    r21524 r23352  
    4444    psMetadataAddStr(outHDU->header, PS_LIST_TAIL, "PPSUB.INPUT", 0,
    4545                     "Subtraction input", inFile->filename);
     46    ppSubVersionHeader(outHDU->header);
    4647
    4748    // Statistics on the matching
  • branches/cnb_branches/cnb_branch_20090301/ppSub/src/ppSubVarianceFactors.c

    r21524 r23352  
    6565
    6666    psStats *vfStats = psStatsAlloc(PS_STAT_ROBUST_MEDIAN); // Statistics
    67     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 0); // Random number generator
     67    psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS); // Random number generator
    6868
    6969    // mask these values when examining the background
  • branches/cnb_branches/cnb_branch_20090301/ppSub/src/ppSubVersion.c

    r21524 r23352  
    1919#include <psmodules.h>
    2020#include <ppStats.h>
     21#include <psphot.h>
    2122
    2223#include "ppSub.h"
    2324
    24 static const char *cvsTag = "$Name: not supported by cvs2svn $";///< CVS tag name
     25#ifndef PPSUB_VERSION
     26#error "PPSUB_VERSION is not set"
     27#endif
     28#ifndef PPSUB_BRANCH
     29#error "PPSUB_BRANCH is not set"
     30#endif
     31#ifndef PPSUB_SOURCE
     32#error "PPSUB_SOURCE is not set"
     33#endif
     34
     35#define xstr(s) str(s)
     36#define str(s) #s
    2537
    2638psString ppSubVersion(void)
    2739{
    28     psString version = NULL;            // Version, to return
    29     psStringAppend(&version, "%s-%s",PACKAGE_NAME,PACKAGE_VERSION);
    30     return version;
     40    char *value = NULL;
     41    psStringAppend(&value, "%s@%s", xstr(PPSUB_BRANCH), xstr(PPSUB_VERSION));
     42    return value;
     43}
     44
     45psString ppSubSource(void)
     46{
     47    return psStringCopy(xstr(PPSUB_SOURCE));
    3148}
    3249
    3350psString ppSubVersionLong(void)
    3451{
    35     psString version = ppSubVersion(); // Version, to return
    36     psString tag = psStringStripCVS(cvsTag, "Name"); // CVS tag
    37     psStringAppend(&version, " (cvs tag %s) %s, %s", tag, __DATE__, __TIME__);
    38     psFree(tag);
     52    psString version = ppSubVersion();  // Version, to return
     53    psString source = ppSubSource();    // Source
     54
     55    psStringPrepend(&version, "ppSub ");
     56    psStringAppend(&version, " from %s, built %s, %s", source, __DATE__, __TIME__);
     57    psFree(source);
     58
     59#ifdef __OPTIMIZE__
     60    psStringAppend(&version, " optimised");
     61#else
     62    psStringAppend(&version, " unoptimised");
     63#endif
     64
    3965    return version;
    40 }
     66};
    4167
    4268
    43 void ppSubVersionMetadata(psMetadata *metadata)
     69bool ppSubVersionHeader(psMetadata *header)
    4470{
    45     PS_ASSERT_METADATA_NON_NULL(metadata,);
    46 
    47     psString pslib = psLibVersionLong();// psLib version
    48     psString psmodules = psModulesVersionLong(); // psModules version
    49     psString ppStats = ppStatsVersionLong(); // ppStats version
    50     psString ppSub = ppSubVersionLong(); // ppSub version
     71    PS_ASSERT_METADATA_NON_NULL(header, false);
    5172
    5273    psTime *time = psTimeGetNow(PS_TIME_TAI); // The time now
    5374    psString timeString = psTimeToISO(time); // The time in an ISO string
    5475    psFree(time);
    55     psString head = NULL;               // Head string
    56     psStringAppend(&head, "ppSub processing at %s. Component information:", timeString);
     76    psString history = NULL;               // History string
     77    psStringAppend(&history, "ppSub at %s", timeString);
     78    psFree(timeString);
     79    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, history);
     80    psFree(history);
     81
     82    psLibVersionHeader(header);
     83    psModulesVersionHeader(header);
     84    psphotVersionHeader(header);
     85    ppStatsVersionHeader(header);
     86
     87    psString version = ppSubVersion(); // Software version
     88    psString source  = ppSubSource();  // Software source
     89
     90    psStringPrepend(&version, "ppSub version: ");
     91    psStringPrepend(&source, "ppSub source: ");
     92
     93    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, version);
     94    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, source);
     95
     96    psFree(version);
     97    psFree(source);
     98
     99    return true;
     100}
     101
     102void ppSubVersionPrint(void)
     103{
     104    psTime *time = psTimeGetNow(PS_TIME_TAI); // The time now
     105    psString timeString = psTimeToISO(time); // The time in an ISO string
     106    psFree(time);
     107    psLogMsg("ppSub", PS_LOG_INFO, "ppSub at %s", timeString);
    57108    psFree(timeString);
    58109
    59     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, head, "");
    60     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, pslib, "");
    61     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, psmodules, "");
    62     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, ppStats, "");
    63     psMetadataAddStr(metadata, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, ppSub, "");
     110    psString pslib = psLibVersionLong();// psLib version
     111    psString psmodules = psModulesVersionLong(); // psModules version
     112    psString psphot = psphotVersionLong(); // psphot version
     113    psString ppStats = ppStatsVersionLong(); // ppStats version
     114    psString ppSub = ppSubVersionLong(); // ppSub version
    64115
    65     psFree(head);
     116    psLogMsg("ppSub", PS_LOG_INFO, "%s", pslib);
     117    psLogMsg("ppSub", PS_LOG_INFO, "%s", psmodules);
     118    psLogMsg("ppSub", PS_LOG_INFO, "%s", psphot);
     119    psLogMsg("ppSub", PS_LOG_INFO, "%s", ppStats);
     120    psLogMsg("ppSub", PS_LOG_INFO, "%s", ppSub);
     121
    66122    psFree(pslib);
    67123    psFree(psmodules);
     124    psFree(psphot);
    68125    psFree(ppStats);
    69126    psFree(ppSub);
  • branches/cnb_branches/cnb_branch_20090301/ppSub/test/fake.c

    r18591 r23352  
    8989int main(int argc, char *argv[])
    9090{
    91     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 0); // Random number generator
     91    psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS); // Random number generator
    9292
    9393    // Images to generate
  • branches/cnb_branches/cnb_branch_20090301/psLib/configure.ac

    r21400 r23352  
    122122TMP_CPPFLAGS=${CPPFLAGS}
    123123
    124 AC_ARG_WITH(cfitsio,
    125 [AS_HELP_STRING(--with-cfitsio=DIR,Specify location of CFITSIO.)],
    126 [CFITSIO_CFLAGS="-I$withval/include"
    127  CFITSIO_LDFLAGS="-L$withval/lib"])
    128 AC_ARG_WITH(cfitsio-include,
    129 [AS_HELP_STRING(--with-cfitsio-include=DIR,Specify CFITSIO include directory.)],
    130 [CFITSIO_CFLAGS="-I$withval"])
    131 AC_ARG_WITH(cfitsio-lib,
    132 [AS_HELP_STRING(--with-cfitsio-lib=DIR,Specify CFITSIO library directory.)],
    133 [CFITSIO_LDFLAGS="-L$withval"])
     124PKG_CHECK_MODULES([CFITSIO], [cfitsio], [], AC_MSG_ERROR([CFITSIO package not found.  Obtain CFITSIO at  http://heasarc.gsfc.nasa.gov/docs/software/fitsio]))
     125
    134126PSLIB_CFLAGS="${PSLIB_CFLAGS=} ${CFITSIO_CFLAGS}"
    135 PSLIB_LIBS="${PSLIB_LIBS=} $CFITSIO_LDFLAGS -lcfitsio -lm"
     127PSLIB_LIBS="${PSLIB_LIBS=} ${CFITSIO_LIBS}"
    136128
    137129CFLAGS="${CFLAGS=} ${CFITSIO_CFLAGS}"
    138 LDFLAGS="${LDFLAGS=} ${CFITSIO_LDFLAGS}"
    139 
    140 dnl Solaris needs to suck in these symbols from unusual locations
    141 AC_SEARCH_LIBS([gethostbyname], [nsl])
    142 AC_SEARCH_LIBS([socket], [socket])
    143 
    144 AC_CHECK_HEADERS([fitsio.h],[],
    145    [AC_MSG_ERROR([CFITSIO headers not found.  Obtain CFITSIO at  http://heasarc.gsfc.nasa.gov/docs/software/fitsio or use --with-cfitsio to specify location.])]
    146 )
    147 TMP_LIBS=${LIBS}
    148 AC_CHECK_LIB(cfitsio,ffopen,[],
    149   [AC_MSG_ERROR([CFITSIO library not found.  Obtain it at  http://heasarc.gsfc.nasa.gov/docs/software/fitsio or use --with-cfitsio to specify location.])],[-lm]
    150 )
     130LDFLAGS="${LDFLAGS=} ${CFITSIO_LIBS}"
     131
    151132dnl Now check if CFITSIO supports fits_open_diskfile, i.e., is at least version 2.501
    152 AC_CHECK_LIB(cfitsio,ffdkopn,
     133AC_CHECK_FUNC(ffdkopn,
    153134  [CFITSIO_DISKFILE=1],
    154135  [AC_MSG_WARN([The CFITSIO library version is rather old.  Suggested version is 2.501 or greater.])
    155    CFITSIO_DISKFILE=0],[-lm]
     136   CFITSIO_DISKFILE=0]
    156137)
    157138
    158139AC_DEFINE_UNQUOTED([CFITSIO_DISKFILE],${CFITSIO_DISKFILE},[Define to 1 if you have fits_open_diskfile in CFITSIO])
     140
    159141AC_SUBST([CFITSIO_CFLAGS])
     142AC_SUBST([CFITSIO_LIBS])
    160143
    161144dnl restore the LIBS/CFLAGS/LDFLAGS
     
    173156TMP_CPPFLAGS=${CPPFLAGS}
    174157
    175 AC_ARG_WITH(fftw3,
    176 [AS_HELP_STRING(--with-fftw3=DIR,Specify location of FFTW version 3.)],
    177 [FFTW3_CFLAGS="-I$withval/include"
    178  FFTW3_LDFLAGS="-L$withval/lib"])
    179 AC_ARG_WITH(fftw3-include,
    180 [AS_HELP_STRING(--with-fftw3-include=DIR,Specify FFTW version 3 include directory.)],
    181 [FFTW3_CFLAGS="-I$withval"])
    182 AC_ARG_WITH(fftw3-lib,
    183 [AS_HELP_STRING(--with-fftw3-lib=DIR,Specify FFTW version 3 library directory.)],
    184 [FFTW3_LDFLAGS="-L$withval"])
     158PKG_CHECK_MODULES([FFTW3], [fftw3f], [], AC_MSG_ERROR([FFTW version 3 (--enable-float) library not found.  Obtain it at http://www.fftw.org/]))
     159
    185160PSLIB_CFLAGS="${PSLIB_CFLAGS=} ${FFTW3_CFLAGS}"
    186 PSLIB_LIBS="${PSLIB_LIBS=} $FFTW3_LDFLAGS -lfftw3f"
     161PSLIB_LIBS="${PSLIB_LIBS=} ${FFTW3_LIBS}"
    187162
    188163CFLAGS="${CFLAGS} ${FFTW3_CFLAGS}"
    189164CPPFLAGS=${CFLAGS}
    190 LDFLAGS="${LDFLAGS} ${FFTW3_LDFLAGS}"
    191 
    192 AC_CHECK_LIB(fftw3f,fftwf_plan_dft_2d,[],
    193   [AC_MSG_ERROR([FFTW version 3 (--enable-float) library not found.  Obtain it at http://www.fftw.org/ or use --with-fftw3 to specify location.])])
    194 
    195 FFTW_THREADS=0
    196 AC_CHECK_LIB(fftw3f,fftwf_init_threads,[FFTW_THREADS=1],
    197   [AC_CHECK_LIB(fftw3f_threads,fftwf_init_threads, [
    198     FFTW_THREADS=1
    199     PSLIB_LIBS="${PSLIB_LIBS=} -lfftw3f_threads"],
    200    AC_MSG_WARN([FFTW version 3 not compiled with thread support (--enable-threads)]),[-lm]
    201    )],[-lm]
    202 )
    203 
    204 dnl AC_CHECK_LIB(fftw3f,fftwf_plan_dft_2d,[],
    205 dnl   [AC_MSG_ERROR([FFTW version 3 (--enable-float) library not found.  Obtain it at http://www.fftw.org/ or use --with-fftw3 to specify location.])],[-lm]
    206 dnl )
    207 
    208 AC_CHECK_HEADERS([fftw3.h],[],
    209   [AC_MSG_ERROR([FFTW version 3 (--enable-float) headers not found.  Obtain it at http://www.fftw.org/ or use --with-fftw3 to specify location.])]
    210 )
    211 
     165LDFLAGS="${LDFLAGS} ${FFTW3_LIBS}"
     166
     167AC_CHECK_FUNC(fftwf_plan_dft_2d,[],
     168  [AC_MSG_ERROR([FFTW version 3 (--enable-float) library not found.  Obtain it at http://www.fftw.org/])])
     169AC_CHECK_FUNC(fftwf_init_threads,[FFTW_THREADS=1],[FFTW_THREADS=0])
    212170AC_DEFINE_UNQUOTED([HAVE_FFTW_THREADS],${FFTW_THREADS},[Define to 1 if you have FFTW compiled with thread support])
    213171
    214172AC_SUBST([FFTW3_CFLAGS])
     173AC_SUBST([FFTW3_LIBS])
    215174
    216175dnl restore the CFLAGS/LDFLAGS
     
    228187TMP_CPPFLAGS=${CPPFLAGS}
    229188
    230 AC_ARG_WITH(gsl-config,
    231 [AS_HELP_STRING(--with-gsl-config=FILE,Specify location of gsl-config.)],
    232 [GSL_CONFIG=$withval],
    233 [GSL_CONFIG=`which gsl-config`])
    234 AC_CHECK_FILE($GSL_CONFIG,[],
    235     [AC_MSG_ERROR([GSL is required.  Obtain it at http://www.gnu.org/software/gsl or use --with-gsl-config to specify location.])])
    236 
    237 AC_MSG_CHECKING([GSL cflags])
    238 GSL_CFLAGS="`${GSL_CONFIG} --cflags`"
    239 AC_MSG_RESULT([${GSL_CFLAGS}])
    240 
    241 AC_MSG_CHECKING([GSL ldflags])
    242 GSL_LDFLAGS="`${GSL_CONFIG} --libs`"
    243 AC_MSG_RESULT([${GSL_LDFLAGS}])
     189PKG_CHECK_MODULES([GSL], [gsl], [], AC_MSG_ERROR([GSL is required.  Obtain it at http://www.gnu.org/software/gsl]))
    244190
    245191PSLIB_CFLAGS="${PSLIB_CFLAGS=} ${GSL_CFLAGS}"
    246 PSLIB_LIBS="${PSLIB_LIBS=} ${GSL_LDFLAGS}"
     192PSLIB_LIBS="${PSLIB_LIBS=} ${GSL_LIBS}"
    247193
    248194AC_SUBST([GSL_CFLAGS])
     195AC_SUBST([GSL_LIBS])
    249196
    250197dnl restore the CFLAGS/LDFLAGS
     
    277224LDFLAGS="${LDFLAGS} ${JPEG_LDFLAGS}"
    278225
    279 AC_CHECK_HEADERS([jpeglib.h],[PSLIB_CFLAGS="$PSLIB_CFLAGS $JPEG_CFLAGS"
     226AC_CHECK_HEADERS([jpeglib.h],[PSLIB_CFLAGS="${PSLIB_CFLAGS=} ${JPEG_CFLAGS}"
    280227                              AC_SUBST(JPEG_CFLAGS)],
    281228  [AC_MSG_ERROR([libjpeg headers not found.  Obtain libjpeg from http://www.ijg.org/ or use --with-jpeg to specify location.])]
    282229)
    283230
    284 AC_CHECK_LIB(jpeg,jpeg_CreateCompress,[PSLIB_LIBS="$PSLIB_LIBS $JPEG_LDFLAGS -ljpeg"],
     231AC_CHECK_LIB(jpeg,jpeg_CreateCompress,[PSLIB_LIBS="${PSLIB_LIBS=} ${JPEG_LDFLAGS} -ljpeg"],
    285232  [AC_MSG_ERROR([libjpeg library not found.  Obtain libjpeg from http://www.ijg.org/ or use --with-jpeg to specify location.])]
    286233)
     
    291238LDFLAGS=${TMP_LDFLAGS}
    292239CPPFLAGS=${TMP_CPPFLAGS}
    293 
    294 dnl ------------------- XML2 options ---------------------
    295 dnl AC_ARG_WITH(xml2-config,
    296 dnl [AS_HELP_STRING(--with-xml2-config=FILE,Specify location of xml2-config.)],
    297 dnl [XML_CONFIG=$withval],
    298 dnl [XML_CONFIG=`which xml2-config`])
    299 dnl AC_CHECK_FILE($XML_CONFIG,[],
    300 dnl     [AC_MSG_ERROR([GNOME XML C parser is required.  Obtain it at http://www.xmlsoft.org or use --with-xml2-config to specify location.])])
    301 dnl
    302 dnl AC_MSG_CHECKING([xml2 version])
    303 dnl XML_VERSION=`xml2-config --version`
    304 dnl XML_VERSION_major=`echo $XML_VERSION | ${PERL} -pe 's|^(\d+).*|\1|'`
    305 dnl XML_VERSION_minor=`echo $XML_VERSION | ${PERL} -pe 's|^(\d+)\.(\d+).*|\2|'`
    306 dnl dnl First test the minimum version of 2.6
    307 dnl if test $XML_VERSION_major -lt 2 || ( test $XML_VERSION_major -eq 2 && test $XML_VERSION_minor -lt 6 )
    308 dnl then
    309 dnl     AC_MSG_ERROR([requires libxml2 2.6.0 or greater, found $XML_VERSION.  Install newer version or use --with-xml2-config to specify another location.])
    310 dnl else
    311 dnl     AC_MSG_RESULT([$XML_VERSION... yes])
    312 dnl fi
    313 dnl
    314 dnl AC_MSG_CHECKING([xml2 cflags])
    315 dnl XML_CFLAGS="`${XML_CONFIG} --cflags`"
    316 dnl AC_MSG_RESULT([${XML_CFLAGS}])
    317 dnl
    318 dnl AC_MSG_CHECKING([xml2 ldflags])
    319 dnl XML_LDFLAGS="`${XML_CONFIG} --libs`"
    320 dnl AC_MSG_RESULT([${XML_LDFLAGS}])
    321 dnl
    322 dnl PSLIB_CFLAGS="${PSLIB_CFLAGS=} ${XML_CFLAGS}"
    323 dnl PSLIB_LIBS="${PSLIB_LIBS=} ${XML_LDFLAGS}"
    324 dnl
    325 dnl AC_SUBST([XML_CFLAGS])
    326240
    327241dnl ------------------- SWIG options ---------------------
     
    477391  utils/Makefile
    478392])
    479 dnl src/xml/Makefile
    480 dnl test/xml/Makefile
    481 
    482393
    483394#if test "$SWIG_REQ" == "yes"
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/fits/psFitsHeader.c

    r22432 r23352  
    149149
    150150
    151 bool psFitsCheckSingleCompressedImagePHU(const psFits *fits, psMetadata *header)
     151bool psFitsCheckCompressedImagePHU(const psFits *fits, psMetadata *header)
    152152{
    153153    PS_ASSERT_FITS_NON_NULL(fits, false);
     
    163163    }
    164164
    165     if (psFitsGetSize(fits) != 2) {
    166         // No second extension, or multiple extensions
     165    if (psFitsGetSize(fits) == 1) {
     166        // No extension present
    167167        return false;
    168168    }
     
    416416    // Explore the potential case that this is an empty PHU, and the first extension contains the sole image,
    417417    // which is compressed.
    418     if (psFitsCheckSingleCompressedImagePHU(fits, header)) {
     418    if (psFitsCheckCompressedImagePHU(fits, header)) {
    419419        // This is really what we want, not the empty PHU
    420420        psTrace("psLib.fits", 1,
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/fits/psFitsHeader.h

    r15179 r23352  
    2020
    2121
    22 /// Determine whether the current HDU is an empty PHU with a single compressed image following.
     22/// Determine whether the current HDU is an empty PHU with a compressed image following.
    2323///
    2424/// In that case, what should be treated as an image PHU is technically an empty PHU with a binary table
     
    2626/// following compressed image to determine if this is the case.  If so, the FITS file pointer is left
    2727/// pointing at the compressed image.
    28 bool psFitsCheckSingleCompressedImagePHU(const psFits *fits, ///< FITS file pointer
    29                                          const psMetadata *header ///< Header, or NULL
     28bool psFitsCheckCompressedImagePHU(const psFits *fits, ///< FITS file pointer
     29                                   const psMetadata *header ///< Header, or NULL
    3030    );
    3131
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/fits/psFitsImage.c

    r21535 r23352  
    219219    PS_ASSERT_FITS_NON_NULL(fits, NULL);
    220220
    221     if (psFitsCheckSingleCompressedImagePHU(fits, NULL)) {
     221    if (psFitsCheckCompressedImagePHU(fits, NULL)) {
    222222        // This is really what we want, not the empty PHU
    223223        psTrace("psLib.fits", 1,
     
    432432    PS_ASSERT_INT_NONNEGATIVE(z, NULL);
    433433
    434     if (psFitsCheckSingleCompressedImagePHU(fits, NULL)) {
     434    if (psFitsCheckCompressedImagePHU(fits, NULL)) {
    435435        // This is really what we want, not the empty PHU
    436436        psTrace("psLib.fits", 1,
     
    479479    }
    480480
    481     if (psFitsCheckSingleCompressedImagePHU(fits, NULL)) {
     481    if (psFitsCheckCompressedImagePHU(fits, NULL)) {
    482482        // This is really what we want, not the empty PHU
    483483        psTrace("psLib.fits", 1,
     
    873873    // code replication, and should be sufficient for our needs.
    874874
    875     if (psFitsCheckSingleCompressedImagePHU(fits, NULL)) {
     875    if (psFitsCheckCompressedImagePHU(fits, NULL)) {
    876876        // This is really what we want, not the empty PHU
    877877        psTrace("psLib.fits", 1,
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/fits/psFitsScale.c

    r21183 r23352  
    112112    // psImageBackground automatically excludes pixels that are non-finite, so we don't need to bother about a
    113113    // mask.
    114     psU64 seed = p_psRandomGetSystemSeed(false);
    115     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, seed);
     114    psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS);
    116115    psStats *stats = psStatsAlloc(MEAN_STAT | STDEV_STAT); // Statistics object
    117116    if (!psImageBackground(stats, NULL, image, mask, maskVal, rng)) {
     
    290289    if (!psMemIncrRefCounter(rng) && options->fuzz) {
    291290        // Don't blab about which seed we're going to get --- it's not necessary for this purpose
    292         psU64 seed = p_psRandomGetSystemSeed(false);
    293         rng = psRandomAlloc(PS_RANDOM_TAUS, seed);
     291        rng = psRandomAlloc(PS_RANDOM_TAUS);
    294292    }
    295293
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/imageops/psImageCovariance.c

    r21467 r23352  
    4343    } else {
    4444        covar = psImageCovarianceNone();
     45    }
     46
     47    // Check for non-finite elements
     48    for (int y = kernel->yMin; y <= kernel->yMax; y++) {
     49        for (int x = kernel->xMin; x <= kernel->xMax; x++) {
     50            if (!isfinite(kernel->kernel[y][x])) {
     51                psError(PS_ERR_BAD_PARAMETER_VALUE, true,
     52                        "Non-finite covariance matrix element in kernel at %d,%d", x, y);
     53                psFree(covar);
     54                return NULL;
     55            }
     56        }
     57    }
     58    for (int y = covar->yMin; y <= covar->yMax; y++) {
     59        for (int x = covar->xMin; x <= covar->xMax; x++) {
     60            if (!isfinite(covar->kernel[y][x])) {
     61                psError(PS_ERR_BAD_PARAMETER_VALUE, true,
     62                        "Non-finite covariance matrix element in covariance matrix at %d,%d", x, y);
     63                psFree(covar);
     64                return NULL;
     65            }
     66        }
    4567    }
    4668
     
    110132float psImageCovarianceFactor(const psKernel *covariance)
    111133{
    112     return covariance ? covariance->kernel[0][0] : NAN;
     134    return covariance ? covariance->kernel[0][0] : 1.0;
    113135}
    114136
     
    144166        for (int y = covar->yMin; y <= covar->yMax; y++) {
    145167            for (int x = covar->xMin; x <= covar->xMax; x++) {
     168                if (!isfinite(covar->kernel[y][x])) {
     169                    psError(PS_ERR_BAD_PARAMETER_VALUE, true,
     170                            "Non-finite covariance matrix element at %d,%d for input %d",
     171                            x, y, i);
     172                    psFree(sum);
     173                    return NULL;
     174                }
    146175                sum->kernel[y][x] += covar->kernel[y][x];
    147176            }
     
    192221            int radius = PS_MAX(abs(x), abs(y)); // Squarish radius
    193222            psAssert(radius <= maxRadius, "Radius doesn't fit");
     223            if (!isfinite(covar->kernel[y][x])) {
     224                psError(PS_ERR_BAD_PARAMETER_VALUE, true, "Non-finite covariance matrix element at %d,%d",
     225                        x, y);
     226                return NULL;
     227            }
    194228            radiusSum->data.F64[radius] += fabsf(covar->kernel[y][x]);
    195229            sum += fabsf(covar->kernel[y][x]);
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/imageops/psImageInterpolate.c

    r21290 r23352  
    133133    }
    134134
    135     float norm1 = 2.0 / PS_SQR(M_PI); // Normalisation for laczos
    136     float norm2 = M_PI * 4.0 / (float)size; // Normalisation for sinc function 1
    137     float norm3 = M_PI_2 * 4.0 / (float)size; // Normalisation for sinc function 2
     135    float norm1 = size / 2.0 / PS_SQR(M_PI); // Normalisation for laczos
     136    float norm2 = M_PI;                // Normalisation for sinc function 1
     137    float norm3 = M_PI * 2.0 / (float)size; // Normalisation for sinc function 2
    138138    float pos = - (size - 1)/2 - frac;  // Position of interest
    139139    for (int i = 0; i < size; i++, pos += 1.0) {
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/math/psRandom.c

    r20547 r23352  
    2929#include <inttypes.h>
    3030
     31#include "psAbort.h"
    3132#include "psMemory.h"
    3233#include "psRandom.h"
     
    3839
    3940
     41unsigned long seed = 0;                 // Seed for RNG
     42
     43
    4044psU64 p_psRandomGetSystemSeed(bool log)
    4145{
    42     FILE*  fd;
    43     psU64  seedVal = 0;
    44     time_t timeVal;
     46    psU64 seedVal = 0;                  // Seed value to return
    4547
    46     fd = fopen("/dev/urandom","r");
    47     if(fd == NULL) {
    48         // Read system clock to get seed
    49         seedVal = (psU64)time(&timeVal);
    50     } else {
    51         // Read urandom to get seed
    52         if (fread(&seedVal, sizeof(psU64),1,fd)) {;} // ignore return value
    53         // Close file
    54         fclose(fd);
     48    // Since zero is a special value in our context, don't allow the final value chosen to be zero
     49    while (seedVal == 0) {
     50        FILE *fd = fopen("/dev/urandom", "r");
     51        if (fd) {
     52            // Read urandom to get seed
     53            if (fread(&seedVal, sizeof(psU64), 1, fd)) {;} // ignore return value
     54            // Close file
     55            fclose(fd);
     56        } else {
     57            // Read system clock to get seed
     58            time_t timeVal;                 // Time value
     59            seedVal = (psU64)time(&timeVal);
     60        }
    5561    }
    5662
     
    6369}
    6470
    65 psRandom *psRandomAlloc(psRandomType type,
    66                         unsigned long seed)
     71psU64 psRandomSeed(psU64 value)
    6772{
    68     gsl_rng   *r      = NULL;
    69     psRandom  *myRNG  = NULL;
     73    while (value == 0) {
     74        value = p_psRandomGetSystemSeed(false);
     75    }
     76    seed = value;
     77    return seed;
     78}
    7079
     80// Destructor for psRandom
     81static void randomFree(psRandom *rng)
     82{
     83    if (rng->gsl) {
     84        gsl_rng_free(rng->gsl);
     85    }
     86    return;
     87}
     88
     89// Constructor for psRandom
     90static psRandom *randomAlloc(psRandomType type)
     91{
     92    psRandom *rng = psAlloc(sizeof(psRandom)); // Random number generator to return
     93    psMemSetDeallocator(rng, (psFreeFunc)randomFree);
     94
     95    rng->type = type;
     96
     97    const gsl_rng_type *gslType;        // Type of RNG according to GSL
    7198    switch (type) {
    72     case PS_RANDOM_TAUS:
    73         myRNG = (psRandom*)psAlloc(sizeof(psRandom));
    74         r = gsl_rng_alloc(gsl_rng_taus);
    75         myRNG->gsl = r;
    76         if(seed == 0) {
    77             gsl_rng_set(myRNG->gsl, p_psRandomGetSystemSeed(true));
    78         } else {
    79             gsl_rng_set(myRNG->gsl, seed);
    80         }
    81         myRNG->type = type;
     99      case PS_RANDOM_TAUS:
     100        gslType = gsl_rng_taus;
    82101        break;
    83 
    84     default:
    85         psError(PS_ERR_UNEXPECTED_NULL, true, _("Unknown Random Number Generator Type"));
     102      default:
     103        psAbort("Unknown Random Number Generator Type: %x", type);
    86104        break;
    87105    }
    88106
    89     return(myRNG);
     107    rng->gsl = gsl_rng_alloc(gslType);
     108    return rng;
    90109}
    91110
    92 void psRandomReset(psRandom *rand,
    93                    unsigned long seed)
     111psRandom *psRandomAlloc(psRandomType type)
    94112{
    95     // Check null psRandom
    96     if(rand==NULL) {
    97         psError(PS_ERR_UNEXPECTED_NULL,
    98                 true,
    99                 _("Random variable is NULL."));
    100     } else {
    101         // Check seed value to see if system seed should be used
    102         if(seed == 0) {
    103             gsl_rng_set(rand->gsl,p_psRandomGetSystemSeed(true));
    104         } else {
    105             gsl_rng_set(rand->gsl, seed);
    106         }
     113    psRandom *rng = randomAlloc(type);
     114    psRandomReset(rng);
     115
     116    return rng;
     117}
     118
     119psRandom *psRandomAllocSpecific(psRandomType type, psU64 specificSeed)
     120{
     121    psRandom *rng = randomAlloc(type);
     122    if (specificSeed == 0) {
     123        specificSeed = p_psRandomGetSystemSeed(true);
    107124    }
     125    gsl_rng_set(rng->gsl, specificSeed);
     126    return rng;
     127}
     128
     129bool psRandomReset(psRandom *rand)
     130{
     131    PS_ASSERT_RANDOM_NON_NULL(rand, false);
     132    if (seed == 0) {
     133        seed = p_psRandomGetSystemSeed(true);
     134    }
     135    gsl_rng_set(rand->gsl, seed);
     136    return true;
    108137}
    109138
    110139double psRandomUniform(const psRandom *r)
    111140{
    112     // Check null psRandom variable
    113     if(r == NULL) {
    114         psError(PS_ERR_UNEXPECTED_NULL,
    115                 true,
    116                 _("Random variable is NULL."));
    117         return(0);
    118     } else {
    119         return(gsl_rng_uniform(r->gsl));
    120     }
     141    PS_ASSERT_RANDOM_NON_NULL(r, NAN);
     142    return gsl_rng_uniform(r->gsl);
    121143}
    122144
    123145double psRandomGaussian(const psRandom *r)
    124146{
    125     // Check null psRandom variable
    126     if(r == NULL) {
    127         psError(PS_ERR_UNEXPECTED_NULL,
    128                 true,
    129                 _("Random variable is NULL."));
    130         return(0);
    131     } else {
    132         // XXX: What should sigma be?
    133         return(gsl_ran_gaussian(r->gsl, 1.0));
    134     }
     147    PS_ASSERT_RANDOM_NON_NULL(r, NAN);
     148    return gsl_ran_gaussian(r->gsl, 1.0);
    135149}
    136150
    137151double p_psRandomGaussian(const psRandom *r, double sigma)
    138152{
    139     // Check null psRandom variable
    140     if(r == NULL) {
    141         psError(PS_ERR_UNEXPECTED_NULL,
    142                 true,
    143                 _("Random variable is NULL."));
    144         return(0);
    145     } else {
    146         return(gsl_ran_gaussian(r->gsl, sigma));
    147     }
     153    PS_ASSERT_RANDOM_NON_NULL(r, NAN);
     154    return gsl_ran_gaussian(r->gsl, sigma);
    148155}
    149156
    150157double psRandomPoisson(const psRandom *r, double mean)
    151158{
    152     // Check null psRandom variable
    153     if(r == NULL) {
    154         psError(PS_ERR_UNEXPECTED_NULL,
    155                 true,
    156                 _("Random variable is NULL."));
    157         return(0);
    158     } else {
    159         return((psF64) gsl_ran_poisson(r->gsl, mean));
    160     }
     159    PS_ASSERT_RANDOM_NON_NULL(r, NAN);
     160    return gsl_ran_poisson(r->gsl, mean);
    161161}
    162162
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/math/psRandom.h

    r15627 r23352  
    2929#include <gsl/gsl_randist.h>
    3030
    31 /** Enumeration containing a flag for psRandom types.  */
     31/// Random number generator types
    3232typedef enum {
    3333    PS_RANDOM_TAUS                     ///< A maximally equidistributed combined Tausworthe generator.
    3434} psRandomType;
    3535
    36 /** Data structure for psRandom.
    37  *  Contains information on the psRandom type and GNU Scientific Library random number generator.
    38  */
     36/// Random number generator
    3937typedef struct {
    4038    psRandomType type;                 ///< The type of RNG
     
    4846    );
    4947
    50 /** Allocates a psRandom struct.
    51  *
    52  *  @return psRandom*:    A new psRandom structure.
    53  */
     48/// Set the seed to use for random number generators.
     49///
     50/// A seed value of zero indicates that the seed is to be generated from the system.
     51/// The new seed value is returned
     52psU64 psRandomSeed(psU64 seed           ///< Seed for RNG
     53                   );
     54
     55/// Allocate a random number generator
     56///
     57/// The currently defined seed (via psRandomSeed) is used
    5458psRandom *psRandomAlloc(
    55     psRandomType type,                 ///< The type of RNG
    56     unsigned long seed                 ///< Known value with which to seed the RNG
     59    psRandomType type                   ///< The type of RNG
    5760) PS_ATTR_MALLOC;
    5861
    59 /** Resets an existing psRandom struct.
    60  *
    61  *  @return void
    62  */
    63 void psRandomReset(
    64     psRandom *rand,                    ///< Existing psRandom struct to reset
    65     unsigned long seed                 ///< Known value with which to seed the RNG
     62/// Allocate a random number generator with a specific seed
     63///
     64/// A seed value of zero indicates that the seed is to be generated from the system.
     65psRandom *psRandomAllocSpecific(psRandomType type, ///< The type of RNG
     66                                psU64 specificSeed ///< The specific seed to use
     67    );
     68
     69/// Resets an existing random number generator
     70bool psRandomReset(
     71    psRandom *rand                      ///< Random number generator to reset
    6672);
    6773
     
    7278 */
    7379double psRandomUniform(
    74     const psRandom *r                  ///< psRandom struct for RNG
     80    const psRandom *r                  ///< Random number generator
    7581);
    7682
     
    8187 */
    8288double psRandomGaussian(
    83     const psRandom *r                  ///< psRandom struct for RNG
     89    const psRandom *r                  ///< Random number generator
    8490);
    8591
    86 /** Random number generator based on a Gaussian deviate, N(0,1).
     92/** Random number generator based on a Gaussian deviate with specified standard deviation.
    8793 *  Uses gsl_ran_gaussian.
    88  *
    89  *  XXX: I created this since the above psLib spec for p_psRandomGaussian
    90  *  had no argument for sigma.  Verify that with IfA.
    9194 *
    9295 *  @return double:     Random number.
    9396 */
    9497double p_psRandomGaussian(
    95     const psRandom *r,                  ///< psRandom struct for RNG
     98    const psRandom *r,                  ///< Random number generator
    9699    double sigma
    97100);
     
    103106 */
    104107double psRandomPoisson(
    105     const psRandom *r,                 ///< psRandom struct for RNG
     108    const psRandom *r,                  ///< Random number generator
    106109    double mean                         ///< Mean value
    107110);
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/math/psStats.c

    r21183 r23352  
    199199    for (long i = 0; i < numData; i++) {
    200200        // Check if the data is with the specified range
     201        if (!isfinite(data[i]))
     202            continue;
    201203        if (useRange && (data[i] < stats->min))
    202204            continue;
     
    322324    // into the temporary vectors.
    323325    for (long i = 0; i < inVector->n; i++) {
     326        if (!isfinite(input[i]))
     327            continue;
    324328        if (useRange && (input[i] < stats->min))
    325329            continue;
     
    420424    for (long i = 0; i < myVector->n; i++) {
    421425        // Check if the data is with the specified range
     426        if (!isfinite(data[i]))
     427            continue;
    422428        if (useRange && (data[i] < stats->min)) {
    423429            continue;
     
    501507    for (long i = 0; i < myVector->n; i++) {
    502508        // Check if the data is with the specified range
     509        if (!isfinite(data[i]))
     510            continue;
    503511        if (useRange && (data[i] < stats->min)) {
    504512            continue;
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/pslib_strict.h

    r21283 r23352  
    110110#include "psMetadataItemParse.h"
    111111#include "psMetadataItemCompare.h"
     112#include "psMetadataHeader.h"
    112113#include "psPixels.h"
    113114#include "psArguments.h"
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/sys/Makefile.am

    r19056 r23352  
    33noinst_LTLIBRARIES = libpslibsys.la
    44
    5 libpslibsys_la_CPPFLAGS = $(SRCINC) $(PSLIB_CFLAGS) $(CFITSIO_CFLAGS)
     5# PSLIB_VERSION=`if [ -e ../../VERSION ]; then cat ../../VERSION; else svnversion; fi`
     6# PSLIB_BRANCH=`if [ -e ../../BRANCH ]; then cat ../../BRANCH; else svn info | sed -n -e '/URL:/ h' -e '/Repository Root:/ { x; H; x; s|Repository Root: \(.*\)\nURL: \1\(.*\)|\2| ; s|^/|| ; s|/[a-zA-Z]*/src.*|| ; p }'; fi`
     7# PSLIB_SOURCE=`if [ -e ../../SOURCE ]; then cat ../../SOURCE; else svn info | sed -n -e 's/Repository UUID: // p'; fi`
     8
     9# Force recompilation of psConfigure.c, since it gets the version information
     10psConfigure.c: FORCE
     11        touch psConfigure.c
     12FORCE: ;
     13
     14libpslibsys_la_CPPFLAGS = $(SRCINC) $(PSLIB_CFLAGS) $(CFITSIO_CFLAGS) -DPSLIB_VERSION=$(SVN_VERSION) -DPSLIB_BRANCH=$(SVN_BRANCH) -DPSLIB_SOURCE=$(SVN_SOURCE)
    615libpslibsys_la_SOURCES = \
    716        psAbort.c \
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/sys/psConfigure.c

    r18953 r23352  
    1212 *  @author Ross Harman, MHPCC
    1313 *  @author Robert DeSonia, MHPCC
     14 *  @author Paul Price, IfA
    1415 *
    15  *  @version $Revision: 1.28 $ $Name: not supported by cvs2svn $
    16  *  @date $Date: 2008-08-08 18:05:08 $
    17  *
    18  *  Copyright 2004-2005 Maui High Performance Computing Center, University of Hawaii
     16 *  Copyright 2004-2009 Institute for Astronomy, University of Hawaii
    1917 */
    2018
     
    2624#include <stdlib.h>
    2725#include <string.h>
     26
     27#include <fitsio.h>
     28#include <longnam.h>
     29#include <fftw3.h>
     30#include <gsl/gsl_version.h>
     31#ifdef HAVE_PSDB
     32#include <mysql.h>
     33#endif
    2834
    2935#include "psAbort.h"
     
    4147static FILE *memCheckFile = NULL;       // File to which to write results of mem check
    4248
    43 static const char *cvsTag = "$Name: not supported by cvs2svn $"; // CVS tag name
     49#ifndef PSLIB_VERSION
     50#error "PSLIB_VERSION is not set"
     51#endif
     52#ifndef PSLIB_BRANCH
     53#error "PSLIB_BRANCH is not set"
     54#endif
     55#ifndef PSLIB_SOURCE
     56#error "PSLIB_SOURCE is not set"
     57#endif
     58
     59#define xstr(s) str(s)
     60#define str(s) #s
    4461
    4562psString psLibVersion(void)
    4663{
    47     psString version = NULL;            // Version, to return
    48     psStringAppend(&version, "%s-%s",PACKAGE_NAME,PACKAGE_VERSION);
    49     return version;
     64    char *value = NULL;
     65    psStringAppend(&value, "%s@%s", xstr(PSLIB_BRANCH), xstr(PSLIB_VERSION));
     66    return value;
     67}
     68
     69psString psLibSource(void)
     70{
     71    return psStringCopy(xstr(PSLIB_SOURCE));
     72}
     73
     74psString psLibDependencies(void)
     75{
     76    psString deps = NULL;               // Dependencies, to return
     77    float cfitsioVersion;               // CFITSIO version number
     78    psStringAppend(&deps, "cfitsio-%.3f gsl-%s %s",
     79                   fits_get_version(&cfitsioVersion), gsl_version, fftwf_version);
     80
     81#ifdef HAVE_PSDB
     82    psStringAppend(&deps, " mysql-%s", mysql_get_client_info());
     83#endif
     84
     85    return deps;
    5086}
    5187
    5288psString psLibVersionLong(void)
    5389{
    54     psString version = psLibVersion();    // Version, to return
    55     psString tag = psStringStripCVS(cvsTag, "Name"); // CVS tag
     90    psString version = psLibVersion();  // Version, to return
     91    psString source = psLibSource();    // Source
     92    psString deps = psLibDependencies();// Dependencies
    5693
    57 #ifdef HAVE_PSDB
    58     psStringAppend(&version, " (cvs tag %s), %s, %s with psDB", tag, __DATE__, __TIME__);
     94    psStringPrepend(&version, "psLib ");
     95    psStringAppend(&version, " from %s, built %s, %s with %s",
     96                   source, __DATE__, __TIME__, deps);
     97    psFree(source);
     98    psFree(deps);
     99
     100#ifdef __OPTIMIZE__
     101    psStringAppend(&version, " optimised");
    59102#else
    60     psStringAppend(&version, " (cvs tag %s), %s, %s without psDB", tag, __DATE__, __TIME__);
     103    psStringAppend(&version, " unoptimised");
    61104#endif
    62     psFree(tag);
     105
     106#ifdef PS_NO_TRACE
     107    psStringAppend(&version, " without trace");
     108#else
     109    psStringAppend(&version, " with trace");
     110#endif
     111
    63112    return version;
    64 }
     113};
    65114
    66115// Check the memory; intended for use on exit, but might be used elsewhere
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/sys/psConfigure.h

    r13950 r23352  
    2020#define PS_CONFIGURE_H
    2121
     22#include <psString.h>
     23
    2224/// @addtogroup SysUtils System Utilities
    2325/// @{
     
    2931 *  @return psString: String with version name.
    3032 */
    31 psString psLibVersion(
    32     void
    33 );
     33psString psLibVersion(void);
    3434
     35/** Get current psLib source
     36 *
     37 * Returns the current psLib source name as a string.
     38 *
     39 * @return psString: String with source name.
     40 */
     41psString psLibSource(void);
     42
     43/** Get psLib dependencies' versions
     44 *
     45 * Returns the psLib dependency versions as a string.
     46 *
     47 * @return psString: String with dependencies.
     48 */
     49psString psLibDependencies(void);
    3550
    3651/** Get current psLib version (full identification)
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/sys/psLogMsg.c

    r20546 r23352  
    195195    }
    196196
    197     int fileD = creat(dest, 0666);
     197    int fileD = open(dest, O_WRONLY | O_CREAT, 0666);
    198198    if (fileD == 0) {
    199199        psError(PS_ERR_IO, true, _("Could not open file '%s' for output."), dest);
     
    316316
    317317    if (write(logFD, head, strlen(head))) {;} // ignore return value
    318    
     318
    319319    if (logMsg) {
    320320        psString msg = NULL;            // Message to print
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/sys/psMemory.c

    r21346 r23352  
    10691069                   memBlock->func, memBlock->file, memBlock->lineno, (unsigned long)memBlock->tid);
    10701070}
     1071
     1072bool psMemTypeEqual (void *ptr1, void *ptr2) {
     1073
     1074    // if ptr is a psAlloc()'d memory, find the actual address of the memBlock
     1075    psMemBlock *memBlock1 = ((psMemBlock *)ptr1) - 1;
     1076    HANDLE_BAD_BLOCK(memBlock1, __FILE__, __LINE__, __func__);
     1077    if (!memBlock1->freeFunc) return false;
     1078
     1079    // if ptr is a psAlloc()'d memory, find the actual address of the memBlock
     1080    psMemBlock *memBlock2 = ((psMemBlock *)ptr2) - 1;
     1081    HANDLE_BAD_BLOCK(memBlock2, __FILE__, __LINE__, __func__);
     1082    if (!memBlock2->freeFunc) return false;
     1083
     1084    return (memBlock1->freeFunc == memBlock2->freeFunc);
     1085}
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/sys/psMemory.h

    r15047 r23352  
    636636);
    637637
     638/** test for matching types (equal free functions)
     639 *
     640 * This function returns true if the two pointers have matching, non-NULL free functions.
     641 * Supplied pointers must have been allocated within the psLib memory system (ie, with a psAlloc) or the function will abort. (XXX just return false?)
     642 * Supplied pointers must have been provided with free function or the function returns false.
     643 */
     644bool psMemTypeEqual (void *ptr1, ///< pointer to first psMemory object
     645                     void *ptr2 ///< pointer to second psMemory object
     646  );
     647
    638648// Ensure this is a psLib pointer
    639649#define PS_ASSERT_PTR_HEAVY(PTR, RVAL) \
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/types/Makefile.am

    r18145 r23352  
    1414        psMetadataItemParse.c \
    1515        psMetadataItemCompare.c \
     16        psMetadataHeader.c \
    1617        psPixels.c \
    1718        psArguments.c   \
     
    3031        psMetadataItemParse.h \
    3132        psMetadataItemCompare.h \
     33        psMetadataHeader.h \
    3234        psPixels.h \
    3335        psArguments.h   \
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/types/psMetadata.h

    r21278 r23352  
    3030#include "psLookupTable.h"
    3131#include "psMutex.h"
     32#include "psError.h"
    3233
    3334#define PS_DATA_IS_PRIMITIVE(TYPE) \
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/types/psMetadataConfig.c

    r22707 r23352  
    14771477            }
    14781478
    1479             psString newStr = psMetadataConfigFormat(item->data.md);
    1480             if (newStr) {
     1479            psMetadata *md = item->data.md; // Metadata at new level
     1480            if (md) {
     1481                psString newStr = psMetadataConfigFormat(item->data.md);
     1482                if (!newStr) {
     1483                    psError(PS_ERR_UNKNOWN, false, "Unable to format metadata %s", item->name);
     1484                    psFree(content);
     1485                    return NULL;
     1486                }
     1487
    14811488                // add 3 extra spaces to each metadata folder item
    14821489                char *buf = strtok(newStr, "\n");
     
    14871494                psFree(newStr);
    14881495            }
    1489 
    14901496            psStringAppend(&content, "\nEND\n");
    14911497            break;
  • branches/cnb_branches/cnb_branch_20090301/psLib/test/fits/tap_psFitsImage.c

    r19382 r23352  
    1212static psImage *generateImage(void)
    1313{
    14     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 12345); // Random number generator
     14    psRandom *rng = psRandomAllocSpecific(PS_RANDOM_TAUS, 12345); // Random number generator
    1515    psImage *image = psImageAlloc(NUMCOLS, NUMROWS, PS_TYPE_F32); // Generated image
    1616    for (int y = 0; y < NUMROWS; y++) {
  • branches/cnb_branches/cnb_branch_20090301/psLib/test/imageops/convolutionBench.c

    r17320 r23352  
    6868int main(int argc, char *argv[])
    6969{
    70     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 0); // Random number generator
     70    psRandom *rng = psRandomAllocSpecific(PS_RANDOM_TAUS, 0); // Random number generator
    7171
    7272    printf("#%14s%16s        %8s        %8s\n", "Image", "Kernel", "Direct", "FFT");
  • branches/cnb_branches/cnb_branch_20090301/psLib/test/imageops/tap_psImageInterpolate2.c

    r21465 r23352  
    7777    psImage *variance = NULL; // generateVariance(xSize, ySize, type);
    7878    psImage *mask = NULL; // generateMask(xSize, ySize);
    79     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 12345);
     79    psRandom *rng = psRandomAllocSpecific(PS_RANDOM_TAUS, 12345);
    8080
    8181    psImageInterpolation *interp = psImageInterpolationAlloc(mode, image, variance, mask, 0, NAN, NAN,
  • branches/cnb_branches/cnb_branch_20090301/psLib/test/math/tap_psMinimizeLMM.c

    r13124 r23352  
    9595    {
    9696        psMemId id = psMemGetId();
    97         psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 1); // Random number generator; using known seed
     97        psRandom *rng = psRandomAllocSpecific(PS_RANDOM_TAUS, 1); // Random number generator; using known seed
    9898        psMinimization *min = psMinimizationAlloc(NUM_ITERATIONS, ERR_TOL);
    9999        psArray *ordinates = psArrayAlloc(NUM_DATA_POINTS);
     
    203203    {
    204204        psMemId id = psMemGetId();
    205         psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 1); // Random number generator; using known seed
     205        psRandom *rng = psRandomAllocSpecific(PS_RANDOM_TAUS, 1); // Random number generator; using known seed
    206206        psMinimization *min = psMinimizationAlloc(NUM_ITERATIONS, ERR_TOL);
    207207        psArray *ordinates = psArrayAlloc(NUM_DATA_POINTS);
  • branches/cnb_branches/cnb_branch_20090301/psLib/test/math/tap_psPolyFit1D.c

    r13337 r23352  
    109109    psVector *xTruth = psVectorAlloc(numData, PS_TYPE_F64);
    110110    psVector *fTruth = psVectorAlloc(numData, PS_TYPE_F64);
    111     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 1); // Using a known seed
     111    psRandom *rng = psRandomAllocSpecific(PS_RANDOM_TAUS, 1); // Using a known seed
    112112    for (int i = 0; i < numData; i++) {
    113113        xTruth->data.F64[i] = (flags & TS00_X_NULL) ? i : 2.0*psRandomUniform(rng) - 1.0;
  • branches/cnb_branches/cnb_branch_20090301/psLib/test/math/tap_psPolyFit2D.c

    r17567 r23352  
    108108    yTruth->n = numData;
    109109    fTruth->n = numData;
    110     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 1); // Using an RNG with a known seed
     110    psRandom *rng = psRandomAllocSpecific(PS_RANDOM_TAUS, 1); // Using an RNG with a known seed
    111111    for (int i = 0; i < numData; i++) {
    112112        xTruth->data.F64[i] = 2.0*psRandomUniform(rng) - 1.0;
  • branches/cnb_branches/cnb_branch_20090301/psLib/test/math/tap_psPolyFit3D.c

    r17567 r23352  
    108108    zTruth->n = numData;
    109109    fTruth->n = numData;
    110     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 1); // Using known seed
     110    psRandom *rng = psRandomAllocSpecific(PS_RANDOM_TAUS, 1); // Using known seed
    111111    for (int i = 0; i < numData; i++) {
    112112        xTruth->data.F64[i] = 2.0*psRandomUniform(rng) - 1.0;
  • branches/cnb_branches/cnb_branch_20090301/psLib/test/math/tap_psPolyFit4D.c

    r17567 r23352  
    132132    tTruth->n = numData;
    133133    fTruth->n = numData;
    134     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 1); // Using known seed
     134    psRandom *rng = psRandomAllocSpecific(PS_RANDOM_TAUS, 1); // Using known seed
    135135    for (int i = 0; i < numData; i++) {
    136136        xTruth->data.F64[i] = 2.0*psRandomUniform(rng) - 1.0;
  • branches/cnb_branches/cnb_branch_20090301/psLib/test/math/tap_psRandom.c

    r13123 r23352  
    33work properly.
    44 
    5     ensure that psRandom structs are properly allocated by psRandomAlloc().
     5    ensure that psRandom structs are properly allocated by psRandomAllocSpecific().
    66    ensure that psRandomUniform() produces a sequence of numbers with
    77        proper mean and stdev.
     
    4747    plan_tests(34);
    4848
    49     // ensure that psRandom structs are properly allocated by psRandomAlloc()
     49    // ensure that psRandom structs are properly allocated by psRandomAllocSpecific()
    5050    {
    5151        psMemId id = psMemGetId();
    5252        // Valid type allocation
    53         psRandom *myRNG = psRandomAlloc(PS_RANDOM_TAUS, SEED);
    54         ok(myRNG != NULL, "psRandom struct was allocated properly");
    55         skip_start(myRNG == NULL, 1, "Skipping tests because psRandomAlloc() failed");
    56         ok(myRNG->type == PS_RANDOM_TAUS, "psRandomAlloc() set type properly");
     53        psRandom *myRNG = psRandomAllocSpecific(PS_RANDOM_TAUS, SEED);
     54        ok(myRNG != NULL, "psRandom struct was allocated properly");
     55        skip_start(myRNG == NULL, 1, "Skipping tests because psRandomAllocSpecific() failed");
     56        ok(myRNG->type == PS_RANDOM_TAUS, "psRandomAllocSpecific() set type properly");
    5757        psFree(myRNG);
    5858        skip_end();
     
    6363    {
    6464        psMemId id = psMemGetId();
    65         psRandom *myRNG = psRandomAlloc(100,SEED);
    66         ok(myRNG == NULL, "psRandomAlloc() refused to generate psRandom with unallowed type");
     65        psRandom *myRNG = psRandomAllocSpecific(100,SEED);
     66        ok(myRNG == NULL, "psRandomAllocSpecific() refused to generate psRandom with unallowed type");
    6767        psFree(myRNG);
    6868        ok(!psMemCheckLeaks (id, NULL, NULL, false), "no memory leaks");
     
    7272    {
    7373        psMemId id = psMemGetId();
    74         psRandom *myRNG = psRandomAlloc(PS_RANDOM_TAUS,-5);
    75         ok(myRNG != NULL, "psRandomAlloc() allows negative seed");
     74        psRandom *myRNG = psRandomAllocSpecific(PS_RANDOM_TAUS,-5);
     75        ok(myRNG != NULL, "psRandomAllocSpecific() allows negative seed");
    7676        psFree(myRNG);
    7777        ok(!psMemCheckLeaks (id, NULL, NULL, false), "no memory leaks");
     
    8585        rans->n = rans->nalloc;
    8686        psStats *stats = psStatsAlloc(PS_STAT_SAMPLE_MEAN);
    87         psRandom *myRNG = psRandomAlloc(PS_RANDOM_TAUS, SEED);
    88         ok(myRNG != NULL, "psRandom struct was allocated properly");
    89         skip_start(myRNG == NULL, 2, "Skipping tests because psRandomAlloc() failed");
     87        psRandom *myRNG = psRandomAllocSpecific(PS_RANDOM_TAUS, SEED);
     88        ok(myRNG != NULL, "psRandom struct was allocated properly");
     89        skip_start(myRNG == NULL, 2, "Skipping tests because psRandomAllocSpecific() failed");
    9090
    9191        // Initialize vector data with random number
     
    125125        rans->n = rans->nalloc;
    126126        psStats *stats = psStatsAlloc(PS_STAT_SAMPLE_MEAN);
    127         psRandom *myRNG = psRandomAlloc(PS_RANDOM_TAUS, SEED);
    128         ok(myRNG != NULL, "psRandom struct was allocated properly");
    129         skip_start(myRNG == NULL, 2, "Skipping tests because psRandomAlloc() failed");
     127        psRandom *myRNG = psRandomAllocSpecific(PS_RANDOM_TAUS, SEED);
     128        ok(myRNG != NULL, "psRandom struct was allocated properly");
     129        skip_start(myRNG == NULL, 2, "Skipping tests because psRandomAllocSpecific() failed");
    130130
    131131        // Initialize vector with random data
     
    167167        rans->n = rans->nalloc;
    168168        psStats *stats = psStatsAlloc(PS_STAT_SAMPLE_MEAN);
    169         psRandom *myRNG = psRandomAlloc(PS_RANDOM_TAUS, SEED);
    170         ok(myRNG != NULL, "psRandom struct was allocated properly");
    171         skip_start(myRNG == NULL, 2, "Skipping tests because psRandomAlloc() failed");
     169        psRandom *myRNG = psRandomAllocSpecific(PS_RANDOM_TAUS, SEED);
     170        ok(myRNG != NULL, "psRandom struct was allocated properly");
     171        skip_start(myRNG == NULL, 2, "Skipping tests because psRandomAllocSpecific() failed");
    172172
    173173        // Initialize vector with random data
     
    210210        rans02->n = rans02->nalloc;
    211211
    212         psRandom *myRNG = psRandomAlloc(PS_RANDOM_TAUS, SEED);
    213         ok(myRNG != NULL, "psRandom struct was allocated properly");
    214         skip_start(myRNG == NULL, 1, "Skipping tests because psRandomAlloc() failed");
     212        psRandom *myRNG = psRandomAllocSpecific(PS_RANDOM_TAUS, SEED);
     213        ok(myRNG != NULL, "psRandom struct was allocated properly");
     214        skip_start(myRNG == NULL, 1, "Skipping tests because psRandomAllocSpecific() failed");
    215215
    216216
     
    252252    if (0) {
    253253        psRandom *myRNG1 = NULL;
    254         myRNG1 = psRandomAlloc(PS_RANDOM_TAUS, SEED);
     254        myRNG1 = psRandomAllocSpecific(PS_RANDOM_TAUS, SEED);
    255255        //    psLogSetDestination("dest:stderr");
    256256        psLogSetDestination(0);
     
    275275        rans02->n = rans02->nalloc;
    276276
    277         psRandom *myRNG = psRandomAlloc(PS_RANDOM_TAUS, SEED);
    278         ok(myRNG != NULL, "psRandom struct was allocated properly");
    279         skip_start(myRNG == NULL, 1, "Skipping tests because psRandomAlloc() failed");
     277        psRandom *myRNG = psRandomAllocSpecific(PS_RANDOM_TAUS, SEED);
     278        ok(myRNG != NULL, "psRandom struct was allocated properly");
     279        skip_start(myRNG == NULL, 1, "Skipping tests because psRandomAllocSpecific() failed");
    280280
    281281
     
    325325        rans02->n = rans02->nalloc;
    326326
    327         psRandom *myRNG = psRandomAlloc(PS_RANDOM_TAUS, SEED);
    328         ok(myRNG != NULL, "psRandom struct was allocated properly");
    329         skip_start(myRNG == NULL, 1, "Skipping tests because psRandomAlloc() failed");
     327        psRandom *myRNG = psRandomAllocSpecific(PS_RANDOM_TAUS, SEED);
     328        ok(myRNG != NULL, "psRandom struct was allocated properly");
     329        skip_start(myRNG == NULL, 1, "Skipping tests because psRandomAllocSpecific() failed");
    330330
    331331        // Initialize vectors with random data
  • branches/cnb_branches/cnb_branch_20090301/psLib/test/math/tap_psStats07.c

    r12247 r23352  
    5858    PS_ASSERT_INT_NONNEGATIVE(Npts, NULL);
    5959
    60     //    psRandom *r = psRandomAlloc(PS_RANDOM_TAUS, p_psRandomGetSystemSeed());
    61     psRandom *r = psRandomAlloc(PS_RANDOM_TAUS, PS_XXX_GAUSSIAN_SEED);
     60    //    psRandom *r = psRandomAllocSpecific(PS_RANDOM_TAUS, p_psRandomGetSystemSeed());
     61    psRandom *r = psRandomAllocSpecific(PS_RANDOM_TAUS, PS_XXX_GAUSSIAN_SEED);
    6262    psVector* gauss = psVectorAlloc(Npts, PS_TYPE_F32);
    6363    for (unsigned int i = 0; i < Npts; i++) {
  • branches/cnb_branches/cnb_branch_20090301/psLib/test/math/tap_psStats09.c

    r12783 r23352  
    5252    srand(SEED);
    5353
    54     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 1); // Random number generator; using known seed
     54    psRandom *rng = psRandomAllocSpecific(PS_RANDOM_TAUS, 1); // Random number generator; using known seed
    5555    psVector *truth = psVectorAlloc(numData, PS_TYPE_F64);
    5656    for (long i = 0; i < numData; i++) {
  • branches/cnb_branches/cnb_branch_20090301/psLib/test/math/tap_psStatsTiming.c

    r12513 r23352  
    2020
    2121    // build a gauss-deviate vector (mean = 0.0, sigma = 1.0) for tests
    22     psRandom *seed = psRandomAlloc (PS_RANDOM_TAUS, 0);
     22    psRandom *seed = psRandomAllocSpecific (PS_RANDOM_TAUS, 0);
    2323    psVector *rnd = psVectorAlloc (1000, PS_TYPE_F32);
    2424    for (int i = 0; i < rnd->n; i++) {
  • branches/cnb_branches/cnb_branch_20090301/psLib/test/math/tst_psMinimizeLMM.c

    r11686 r23352  
    6666    psBool testStatus = true;
    6767
    68     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 1); // Random number generator; using known seed
     68    psRandom *rng = psRandomAllocSpecific(PS_RANDOM_TAUS, 1); // Random number generator; using known seed
    6969    psMinimization *min = psMinimizationAlloc(NUM_ITERATIONS, ERR_TOL);
    7070    psArray *ordinates = psArrayAlloc(NUM_DATA_POINTS);
  • branches/cnb_branches/cnb_branch_20090301/psLib/test/math/tst_psPolyFit1D.c

    r11686 r23352  
    101101    xTruth->n = numData;
    102102    fTruth->n = numData;
    103     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 1); // Using a known seed
     103    psRandom *rng = psRandomAllocSpecific(PS_RANDOM_TAUS, 1); // Using a known seed
    104104    for (int i = 0; i < numData; i++) {
    105105        xTruth->data.F64[i] = (flags & TS00_X_NULL) ? i : 2.0*psRandomUniform(rng) - 1.0;
  • branches/cnb_branches/cnb_branch_20090301/psLib/test/math/tst_psPolyFit2D.c

    r11686 r23352  
    100100    yTruth->n = numData;
    101101    fTruth->n = numData;
    102     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 1); // Using an RNG with a known seed
     102    psRandom *rng = psRandomAllocSpecific(PS_RANDOM_TAUS, 1); // Using an RNG with a known seed
    103103    for (int i = 0; i < numData; i++) {
    104104        xTruth->data.F64[i] = 2.0*psRandomUniform(rng) - 1.0;
  • branches/cnb_branches/cnb_branch_20090301/psLib/test/math/tst_psPolyFit3D.c

    r11686 r23352  
    103103    zTruth->n = numData;
    104104    fTruth->n = numData;
    105     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 1); // Using known seed
     105    psRandom *rng = psRandomAllocSpecific(PS_RANDOM_TAUS, 1); // Using known seed
    106106    for (int i = 0; i < numData; i++) {
    107107        xTruth->data.F64[i] = 2.0*psRandomUniform(rng) - 1.0;
  • branches/cnb_branches/cnb_branch_20090301/psLib/test/math/tst_psPolyFit4D.c

    r11686 r23352  
    124124    tTruth->n = numData;
    125125    fTruth->n = numData;
    126     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 1); // Using known seed
     126    psRandom *rng = psRandomAllocSpecific(PS_RANDOM_TAUS, 1); // Using known seed
    127127    for (int i = 0; i < numData; i++) {
    128128        xTruth->data.F64[i] = 2.0*psRandomUniform(rng) - 1.0;
  • branches/cnb_branches/cnb_branch_20090301/psLib/test/math/tst_psRandom.c

    r6484 r23352  
    33work properly.
    44 
    5     t00(): ensure that psRandom structs are properly allocated by psRandomAlloc().
     5    t00(): ensure that psRandom structs are properly allocated by psRandomAllocSpecific().
    66    t01(): ensure that psRandomUniform() produces a sequence of numbers with
    77    proper mean and stdev.
     
    4545
    4646testDescription tests[] = {
    47                               {testRandomAlloc,000,"psRandomAlloc",0,false},
     47                              {testRandomAlloc,000,"psRandomAllocSpecific",0,false},
    4848                              {testRandomUniform,000,"psRandomUniform",0,false},
    4949                              {testRandomGaussian,000,"psRandomGaussian",0,false},
     
    7070
    7171    // Valid type allocation
    72     myRNG = psRandomAlloc(PS_RANDOM_TAUS, SEED);
     72    myRNG = psRandomAllocSpecific(PS_RANDOM_TAUS, SEED);
    7373    if (myRNG == NULL) {
    7474        psError(PS_ERR_UNKNOWN,true,"Could not allocate psRandom structure");
     
    8585    //    psLogSetDestination("file:seed_msglog1.txt");
    8686    psLogSetDestination(fd1);
    87     myRNG = psRandomAlloc(PS_RANDOM_TAUS, 0);
     87    myRNG = psRandomAllocSpecific(PS_RANDOM_TAUS, 0);
    8888    //    psLogSetDestination("dest:stderr");
    8989    psLogSetDestination(2);
     
    100100    // Invalid type allocation
    101101    psLogMsg(__func__,PS_LOG_INFO,"Invalid type, should generate error message");
    102     myRNG = psRandomAlloc(100,SEED);
     102    myRNG = psRandomAllocSpecific(100,SEED);
    103103    if (myRNG != NULL) {
    104104        psError(PS_ERR_UNKNOWN,true,"Did not return NULL for invalid type");
     
    107107
    108108    // Negative seed value
    109     myRNG = psRandomAlloc(PS_RANDOM_TAUS,-5);
     109    myRNG = psRandomAllocSpecific(PS_RANDOM_TAUS,-5);
    110110    if(myRNG == NULL) {
    111111        psError(PS_ERR_UNKNOWN,true,"Did not return allocated psRandom");
     
    125125    psStats *stats = psStatsAlloc(PS_STAT_SAMPLE_MEAN);
    126126
    127     myRNG = psRandomAlloc(PS_RANDOM_TAUS, SEED);
     127    myRNG = psRandomAllocSpecific(PS_RANDOM_TAUS, SEED);
    128128    if (myRNG == NULL) {
    129129        psError(PS_ERR_UNKNOWN,true,"Could not allocate psRandom structure");
     
    171171    psStats *stats = psStatsAlloc(PS_STAT_SAMPLE_MEAN);
    172172
    173     myRNG = psRandomAlloc(PS_RANDOM_TAUS, SEED);
     173    myRNG = psRandomAllocSpecific(PS_RANDOM_TAUS, SEED);
    174174    if (myRNG == NULL) {
    175175        psError(PS_ERR_UNKNOWN,true,"Could not allocate psRandom structure");
     
    219219    psStats *stats = psStatsAlloc(PS_STAT_SAMPLE_MEAN);
    220220
    221     myRNG = psRandomAlloc(PS_RANDOM_TAUS, SEED);
     221    myRNG = psRandomAllocSpecific(PS_RANDOM_TAUS, SEED);
    222222    if (myRNG == NULL) {
    223223        psError(PS_ERR_UNKNOWN,true,"Could not allocate psRandom structure");
     
    268268    rans02->n = rans02->nalloc;
    269269
    270     myRNG = psRandomAlloc(PS_RANDOM_TAUS, SEED);
     270    myRNG = psRandomAllocSpecific(PS_RANDOM_TAUS, SEED);
    271271    if (myRNG == NULL) {
    272272        psError(PS_ERR_UNKNOWN,true,"Could not allocate psRandom structure");
     
    302302
    303303    psRandom *myRNG1 = NULL;
    304     myRNG1 = psRandomAlloc(PS_RANDOM_TAUS, SEED);
     304    myRNG1 = psRandomAllocSpecific(PS_RANDOM_TAUS, SEED);
    305305    //    psLogSetDestination("dest:stderr");
    306306    psLogSetDestination(0);
     
    326326    rans02->n = rans02->nalloc;
    327327
    328     myRNG = psRandomAlloc(PS_RANDOM_TAUS, SEED);
     328    myRNG = psRandomAllocSpecific(PS_RANDOM_TAUS, SEED);
    329329    if (myRNG == NULL) {
    330330        psError(PS_ERR_UNKNOWN,true,"Could not allocate psRandom structure");
     
    372372    rans02->n = rans02->nalloc;
    373373
    374     myRNG = psRandomAlloc(PS_RANDOM_TAUS, SEED);
     374    myRNG = psRandomAllocSpecific(PS_RANDOM_TAUS, SEED);
    375375    if (myRNG == NULL) {
    376376        psError(PS_ERR_UNKNOWN,true,"Could not allocate psRandom structure");
  • branches/cnb_branches/cnb_branch_20090301/psLib/test/math/tst_psStats09.c

    r11686 r23352  
    5252    printPositiveTestHeader(stdout, "psMathUtils functions", "psVectorStats Clipped Stats Routine");
    5353
    54     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 1); // Random number generator; using known seed
     54    psRandom *rng = psRandomAllocSpecific(PS_RANDOM_TAUS, 1); // Random number generator; using known seed
    5555    psVector *truth = psVectorAlloc(numData, PS_TYPE_F64);
    5656    truth->n = numData;
  • branches/cnb_branches/cnb_branch_20090301/psLib/test/mathtypes/tap_psVectorSelect.c

    r18333 r23352  
    1717    psVector *vector = psVectorAlloc(size, PS_TYPE_F32);
    1818    psVectorInit(vector, 0.0);
    19     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 12345);
     19    psRandom *rng = psRandomAllocSpecific(PS_RANDOM_TAUS, 12345);
    2020    for (long i = 0; i < numNonzero; i++) {
    2121        long index = psRandomUniform(rng) * size;
     
    5252    psVector *vector = psVectorAlloc(size, PS_TYPE_F32);
    5353    psVectorInit(vector, 0.0);
    54     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 12345);
     54    psRandom *rng = psRandomAllocSpecific(PS_RANDOM_TAUS, 12345);
    5555    for (long i = 0; i < numNonzero; i++) {
    5656        long index = psRandomUniform(rng) * size;
  • branches/cnb_branches/cnb_branch_20090301/psLib/test/types/tap_psTree.c

    r18145 r23352  
    1616        psVector *y = psVectorAlloc(NUM, PS_TYPE_F64);
    1717
    18         psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 0);
     18        psRandom *rng = psRandomAllocSpecific(PS_RANDOM_TAUS, 0);
    1919        for (int i = 0; i < NUM; i++) {
    2020            x->data.F64[i] = 2.0 * psRandomUniform(rng) - 1.0;
  • branches/cnb_branches/cnb_branch_20090301/psastro

  • branches/cnb_branches/cnb_branch_20090301/psastro/src/Makefile.am

    r21422 r23352  
     1lib_LTLIBRARIES = libpsastro.la
    12
    2 lib_LTLIBRARIES = libpsastro.la
    3 libpsastro_la_CFLAGS = $(PSASTRO_CFLAGS) $(PSMODULE_CFLAGS) $(PSLIB_CFLAGS)
    4 libpsastro_la_LDFLAGS = $(PSASTRO_LIBS) $(PSMODULE_LIBS) $(PSLIB_LIBS)
     3libpsastro_la_CFLAGS = $(PSASTRO_CFLAGS) $(PPSTATS_CFLAGS) $(PSMODULE_CFLAGS) $(PSLIB_CFLAGS) -DPSASTRO_VERSION=$(SVN_VERSION) -DPSASTRO_BRANCH=$(SVN_BRANCH) -DPSASTRO_SOURCE=$(SVN_SOURCE)
     4libpsastro_la_LDFLAGS = $(PSASTRO_LIBS) $(PPSTATS_LIBS) $(PSMODULE_LIBS) $(PSLIB_LIBS)
     5
     6# Force recompilation of psastroVersion.c, since it gets the version information
     7# can we do this with dependency info?
     8# psastroVersion.c: FORCE
     9# touch psastroVersion.c
     10# FORCE: ;
    511
    612bin_PROGRAMS = psastro psastroModel psastroModelFit gpcModel
  • branches/cnb_branches/cnb_branch_20090301/psastro/src/psastro.c

    r21409 r23352  
    3434    if (!config) usage ();
    3535
     36    psastroVersionPrint();
     37
    3638    // load identify the data sources
    3739    if (!psastroParseCamera (config)) {
    38         psErrorStackPrint(stderr, "error setting up the camera\n");
    39         exit (1);
     40        psErrorStackPrint(stderr, "error setting up the camera\n");
     41        exit (1);
    4042    }
    4143
     
    4345    // select subset of stars for astrometry
    4446    if (!psastroDataLoad (config)) {
    45         psErrorStackPrint(stderr, "error loading input data\n");
    46         exit (1);
     47        psErrorStackPrint(stderr, "error loading input data\n");
     48        exit (1);
    4749    }
    4850
    4951    // run the full astrometry analysis (chip and/or mosaic)
    5052    if (!psastroAnalysis (config)) {
    51         psErrorStackPrint(stderr, "failure in psastro analysis\n");
    52         exit (1);
     53        psErrorStackPrint(stderr, "failure in psastro analysis\n");
     54        exit (1);
    5355    }
    54    
     56
    5557    // write out the results
    5658    if (!psastroDataSave (config)) {
    57         psErrorStackPrint(stderr, "failed to write out data\n");
    58         exit (1);
     59        psErrorStackPrint(stderr, "failed to write out data\n");
     60        exit (1);
    5961    }
    6062
  • branches/cnb_branches/cnb_branch_20090301/psastro/src/psastro.h

    r21422 r23352  
    9595// Return version strings.
    9696psString          psastroVersion(void);
     97psString          psastroSource(void);
    9798psString          psastroVersionLong(void);
     99bool              psastroVersionHeader(psMetadata *header);
     100bool              psastroVersionHeaderFull(psMetadata *header);
     101void              psastroVersionPrint(void);
    98102
    99103// demo plots
  • branches/cnb_branches/cnb_branch_20090301/psastro/src/psastroArguments.c

    r21422 r23352  
    66 *
    77 *  @author IfA
    8  *  @version $Revision: 1.34 $ $Name: not supported by cvs2svn $
    9  *  @date $Date: 2009-02-09 21:25:34 $
     8 *  @version $Revision: 1.34.2.1 $ $Name: not supported by cvs2svn $
     9 *  @date $Date: 2009-02-19 17:59:50 $
    1010 *  Copyright 2009 Institute for Astronomy, University of Hawaii
    1111 */
     
    100100    if ((N = psArgumentGet (argc, argv, "-visual"))) {
    101101        psArgumentRemove (N, &argc, argv);
    102         pmAstromSetVisual (true);
     102        pmVisualSetVisual (true);
    103103    }
    104104
  • branches/cnb_branches/cnb_branch_20090301/psastro/src/psastroCleanup.c

    r21422 r23352  
    66 *
    77 *  @author IfA
    8  *  @version $Revision: 1.8 $ $Name: not supported by cvs2svn $
    9  *  @date $Date: 2009-02-09 21:25:34 $
     8 *  @version $Revision: 1.8.2.1 $ $Name: not supported by cvs2svn $
     9 *  @date $Date: 2009-02-19 17:59:50 $
    1010 *  Copyright 2009 Institute for Astronomy, University of Hawaii
    1111 */
     
    1616
    1717    psFree (config);
    18     pmAstromVisualClose ();
     18    pmVisualClose ();
    1919
    2020    psTimerStop ();
  • branches/cnb_branches/cnb_branch_20090301/psastro/src/psastroConvert.c

    r21409 r23352  
    9999        int n = index->data.S32[i];
    100100        pmSource *source = sources->data[n];
    101         // XXX this needs to be flexible
     101
     102        psTrace ("psastro", 6, "mag: %f +/- %f, mode: %x, skip: %x\n", source->psfMag, source->errMag, source->mode, skip);
     103
    102104        if (source->mode & skip) {
    103105          nModeSkip ++;
    104106          continue;
    105107        }
     108
    106109        if ((iMagMax != 0.0) && (source->psfMag > iMagMax)) {
    107110          nFaintSkip ++;
  • branches/cnb_branches/cnb_branch_20090301/psastro/src/psastroDataSave.c

    r21409 r23352  
    1818  return false; \
    1919}
    20  
     20
    2121/**
    2222 * this loop saves the photometry/astrometry data files
     
    3131    psMetadata *recipe  = psMetadataLookupPtr (NULL, config->recipes, PSASTRO_RECIPE);
    3232    if (!recipe) {
    33         psError(PSASTRO_ERR_CONFIG, true, "Can't find PSASTRO recipe!\n");
    34         return false;
     33        psError(PSASTRO_ERR_CONFIG, true, "Can't find PSASTRO recipe!\n");
     34        return false;
    3535    }
    3636
     
    3838    pmFPAfile *output = psMetadataLookupPtr (NULL, config->files, "PSASTRO.OUTPUT");
    3939    if (!output) {
    40         psError(PSASTRO_ERR_CONFIG, true, "Can't find or interpret output file rule PSASTRO.OUTPUT!\n");
    41         return false;
     40        psError(PSASTRO_ERR_CONFIG, true, "Can't find or interpret output file rule PSASTRO.OUTPUT!\n");
     41        return false;
    4242    }
    4343
     
    4848
    4949    pmFPAview *view = pmFPAviewAlloc (0);
     50    pmHDU *lastHDU = NULL;              // Last HDU updated
    5051
    5152    // open/load files as needed
     
    5556        psTrace ("psastro", 4, "Chip %d: %x %x\n", view->chip, chip->file_exists, chip->process);
    5657        if (!chip->process || !chip->file_exists) { continue; }
    57         if (!pmFPAfileIOChecks (config, view, PM_FPA_BEFORE)) ESCAPE;
     58        if (!pmFPAfileIOChecks (config, view, PM_FPA_BEFORE)) ESCAPE;
    5859
    59         while ((cell = pmFPAviewNextCell (view, output->fpa, 1)) != NULL) {
     60        while ((cell = pmFPAviewNextCell (view, output->fpa, 1)) != NULL) {
    6061            psTrace ("psastro", 4, "Cell %d: %x %x\n", view->cell, cell->file_exists, cell->process);
    6162            if (!cell->process || !cell->file_exists) { continue; }
    62             if (!pmFPAfileIOChecks (config, view, PM_FPA_BEFORE)) ESCAPE;
     63            if (!pmFPAfileIOChecks (config, view, PM_FPA_BEFORE)) ESCAPE;
    6364
    64             // process each of the readouts
    65             while ((readout = pmFPAviewNextReadout (view, output->fpa, 1)) != NULL) {
    66                 if (!pmFPAfileIOChecks (config, view, PM_FPA_BEFORE)) ESCAPE;
    67                 if (!readout->data_exists) { continue; }
     65            // process each of the readouts
     66            while ((readout = pmFPAviewNextReadout (view, output->fpa, 1)) != NULL) {
     67                if (!pmFPAfileIOChecks (config, view, PM_FPA_BEFORE)) ESCAPE;
     68                if (!readout->data_exists) { continue; }
    6869
    69                 if (!pmFPAfileIOChecks (config, view, PM_FPA_AFTER)) ESCAPE;
    70             }
    71             if (!pmFPAfileIOChecks (config, view, PM_FPA_AFTER)) ESCAPE;
    72         }
    73         if (!pmFPAfileIOChecks (config, view, PM_FPA_AFTER)) ESCAPE;
     70                // Put version information into the header
     71                pmHDU *hdu = pmHDUGetHighest(output->fpa, chip, cell);
     72                if (hdu && hdu != lastHDU) {
     73                    psastroVersionHeaderFull(hdu->header);
     74                    lastHDU = hdu;
     75                }
     76
     77                if (!pmFPAfileIOChecks (config, view, PM_FPA_AFTER)) ESCAPE;
     78            }
     79            if (!pmFPAfileIOChecks (config, view, PM_FPA_AFTER)) ESCAPE;
     80        }
     81        if (!pmFPAfileIOChecks (config, view, PM_FPA_AFTER)) ESCAPE;
    7482    }
    7583    if (!pmFPAfileIOChecks (config, view, PM_FPA_AFTER)) ESCAPE;
  • branches/cnb_branches/cnb_branch_20090301/psastro/src/psastroVersion.c

    r21409 r23352  
    55 *  @ingroup libpsastro
    66 *
    7  *  @author IfA
    8  *  @version $Revision: 1.3 $ $Name: not supported by cvs2svn $
    9  *  @date $Date: 2009-02-07 02:03:34 $
    107 *  Copyright 2009 Institute for Astronomy, University of Hawaii
    118 */
     
    1310#include "psastroInternal.h"
    1411
    15 static const char *cvsTag = "$Name: not supported by cvs2svn $";///< CVS tag name
     12#ifndef PSASTRO_VERSION
     13#error "PSASTRO_VERSION is not set"
     14#endif
     15#ifndef PSASTRO_BRANCH
     16#error "PSASTRO_BRANCH is not set"
     17#endif
     18#ifndef PSASTRO_SOURCE
     19#error "PSASTRO_SOURCE is not set"
     20#endif
     21
     22#define xstr(s) str(s)
     23#define str(s) #s
    1624
    1725psString psastroVersion(void)
    1826{
    19     psString version = NULL;            // Version, to return
    20     psStringAppend(&version, "%s-%s",PACKAGE_NAME,PACKAGE_VERSION);
    21     return version;
     27    char *value = NULL;
     28    psStringAppend(&value, "%s@%s", xstr(PSASTRO_BRANCH), xstr(PSASTRO_VERSION));
     29    return value;
     30}
     31
     32psString psastroSource(void)
     33{
     34  return psStringCopy(xstr(PSASTRO_SOURCE));
    2235}
    2336
    2437psString psastroVersionLong(void)
    2538{
    26     psString version = psastroVersion(); // Version, to return
    27     psString tag = psStringStripCVS(cvsTag, "Name"); // CVS tag
    28     psStringAppend(&version, " (cvs tag %s) %s, %s", tag, __DATE__, __TIME__);
    29     psFree(tag);
     39    psString version = psastroVersion();  // Version, to return
     40    psString source = psastroSource();    // Source
     41
     42    psStringPrepend(&version, "psastro ");
     43    psStringAppend(&version, " from %s, built %s, %s", source, __DATE__, __TIME__);
     44    psFree(source);
     45
     46#ifdef __OPTIMIZE__
     47    psStringAppend(&version, " optimised");
     48#else
     49    psStringAppend(&version, " unoptimised");
     50#endif
     51
    3052    return version;
     53};
     54
     55bool psastroVersionHeader(psMetadata *header)
     56{
     57    PS_ASSERT_METADATA_NON_NULL(header, false);
     58
     59    psString version = psastroVersion(); // Software version
     60    psString source = psastroSource();   // Software source
     61
     62    psStringPrepend(&version, "psastro version: ");
     63    psStringPrepend(&source, "psastro source: ");
     64
     65    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, version);
     66    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, source);
     67
     68    psFree(version);
     69    psFree(source);
     70
     71    return true;
    3172}
    3273
     74bool psastroVersionHeaderFull(psMetadata *header)
     75{
     76    PS_ASSERT_METADATA_NON_NULL(header, false);
     77
     78    psTime *time = psTimeGetNow(PS_TIME_TAI); // The time now
     79    psString timeString = psTimeToISO(time); // The time in an ISO string
     80    psFree(time);
     81    psString history = NULL;               // History string
     82    psStringAppend(&history, "psastro at %s", timeString);
     83    psFree(timeString);
     84    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, history);
     85    psFree(history);
     86
     87    psLibVersionHeader(header);
     88    psModulesVersionHeader(header);
     89    ppStatsVersionHeader(header);
     90    psastroVersionHeader(header);
     91
     92    return true;
     93}
     94
     95void psastroVersionPrint(void)
     96{
     97    psTime *time = psTimeGetNow(PS_TIME_TAI); // The time now
     98    psString timeString = psTimeToISO(time); // The time in an ISO string
     99    psFree(time);
     100    psLogMsg("psastro", PS_LOG_INFO, "psastro at %s", timeString);
     101    psFree(timeString);
     102
     103    psString pslib = psLibVersionLong();// psLib version
     104    psString psmodules = psModulesVersionLong(); // psModules version
     105    psString ppStats = ppStatsVersionLong(); // ppStats version
     106    psString psastro = psastroVersionLong(); // psastro version
     107
     108    psLogMsg("psastro", PS_LOG_INFO, "%s", pslib);
     109    psLogMsg("psastro", PS_LOG_INFO, "%s", psmodules);
     110    psLogMsg("psastro", PS_LOG_INFO, "%s", ppStats);
     111    psLogMsg("psastro", PS_LOG_INFO, "%s", psastro);
     112
     113    psFree(pslib);
     114    psFree(psmodules);
     115    psFree(ppStats);
     116    psFree(psastro);
     117
     118    return;
     119}
  • branches/cnb_branches/cnb_branch_20090301/psconfig/psbuild

    r22697 r23352  
    1313$stop = "";
    1414$verbose = 0;
     15$use_svn = 1;
    1516
    1617$extlibs = "none";
     
    8384    if ($ARGV[0] eq "-bootstrap") {
    8485        &bootstrap ();
     86    }
     87    if ($ARGV[0] eq "-skip-svn") {
     88        $use_svn = 0;
     89        shift; next;
    8590    }
    8691    if ($ARGV[0] eq "-env") {
     
    157162sub build_distribution {
    158163
     164    # set environment variables used to supply SVN info to the compilation
     165
     166    if ($use_svn) {
     167        # example dump from svn info:
     168        # pikake: svn info
     169        # Path: .
     170        # URL: https://svn.pan-starrs.ifa.hawaii.edu/repo/ipp/branches/eam_branches/eam_branch_20090303/ppImage
     171        # Repository Root: https://svn.pan-starrs.ifa.hawaii.edu/repo/ipp
     172        # Repository UUID: 60eb6cdc-a59c-4636-a4e0-dba66a9721fd
     173        # Revision: 23158
     174        # Node Kind: directory
     175        # Schedule: normal
     176        # Last Changed Author: price
     177        # Last Changed Rev: 23125
     178        # Last Changed Date: 2009-03-03 15:41:16 -1000 (Tue, 03 Mar 2009)
     179       
     180        $svn_version = `svnversion`; chomp $svn_version;
     181        @svn_info = `svn info`;
     182
     183        # get the svn_root first:
     184        foreach $line (@svn_info) {
     185            if ($line =~ m|^Repository Root:|) {
     186                ($svn_root) = $line =~ m|^Repository Root:\s*(\S*)|;
     187                last;
     188            }
     189        }
     190
     191        # now get the branch and UUID values
     192        foreach $line (@svn_info) {
     193            if ($line =~ m|^URL:|) {
     194                ($svn_branch) = $line =~ m|^URL:\s*$svn_root/*(\S*)|;
     195            }
     196            if ($line =~ m|^Repository UUID:|) {
     197                ($svn_source) = $line =~ m|^Repository UUID:\s*(\S*)|;
     198            }
     199        }
     200       
     201        $ENV{SVN_VERSION} = $svn_version;
     202        $ENV{SVN_BRANCH}  = $svn_branch;
     203        $ENV{SVN_SOURCE}  = $svn_source;
     204    } else {
     205        # alternatively, grab these from the following files:
     206        if (! -e "SVNINFO") {
     207            print "missing SVNINFO file for repository info, skipping\n";
     208        } else {
     209            @svn_info = `cat SVNINFO`;
     210            foreach $line (@svn_info) {
     211                ($name, $value) = split (" ", $line);
     212                $ENV{$name} = $value;
     213            }
     214        }
     215    }
     216    print "SVN_VERSION $ENV{SVN_VERSION}\n";
     217    print "SVN_BRANCH  $ENV{SVN_BRANCH}\n";
     218    print "SVN_SOURCE  $ENV{SVN_SOURCE}\n";
     219
    159220    # use psconfig.csh to set needed build aliases
    160 
    161221    if ($extlibs eq "check") {
    162222        $status = vsystem ("pschecklibs");
     
    247307
    248308        if (-e "Build.PL") {
    249             vsystem ("$psperlbuild");
    250             if ($?) { &failure($module[$i], "failure in perl Build.PL"); }
    251 
    252             vsystem ("./Build");
    253             if ($?) { &failure($module[$i], "failure in Build"); }
    254 
    255             vsystem ("./Build install");
    256             if ($?) { &failure($module[$i], "failure in Build install"); }
     309            $status = vsystem ("$psperlbuild");
     310            if ($status) { &failure($module[$i], "failure in perl Build.PL"); }
     311
     312            $status = vsystem ("./Build");
     313            if ($status) { &failure($module[$i], "failure in Build"); }
     314
     315            $status = vsystem ("./Build install");
     316            if ($status) { &failure($module[$i], "failure in Build install"); }
    257317
    258318            next;
     
    272332        if ($developer && $rebuild_this && ! -e "configure" && -e "autogen.sh") {
    273333            $skip_configure = 1;
    274             vsystem ("$psautogen $psopts");
    275             if ($?) { &failure($module[$i], "failure in psautogen"); }
     334            $status = vsystem ("$psautogen $psopts");
     335            if ($status) { &failure($module[$i], "failure in psautogen"); }
    276336        }
    277337
    278338        if ($rebuild_this && -e "configure" && !$skip_configure) {
    279             vsystem ("$psconfigure $psopts");
    280             if ($?) { &failure($module[$i], "failure in psconfigure"); }
     339            $status = vsystem ("$psconfigure $psopts");
     340            if ($status) { &failure($module[$i], "failure in psconfigure"); }
    281341        }
    282342
     
    288348
    289349        if ($clean) {
    290             vsystem ("$make clean");
    291             if ($?) { &failure($module[$i], "failure in make clean"); }
     350            $status = vsystem ("$make clean");
     351            if ($status) { &failure($module[$i], "failure in make clean"); }
    292352        }
    293353
    294         vsystem ("$make");
    295         if ($?) { &failure($module[$i], "failure in make"); }
    296 
    297         vsystem ("$make install");
    298         if ($?) { &failure($module[$i], "failure in make install"); }
     354        $status = vsystem ("$make");
     355        if ($status) { &failure($module[$i], "failure in make"); }
     356
     357        $status = vsystem ("$make install");
     358        if ($status) { &failure($module[$i], "failure in make install"); }
    299359
    300360        print "*** done with $module[$i] ***\n";
  • branches/cnb_branches/cnb_branch_20090301/psconfig/pschecklibs

    r22721 r23352  
    487487
    488488sub usage {
    489     print STDERR "USAGE: pscheckperl [-version] [-build]\n";
     489    print STDERR "USAGE: pschecklibs [-version] [-build]\n";
    490490    exit 2;
    491491}
  • branches/cnb_branches/cnb_branch_20090301/psphot

  • branches/cnb_branches/cnb_branch_20090301/psphot/src/Makefile.am

    r21392 r23352  
    11lib_LTLIBRARIES = libpsphot.la
    2 libpsphot_la_CFLAGS = $(PSPHOT_CFLAGS) $(PSMODULE_CFLAGS) $(PSLIB_CFLAGS)
     2
     3# PSPHOT_VERSION=`if [ -e ../../VERSION ]; then cat ../../VERSION; else svnversion; fi`
     4# PSPHOT_BRANCH=`if [ -e ../../BRANCH ]; then cat ../../BRANCH; else svn info | sed -n -e '/URL:/ h' -e '/Repository Root:/ { x; H; x; s|Repository Root: \(.*\)\nURL: \1\(.*\)|\2| ; s|^/|| ; s|/[a-zA-Z]*/src.*|| ; p }'; fi`
     5# PSPHOT_SOURCE=`if [ -e ../../SOURCE ]; then cat ../../SOURCE; else svn info | sed -n -e 's/Repository UUID: // p'; fi`
     6#
     7# # Force recompilation of psphotVersion.c, since it gets the version information
     8# psphotVersion.c: FORCE
     9#       touch psphotVersion.c
     10# FORCE: ;
     11
     12libpsphot_la_CFLAGS = $(PSPHOT_CFLAGS) $(PSMODULE_CFLAGS) $(PSLIB_CFLAGS) -DPSPHOT_VERSION=$(PSPHOT_VERSION) -DPSPHOT_BRANCH=$(PSPHOT_BRANCH) -DPSPHOT_SOURCE=$(SVN_SOURCE)
    313libpsphot_la_LDFLAGS = $(PSPHOT_LIBS) $(PSMODULE_LIBS) $(PSLIB_LIBS)
    414
  • branches/cnb_branches/cnb_branch_20090301/psphot/src/psphot.c

    r20411 r23352  
    99
    1010    psTimerStart ("complete");
    11     pmErrorRegister();                  // register psModule's error codes/messages
     11    pmErrorRegister();                  // register psModule's error codes/messages
    1212    psphotInit();
    1313
     
    1515    pmConfig *config = psphotArguments (argc, argv);
    1616    if (!config) {
    17         psErrorStackPrint(stderr, "Error reading arguments\n");
    18         usage ();
     17        psErrorStackPrint(stderr, "Error reading arguments\n");
     18        usage ();
    1919    }
     20
     21    psphotVersionPrint();
    2022
    2123    // load input data (config and images (signal, noise, mask)
  • branches/cnb_branches/cnb_branch_20090301/psphot/src/psphot.h

    r21392 r23352  
    1616const char     *psphotCVSName(void);
    1717psString        psphotVersion(void);
     18psString        psphotSource(void);
    1819psString        psphotVersionLong(void);
     20bool            psphotVersionHeader(psMetadata *header);
     21bool            psphotVersionHeaderFull(psMetadata *header);
     22void            psphotVersionPrint(void);
    1923
    2024bool            psphotModelTest (pmConfig *config, const pmFPAview *view, psMetadata *recipe);
     
    167171
    168172// psphotVisual functions
    169 bool psphotSetVisual (bool mode);
    170173bool psphotVisualShowImage (pmReadout *readout);
    171174bool psphotVisualShowBackground (pmConfig *config, const pmFPAview *view, pmReadout *readout);
  • branches/cnb_branches/cnb_branch_20090301/psphot/src/psphotArguments.c

    r21458 r23352  
    8282    if ((N = psArgumentGet (argc, argv, "-visual"))) {
    8383        psArgumentRemove (N, &argc, argv);
    84         psphotSetVisual (true);
    85         // pmSourceSetVisual (true);
     84        pmVisualSetVisual(true);
    8685    }
    8786
  • branches/cnb_branches/cnb_branch_20090301/psphot/src/psphotImageLoop.c

    r21458 r23352  
    2626
    2727    pmFPAview *view = pmFPAviewAlloc (0);
     28    pmHDU *lastHDU = NULL;              // Last HDU updated
    2829
    2930    // files associated with the science image
     
    6465                psLogMsg ("psphot", 6, "Cell %d: %x %x\n", view->cell, cell->file_exists, cell->process);
    6566                if (! readout->data_exists) { continue; }
     67
     68                // Update the header
     69                {
     70                    pmHDU *hdu = pmHDUGetHighest(input->fpa, chip, cell);
     71                    if (hdu && hdu != lastHDU) {
     72                        psphotVersionHeaderFull(hdu->header);
     73                        lastHDU = hdu;
     74                    }
     75                }
    6676
    6777                // run the actual photometry analysis on this chip/cell/readout
  • branches/cnb_branches/cnb_branch_20090301/psphot/src/psphotMagnitudes.c

    r21519 r23352  
    1515    int nThreads = psMetadataLookupS32(&status, config->arguments, "NTHREADS"); // Number of threads
    1616    if (!status) {
    17         nThreads = 0;
     17        nThreads = 0;
    1818    }
    1919
     
    3636
    3737    // the binning details are saved on the analysis metadata
    38     psImageBinning *binning = psMetadataLookupPtr(&status, recipe, "PSPHOT.BACKGROUND.BINNING");
     38    psImageBinning *binning = NULL;
     39    if (backModel) {
     40        binning = psMetadataLookupPtr(&status, backModel->analysis, "PSPHOT.BACKGROUND.BINNING");
     41    }
    3942
    4043    bool IGNORE_GROWTH = psMetadataLookupBool (&status, recipe, "IGNORE_GROWTH");
     
    5356    for (int i = 0; i < cellGroups->n; i++) {
    5457
    55         psArray *cells = cellGroups->data[i];
    56 
    57         for (int j = 0; j < cells->n; j++) {
    58 
    59             // allocate a job -- if threads are not defined, this just runs the job
    60             psThreadJob *job = psThreadJobAlloc ("PSPHOT_MAGNITUDES");
    61 
    62             psArrayAdd(job->args, 1, cells->data[j]); // sources
    63             psArrayAdd(job->args, 1, psf);
    64             psArrayAdd(job->args, 1, binning);
    65             psArrayAdd(job->args, 1, backModel);
    66             psArrayAdd(job->args, 1, backStdev);
    67 
    68             PS_ARRAY_ADD_SCALAR(job->args, photMode, PS_TYPE_S32);
    69             PS_ARRAY_ADD_SCALAR(job->args, maskVal,  PS_TYPE_IMAGE_MASK);
    70             PS_ARRAY_ADD_SCALAR(job->args, 0,        PS_TYPE_S32); // this is used as a return value for nAp
    71 
    72             if (!psThreadJobAddPending(job)) {
    73                 psError(PS_ERR_UNKNOWN, false, "Unable to guess model.");
    74                 psFree (job);
    75                 return false;
    76             }
    77             psFree(job);
     58        psArray *cells = cellGroups->data[i];
     59
     60        for (int j = 0; j < cells->n; j++) {
     61
     62            // allocate a job -- if threads are not defined, this just runs the job
     63            psThreadJob *job = psThreadJobAlloc ("PSPHOT_MAGNITUDES");
     64
     65            psArrayAdd(job->args, 1, cells->data[j]); // sources
     66            psArrayAdd(job->args, 1, psf);
     67            psArrayAdd(job->args, 1, binning);
     68            psArrayAdd(job->args, 1, backModel);
     69            psArrayAdd(job->args, 1, backStdev);
     70
     71            PS_ARRAY_ADD_SCALAR(job->args, photMode, PS_TYPE_S32);
     72            PS_ARRAY_ADD_SCALAR(job->args, maskVal,  PS_TYPE_IMAGE_MASK);
     73            PS_ARRAY_ADD_SCALAR(job->args, 0,        PS_TYPE_S32); // this is used as a return value for nAp
     74
     75            if (!psThreadJobAddPending(job)) {
     76                psError(PS_ERR_UNKNOWN, false, "Unable to guess model.");
     77                psFree (job);
     78                return false;
     79            }
     80            psFree(job);
    7881
    7982# if (0)
    80                 int nap = 0;
    81                 if (!psphotMagnitudes_Unthreaded (&nap, cells->data[j], psf, binning, backModel, backStdev, photMode, maskVal)) {
    82                     psError(PS_ERR_UNKNOWN, false, "Unable to guess model.");
    83                     return false;
    84                 }
    85                 Nap += nap;
     83                int nap = 0;
     84                if (!psphotMagnitudes_Unthreaded (&nap, cells->data[j], psf, binning, backModel, backStdev, photMode, maskVal)) {
     85                    psError(PS_ERR_UNKNOWN, false, "Unable to guess model.");
     86                    return false;
     87                }
     88                Nap += nap;
    8689# endif
    87         }
    88 
    89         // wait for the threads to finish and manage results
    90         if (!psThreadPoolWait (false)) {
    91             psError(PS_ERR_UNKNOWN, false, "Unable to guess model.");
    92             return false;
    93         }
    94 
    95         // we have only supplied one type of job, so we can assume the types here
    96         psThreadJob *job = NULL;
    97         while ((job = psThreadJobGetDone()) != NULL) {
    98             if (job->args->n < 1) {
    99                 fprintf (stderr, "error with job\n");
    100             } else {
    101                 psScalar *scalar = job->args->data[7];
    102                 Nap += scalar->data.S32;
    103             }
    104             psFree(job);
    105         }
     90        }
     91
     92        // wait for the threads to finish and manage results
     93        if (!psThreadPoolWait (false)) {
     94            psError(PS_ERR_UNKNOWN, false, "Unable to guess model.");
     95            return false;
     96        }
     97
     98        // we have only supplied one type of job, so we can assume the types here
     99        psThreadJob *job = NULL;
     100        while ((job = psThreadJobGetDone()) != NULL) {
     101            if (job->args->n < 1) {
     102                fprintf (stderr, "error with job\n");
     103            } else {
     104                psScalar *scalar = job->args->data[7];
     105                Nap += scalar->data.S32;
     106            }
     107            psFree(job);
     108        }
    106109    }
    107110
     
    130133        if (status && isfinite(source->apMag)) Nap ++;
    131134
    132         if (backModel) {
    133             psAssert (binning, "if backModel is defined, so should binning be");
    134             source->sky = psImageUnbinPixel(source->peak->x, source->peak->y, backModel->image, binning);
    135             if (isnan(source->sky) && false) {
    136                 psLogMsg ("psphot.magnitudes", PS_LOG_DETAIL, "error setting pmSource.sky");
    137             }
    138         } else {
    139             source->sky = NAN;
    140         }
    141 
    142         if (backStdev) {
    143             psAssert (binning, "if backStdev is defined, so should binning be");
    144             source->skyErr = psImageUnbinPixel(source->peak->x, source->peak->y, backStdev->image, binning);
    145             if (isnan(source->skyErr) && false) {
    146                 psLogMsg ("psphot.magnitudes", PS_LOG_DETAIL, "error setting pmSource.skyErr");
    147             }
    148         } else {
    149             source->skyErr = NAN;
    150         }
     135        if (backModel) {
     136            psAssert (binning, "if backModel is defined, so should binning be");
     137            source->sky = psImageUnbinPixel(source->peak->x, source->peak->y, backModel->image, binning);
     138            if (isnan(source->sky) && false) {
     139                psLogMsg ("psphot.magnitudes", PS_LOG_DETAIL, "error setting pmSource.sky");
     140            }
     141        } else {
     142            source->sky = NAN;
     143        }
     144
     145        if (backStdev) {
     146            psAssert (binning, "if backStdev is defined, so should binning be");
     147            source->skyErr = psImageUnbinPixel(source->peak->x, source->peak->y, backStdev->image, binning);
     148            if (isnan(source->skyErr) && false) {
     149                psLogMsg ("psphot.magnitudes", PS_LOG_DETAIL, "error setting pmSource.skyErr");
     150            }
     151        } else {
     152            source->skyErr = NAN;
     153        }
    151154    }
    152155
     
    169172        if (status && isfinite(source->apMag)) Nap ++;
    170173
    171         if (backModel) {
    172             psAssert (binning, "if backModel is defined, so should binning be");
    173             source->sky = psImageUnbinPixel(source->peak->x, source->peak->y, backModel->image, binning);
    174             if (isnan(source->sky) && false) {
    175                 psLogMsg ("psphot.magnitudes", PS_LOG_DETAIL, "error setting pmSource.sky");
    176             }
    177         } else {
    178             source->sky = NAN;
    179         }
    180 
    181         if (backStdev) {
    182             psAssert (binning, "if backStdev is defined, so should binning be");
    183             source->skyErr = psImageUnbinPixel(source->peak->x, source->peak->y, backStdev->image, binning);
    184             if (isnan(source->skyErr) && false) {
    185                 psLogMsg ("psphot.magnitudes", PS_LOG_DETAIL, "error setting pmSource.skyErr");
    186             }
    187         } else {
    188             source->skyErr = NAN;
    189         }
     174        if (backModel) {
     175            psAssert (binning, "if backModel is defined, so should binning be");
     176            source->sky = psImageUnbinPixel(source->peak->x, source->peak->y, backModel->image, binning);
     177            if (isnan(source->sky) && false) {
     178                psLogMsg ("psphot.magnitudes", PS_LOG_DETAIL, "error setting pmSource.sky");
     179            }
     180        } else {
     181            source->sky = NAN;
     182        }
     183
     184        if (backStdev) {
     185            psAssert (binning, "if backStdev is defined, so should binning be");
     186            source->skyErr = psImageUnbinPixel(source->peak->x, source->peak->y, backStdev->image, binning);
     187            if (isnan(source->skyErr) && false) {
     188                psLogMsg ("psphot.magnitudes", PS_LOG_DETAIL, "error setting pmSource.skyErr");
     189            }
     190        } else {
     191            source->skyErr = NAN;
     192        }
    190193    }
    191194
     
    210213    int nThreads = psMetadataLookupS32(&status, config->arguments, "NTHREADS"); // Number of threads
    211214    if (!status) {
    212         nThreads = 0;
     215        nThreads = 0;
    213216    }
    214217    nThreads = 0; // XXX until testing is complete, do not thread this function
     
    233236    for (int i = 0; i < cellGroups->n; i++) {
    234237
    235         psArray *cells = cellGroups->data[i];
    236 
    237         for (int j = 0; j < cells->n; j++) {
    238 
    239             // allocate a job -- if threads are not defined, this just runs the job
    240             psThreadJob *job = psThreadJobAlloc ("PSPHOT_PSF_WEIGHTS");
    241 
    242             psArrayAdd(job->args, 1, cells->data[j]); // sources
    243             PS_ARRAY_ADD_SCALAR(job->args, maskVal,  PS_TYPE_IMAGE_MASK);
    244 
    245             if (!psThreadJobAddPending(job)) {
    246                 psError(PS_ERR_UNKNOWN, false, "Unable to guess model.");
    247                 psFree (job);
    248                 return false;
    249             }
    250             psFree(job);
    251 
    252         }
    253 
    254         // wait for the threads to finish and manage results
    255         if (!psThreadPoolWait (false)) {
    256             psError(PS_ERR_UNKNOWN, false, "Unable to guess model.");
    257             return false;
    258         }
    259 
    260         // we have only supplied one type of job, so we can assume the types here
    261         psThreadJob *job = NULL;
    262         while ((job = psThreadJobGetDone()) != NULL) {
    263             if (job->args->n < 1) {
    264                 fprintf (stderr, "error with job\n");
    265             }
    266             psFree(job);
    267         }
     238        psArray *cells = cellGroups->data[i];
     239
     240        for (int j = 0; j < cells->n; j++) {
     241
     242            // allocate a job -- if threads are not defined, this just runs the job
     243            psThreadJob *job = psThreadJobAlloc ("PSPHOT_PSF_WEIGHTS");
     244
     245            psArrayAdd(job->args, 1, cells->data[j]); // sources
     246            PS_ARRAY_ADD_SCALAR(job->args, maskVal,  PS_TYPE_IMAGE_MASK);
     247
     248            if (!psThreadJobAddPending(job)) {
     249                psError(PS_ERR_UNKNOWN, false, "Unable to guess model.");
     250                psFree (job);
     251                return false;
     252            }
     253            psFree(job);
     254
     255        }
     256
     257        // wait for the threads to finish and manage results
     258        if (!psThreadPoolWait (false)) {
     259            psError(PS_ERR_UNKNOWN, false, "Unable to guess model.");
     260            return false;
     261        }
     262
     263        // we have only supplied one type of job, so we can assume the types here
     264        psThreadJob *job = NULL;
     265        while ((job = psThreadJobGetDone()) != NULL) {
     266            if (job->args->n < 1) {
     267                fprintf (stderr, "error with job\n");
     268            }
     269            psFree(job);
     270        }
    268271    }
    269272
     
    285288        pmSource *source = (pmSource *) sources->data[i];
    286289
    287         // we must have a valid model
    288         pmModel *model = pmSourceGetModel (&isPSF, source);
    289         if (model == NULL) {
    290           psTrace ("psphot", 3, "fail mag : no valid model");
    291           source->pixWeight = NAN;
    292           continue;
    293         }
     290        // we must have a valid model
     291        pmModel *model = pmSourceGetModel (&isPSF, source);
     292        if (model == NULL) {
     293          psTrace ("psphot", 3, "fail mag : no valid model");
     294          source->pixWeight = NAN;
     295          continue;
     296        }
    294297
    295298        status = pmSourcePixelWeight (&source->pixWeight, model, source->maskObj, maskVal);
    296         if (!status) {
    297           psTrace ("psphot", 3, "fail to measure pixel weight");
    298           source->pixWeight = NAN;
    299           continue;
    300         }
    301 
    302     }
    303 
    304     return true;
    305 }
     299        if (!status) {
     300          psTrace ("psphot", 3, "fail to measure pixel weight");
     301          source->pixWeight = NAN;
     302          continue;
     303        }
     304
     305    }
     306
     307    return true;
     308}
  • branches/cnb_branches/cnb_branch_20090301/psphot/src/psphotMaskReadout.c

    r21366 r23352  
    2929    }
    3030
     31    // make this an option via the recipe
     32    if (0) {
     33      psImage *im = readout->image;
     34      psImage *wt = readout->variance;
     35      psImage *mk = readout->mask;
     36      for (int j = 0; j < im->numRows; j++) {
     37        for (int i = 0; i < im->numCols; i++) {
     38          if (isfinite(im->data.F32[j][i]) && isfinite(wt->data.F32[j][i])) continue;
     39          mk->data.PS_TYPE_IMAGE_MASK_DATA[j][i] |= maskBad;
     40        }
     41      }
     42    }
     43
    3144    // mask the excluded outer pixels
    3245    // these coordinates refer to the parent image
  • branches/cnb_branches/cnb_branch_20090301/psphot/src/psphotModelBackground.c

    r21183 r23352  
    3131static bool backgroundModel(psImage *model,  // Model image
    3232                            psImage *modelStdev, // Model stdev image
    33                             psImage *image, // Image for which to generate a background model
    34                             psImage *mask, // Mask for image
     33                            psMetadata *analysis, // Analysis metadata for outputs
     34                            pmReadout *readout, // Readout for which to generate a background model
    3535                            psImageBinning *binning, // Binning parameters
    3636                            const pmConfig *config // Configuration
     
    4141    bool status = true;
    4242
     43    psImage *image = readout->image, *mask = readout->mask; // Image and mask for readout
     44
    4345    // select the appropriate recipe information
    4446    psMetadata *recipe  = psMetadataLookupPtr (&status, config->recipes, PSPHOT_RECIPE);
     
    4951    assert (maskVal);
    5052
    51     // user supplied seed, if available
    52     unsigned long seed = psMetadataLookupS32 (&status, recipe, "IMSTATS_SEED");
    53     if (!status) {
    54         seed = 0;
    55     }
    56     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, seed);
     53    psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS);
    5754
    5855    // subtract this amount extra from the sky
     
    140137
    141138    // we save the binning structure for use in psphotMagnitudes
    142     status = psMetadataAddPtr(recipe, PS_LIST_TAIL, "PSPHOT.BACKGROUND.BINNING", PS_DATA_UNKNOWN | PS_META_REPLACE, "Background binning", binning);
    143     PS_ASSERT (status, false);
    144 
     139    psMetadataAddPtr(analysis, PS_LIST_TAIL, "PSPHOT.BACKGROUND.BINNING",
     140                     PS_DATA_UNKNOWN | PS_META_REPLACE, "Background binning", binning);
    145141
    146142    psF32 **modelData = model->data.F32;
     
    343339    psImage *modelStdev = psImageAlloc(binning->nXruff, binning->nYruff, PS_TYPE_F32); // Standard deviation
    344340
    345     if (!backgroundModel(model, modelStdev, ro->image, ro->mask, binning, config)) {
     341    if (!backgroundModel(model, modelStdev, ro->analysis, ro, binning, config)) {
    346342        psFree(model);
    347343        psFree(modelStdev);
     
    365361    pmFPAfile *file = psMetadataLookupPtr (&status, config->files, filename);
    366362    pmFPA *inFPA = file->fpa;
    367     pmReadout *readout = pmFPAviewThisReadout (view, inFPA);
    368     psImage *image = readout->image;
    369     psImage *mask  = readout->mask;
    370 
    371     psImageBinning *binning = backgroundBinning(image, config); // Image binning parameters
     363    pmReadout *readout = pmFPAviewThisReadout(view, inFPA);
     364
     365    psImageBinning *binning = backgroundBinning(readout->image, config); // Image binning parameters
    372366    pmReadout *model = pmFPAGenerateReadout(config, view, "PSPHOT.BACKMDL", inFPA, binning);
    373367    pmReadout *modelStdev = pmFPAGenerateReadout(config, view, "PSPHOT.BACKMDL.STDEV", inFPA, binning);
    374368
    375     if (!backgroundModel(model->image, modelStdev->image, image, mask, binning, config)) {
     369    if (!backgroundModel(model->image, modelStdev->image, model->analysis, readout, binning, config)) {
    376370        psError(PS_ERR_UNKNOWN, false, "Unable to generate background model");
    377371        return false;
  • branches/cnb_branches/cnb_branch_20090301/psphot/src/psphotSetThreads.c

    r21392 r23352  
    2525    psFree(task);
    2626
    27     task = psThreadTaskAlloc("PSPHOT_SOURCE_STATS", 4);
     27    task = psThreadTaskAlloc("PSPHOT_SOURCE_STATS", 5);
    2828    task->function = &psphotSourceStats_Threaded;
    2929    psThreadTaskAdd(task);
  • branches/cnb_branches/cnb_branch_20090301/psphot/src/psphotSourceStats.c

    r21519 r23352  
    1515    int nThreads = psMetadataLookupS32(&status, config->arguments, "NTHREADS"); // Number of threads
    1616    if (!status) {
    17         nThreads = 0;
     17        nThreads = 0;
    1818    }
    1919
     
    4141        pmSource *source = pmSourceAlloc();
    4242
    43         // add the peak
     43        // add the peak
    4444        source->peak = psMemIncrRefCounter(peak);
    4545
    46         // allocate space for moments
     46        // allocate space for moments
    4747        source->moments = pmMomentsAlloc();
    4848
     
    5050        pmSourceDefinePixels (source, readout, source->peak->x, source->peak->y, OUTER);
    5151
    52         peak->assigned = true;
    53         psArrayAdd (sources, 100, source);
    54         psFree (source);
     52        peak->assigned = true;
     53        psArrayAdd (sources, 100, source);
     54        psFree (source);
    5555    }
    5656
    5757    if (!strcasecmp (breakPt, "PEAKS")) {
    58         psLogMsg ("psphot", PS_LOG_INFO, "%ld sources : %f sec\n", sources->n, psTimerMark ("psphot.stats"));
    59         psLogMsg ("psphot", PS_LOG_INFO, "break point PEAKS, skipping MOMENTS\n");
    60         psphotVisualShowMoments (sources);
    61         return sources;
     58        psLogMsg ("psphot", PS_LOG_INFO, "%ld sources : %f sec\n", sources->n, psTimerMark ("psphot.stats"));
     59        psLogMsg ("psphot", PS_LOG_INFO, "break point PEAKS, skipping MOMENTS\n");
     60        psphotVisualShowMoments (sources);
     61        return sources;
    6262    }
    6363
     
    6565    int Nfail = 0;
    6666    int Nmoments = 0;
     67    int Nfaint = 0;
    6768
    6869    // choose Cx, Cy (see psphotThreadTools.c for overview of the concepts)
     
    7475    for (int i = 0; i < cellGroups->n; i++) {
    7576
    76         psArray *cells = cellGroups->data[i];
    77 
    78         for (int j = 0; j < cells->n; j++) {
    79 
    80             // allocate a job -- if threads are not defined, this just runs the job
    81             psThreadJob *job = psThreadJobAlloc ("PSPHOT_SOURCE_STATS");
    82 
    83             psArrayAdd(job->args, 1, cells->data[j]); // sources
    84             psArrayAdd(job->args, 1, recipe);
    85             PS_ARRAY_ADD_SCALAR(job->args, 0, PS_TYPE_S32); // this is used as a return value for Nmoments
    86             PS_ARRAY_ADD_SCALAR(job->args, 0, PS_TYPE_S32); // this is used as a return value for Nfail
    87 
    88             if (!psThreadJobAddPending(job)) {
    89                 psError(PS_ERR_UNKNOWN, false, "Unable to guess model.");
    90                 psFree (job);
    91                 return NULL;
    92             }
    93             psFree(job);
     77        psArray *cells = cellGroups->data[i];
     78
     79        for (int j = 0; j < cells->n; j++) {
     80
     81            // allocate a job -- if threads are not defined, this just runs the job
     82            psThreadJob *job = psThreadJobAlloc ("PSPHOT_SOURCE_STATS");
     83
     84            psArrayAdd(job->args, 1, cells->data[j]); // sources
     85            psArrayAdd(job->args, 1, recipe);
     86            PS_ARRAY_ADD_SCALAR(job->args, 0, PS_TYPE_S32); // this is used as a return value for Nmoments
     87            PS_ARRAY_ADD_SCALAR(job->args, 0, PS_TYPE_S32); // this is used as a return value for Nfail
     88            PS_ARRAY_ADD_SCALAR(job->args, 0, PS_TYPE_S32); // this is used as a return value for Nfaint
     89
     90            if (!psThreadJobAddPending(job)) {
     91                psError(PS_ERR_UNKNOWN, false, "Unable to guess model.");
     92                psFree (job);
     93                return NULL;
     94            }
     95            psFree(job);
    9496
    9597# if (0)
    96                 int nfail = 0;
    97                 int nmoments = 0;
    98                 if (!psphotSourceStats_Unthreaded (&nfail, &nmoments, cells->data[j], recipe)) {
    99                     psError(PS_ERR_UNKNOWN, false, "Unable to guess model.");
    100                     return NULL;
    101                 }
    102                 Nfail += nfail;
    103                 Nmoments += nmoments;
     98                int nfail = 0;
     99                int nmoments = 0;
     100                if (!psphotSourceStats_Unthreaded (&nfail, &nmoments, cells->data[j], recipe)) {
     101                    psError(PS_ERR_UNKNOWN, false, "Unable to guess model.");
     102                    return NULL;
     103                }
     104                Nfail += nfail;
     105                Nmoments += nmoments;
    104106# endif
    105         }
    106 
    107         // wait for the threads to finish and manage results
    108         if (!psThreadPoolWait (false)) {
    109             psError(PS_ERR_UNKNOWN, false, "Unable to guess model.");
    110             return NULL;
    111         }
    112 
    113         // we have only supplied one type of job, so we can assume the types here
    114         psThreadJob *job = NULL;
    115         while ((job = psThreadJobGetDone()) != NULL) {
    116             if (job->args->n < 1) {
    117                 fprintf (stderr, "error with job\n");
    118             } else {
    119                 psScalar *scalar = NULL;
    120                 scalar = job->args->data[2];
    121                 Nmoments += scalar->data.S32;
    122                 scalar = job->args->data[3];
    123                 Nfail += scalar->data.S32;
    124             }
    125             psFree(job);
    126         }
     107        }
     108
     109        // wait for the threads to finish and manage results
     110        if (!psThreadPoolWait (false)) {
     111            psError(PS_ERR_UNKNOWN, false, "Unable to guess model.");
     112            return NULL;
     113        }
     114
     115        // we have only supplied one type of job, so we can assume the types here
     116        psThreadJob *job = NULL;
     117        while ((job = psThreadJobGetDone()) != NULL) {
     118            if (job->args->n < 1) {
     119                fprintf (stderr, "error with job\n");
     120            } else {
     121                psScalar *scalar = NULL;
     122                scalar = job->args->data[2];
     123                Nmoments += scalar->data.S32;
     124                scalar = job->args->data[3];
     125                Nfail += scalar->data.S32;
     126                scalar = job->args->data[4];
     127                Nfaint += scalar->data.S32;
     128            }
     129            psFree(job);
     130        }
    127131    }
    128132
    129133    psFree (cellGroups);
    130134
    131     psLogMsg ("psphot", PS_LOG_INFO, "%ld sources, %d moments, %d failed: %f sec\n", sources->n, Nmoments, Nfail, psTimerMark ("psphot.stats"));
     135    psLogMsg ("psphot", PS_LOG_INFO, "%ld sources, %d moments, %d faint, %d failed: %f sec\n", sources->n, Nmoments, Nfaint, Nfail, psTimerMark ("psphot.stats"));
    132136
    133137    psphotVisualShowMoments (sources);
     
    166170    int Nfail = 0;
    167171    int Nmoments = 0;
     172    int Nfaint = 0;
    168173    for (int i = 0; i < sources->n; i++) {
    169174        pmSource *source = sources->data[i];
     
    171176        // skip faint sources for moments measurement
    172177        if (source->peak->SN < MIN_SN) {
    173             source->mode |= PM_SOURCE_MODE_BELOW_MOMENTS_SN;
     178            source->mode |= PM_SOURCE_MODE_BELOW_MOMENTS_SN;
     179            Nfaint++;
    174180            continue;
    175181        }
     
    179185        status = pmSourceLocalSky (source, PS_STAT_SAMPLE_MEDIAN, INNER, maskVal, markVal);
    180186        if (!status) {
    181             source->mode |= PM_SOURCE_MODE_SKY_FAILURE;
    182             psErrorClear(); // XXX re-consider the errors raised here
    183             Nfail ++;
    184             continue;
     187            source->mode |= PM_SOURCE_MODE_SKY_FAILURE;
     188            psErrorClear(); // XXX re-consider the errors raised here
     189            Nfail ++;
     190            continue;
    185191        }
    186192
     
    189195        status = pmSourceLocalSkyVariance (source, PS_STAT_SAMPLE_MEDIAN, INNER, maskVal, markVal);
    190196        if (!status) {
    191             source->mode |= PM_SOURCE_MODE_SKYVAR_FAILURE;
    192             Nfail ++;
    193             psErrorClear();
    194             continue;
     197            source->mode |= PM_SOURCE_MODE_SKYVAR_FAILURE;
     198            Nfail ++;
     199            psErrorClear();
     200            continue;
    195201        }
    196202
     
    208214        status = pmSourceMoments (source, BIG_RADIUS);
    209215        if (status) {
    210             source->mode |= PM_SOURCE_MODE_BIG_RADIUS;
     216            source->mode |= PM_SOURCE_MODE_BIG_RADIUS;
    211217            Nmoments ++;
    212218            continue;
    213219        }
    214220
    215         source->mode |= PM_SOURCE_MODE_MOMENTS_FAILURE;
     221        source->mode |= PM_SOURCE_MODE_MOMENTS_FAILURE;
    216222        Nfail ++;
    217223        psErrorClear();
     
    225231    scalar = job->args->data[3];
    226232    scalar->data.S32 = Nfail;
    227    
     233
     234    scalar = job->args->data[4];
     235    scalar->data.S32 = Nfaint;
     236
    228237    return true;
    229238}
     
    268277        status = pmSourceLocalSky (source, PS_STAT_SAMPLE_MEDIAN, INNER, maskVal, markVal);
    269278        if (!status) {
    270             psErrorClear(); // XXX re-consider the errors raised here
    271             Nfail ++;
    272             continue;
     279            psErrorClear(); // XXX re-consider the errors raised here
     280            Nfail ++;
     281            continue;
    273282        }
    274283
     
    277286        status = pmSourceLocalSkyVariance (source, PS_STAT_SAMPLE_MEDIAN, INNER, maskVal, markVal);
    278287        if (!status) {
    279             Nfail ++;
    280             psErrorClear();
    281             continue;
     288            Nfail ++;
     289            psErrorClear();
     290            continue;
    282291        }
    283292
     
    307316    *nmoments = Nmoments;
    308317    *nfail = Nfail;
    309    
     318
    310319    return true;
    311320}
    312 # endif 
     321# endif
  • branches/cnb_branches/cnb_branch_20090301/psphot/src/psphotSubtractBackground.c

    r21183 r23352  
    44// generate the median in NxN boxes, clipping heavily
    55// linear interpolation to generate full-scale model
    6 bool psphotSubtractBackground (pmConfig *config, const pmFPAview *view, const char *filename) 
     6bool psphotSubtractBackground (pmConfig *config, const pmFPAview *view, const char *filename)
    77{
    88    bool status = true;
     
    3131    assert (maskVal);
    3232
    33     psImageBinning *binning = psMetadataLookupPtr(&status, recipe, "PSPHOT.BACKGROUND.BINNING");
     33    psImageBinning *binning = psMetadataLookupPtr(&status, model->analysis, "PSPHOT.BACKGROUND.BINNING");
    3434    assert (binning);
    3535
  • branches/cnb_branches/cnb_branch_20090301/psphot/src/psphotVersion.c

    r12805 r23352  
    1 # include "psphotInternal.h"
     1#include "psphotInternal.h"
    22
    3 # if (HAVE_KAPA)
    4 # include <kapa.h>
    5 # endif
     3#ifdef HAVE_KAPA
     4#include <kapa.h>
     5#endif
    66
    7 static const char *cvsTag = "$Name: not supported by cvs2svn $";// CVS tag name
     7#ifndef PSPHOT_VERSION
     8#error "PSPHOT_VERSION is not set"
     9#endif
     10#ifndef PSPHOT_BRANCH
     11#error "PSPHOT_BRANCH is not set"
     12#endif
     13#ifndef PSPHOT_SOURCE
     14#error "PSPHOT_SOURCE is not set"
     15#endif
     16
     17#define xstr(s) str(s)
     18#define str(s) #s
    819
    920psString psphotVersion(void)
    1021{
    11     psString version = NULL;            // Version, to return
    12     psStringAppend(&version, "%s-%s",PACKAGE_NAME,PACKAGE_VERSION);
    13     return version;
     22    char *value = NULL;
     23    psStringAppend(&value, "%s@%s", xstr(PSPHOT_BRANCH), xstr(PSPHOT_VERSION));
     24    return value;
     25}
     26
     27psString psphotSource(void)
     28{
     29    return psStringCopy(xstr(PSPHOT_SOURCE));
    1430}
    1531
    1632psString psphotVersionLong(void)
    1733{
    18     psString version = psphotVersion(); // Version, to return
    19     psString tag = psStringStripCVS(cvsTag, "Name"); // CVS tag
    20     psStringAppend(&version, " (cvs tag %s) %s, %s", tag, __DATE__, __TIME__);
     34    psString version = psLibVersion();  // Version, to return
     35    psString source = psLibSource();    // Source
    2136
    22 # if (HAVE_KAPA)
    23     psString ohanaVersion = psStringStripCVS (ohana_version(), "Name");
    24     psString libdvoVersion = psStringStripCVS (libdvo_version(), "Name");
     37    psStringPrepend(&version, "psphot ");
     38    psStringAppend(&version, " from %s, built %s, %s", source, __DATE__, __TIME__);
     39    psFree(source);
    2540
    26     psStringAppend (&version, " with libkapa (ohana %s, libdvo: %s)", ohanaVersion, libdvoVersion);
    27     psFree (ohanaVersion);
    28     psFree (libdvoVersion);
    29 # else
    30     psStringAppend (&version, " WITHOUT libkapa");
    31 # endif
     41#ifdef __OPTIMIZE__
     42    psStringAppend(&version, " optimised");
     43#else
     44    psStringAppend(&version, " unoptimised");
     45#endif
    3246
    33     psFree(tag);
     47#ifdef HAVE_KAPA
     48#if 0
     49    // XXX Need to get ohana and libdvo versions
     50    psString ohanaVersion = psStringStripCVS(ohana_version(), "Name");
     51    psString libdvoVersion = psStringStripCVS(libdvo_version(), "Name");
     52    psStringAppend(&version, " with libkapa (ohana %s, libdvo: %s)", ohanaVersion, libdvoVersion);
     53    psFree(ohanaVersion);
     54    psFree(libdvoVersion);
     55#else
     56    psStringAppend(&version, " with libkapa");
     57#endif
     58
     59#else
     60    psStringAppend (&version, " without libkapa");
     61#endif
     62
    3463    return version;
    3564}
    3665
    37 // Defined by RHL; leaving for backwards compatibility.
    38 const char *psphotCVSName(void) {
    39    return cvsTag;
     66bool psphotVersionHeader(psMetadata *header)
     67{
     68    PS_ASSERT_METADATA_NON_NULL(header, false);
     69
     70    psString version = psphotVersion(); // Software version
     71    psString source = psphotSource();   // Software source
     72
     73    psStringPrepend(&version, "psphot version: ");
     74    psStringPrepend(&source, "psphot source: ");
     75
     76    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, version);
     77    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, source);
     78
     79    psFree(version);
     80    psFree(source);
     81
     82    return true;
    4083}
     84
     85
     86bool psphotVersionHeaderFull(psMetadata *header)
     87{
     88    PS_ASSERT_METADATA_NON_NULL(header, false);
     89
     90    psTime *time = psTimeGetNow(PS_TIME_TAI); // The time now
     91    psString timeString = psTimeToISO(time); // The time in an ISO string
     92    psFree(time);
     93    psString history = NULL;               // History string
     94    psStringAppend(&history, "psphot at %s", timeString);
     95    psFree(timeString);
     96    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, history);
     97    psFree(history);
     98
     99    psLibVersionHeader(header);
     100    psModulesVersionHeader(header);
     101    psphotVersionHeader(header);
     102
     103    return true;
     104}
     105
     106
     107void psphotVersionPrint(void)
     108{
     109    psTime *time = psTimeGetNow(PS_TIME_TAI); // The time now
     110    psString timeString = psTimeToISO(time); // The time in an ISO string
     111    psFree(time);
     112    psLogMsg("psphot", PS_LOG_INFO, "psphot at %s", timeString);
     113    psFree(timeString);
     114
     115    psString pslib = psLibVersionLong();// psLib version
     116    psString psmodules = psModulesVersionLong(); // psModules version
     117    psString psphot = psphotVersionLong(); // psphot version
     118
     119    psLogMsg("psphot", PS_LOG_INFO, "%s", pslib);
     120    psLogMsg("psphot", PS_LOG_INFO, "%s", psmodules);
     121    psLogMsg("psphot", PS_LOG_INFO, "%s", psphot);
     122
     123    psFree(pslib);
     124    psFree(psmodules);
     125    psFree(psphot);
     126
     127    return;
     128}
  • branches/cnb_branches/cnb_branch_20090301/psphot/src/psphotVisual.c

    r21519 r23352  
    1818// these are invoked by the -visual options
    1919
    20 static bool isVisual = false;
    2120static int kapa = -1;
    2221static int kapa2 = -1;
    2322static int kapa3 = -1;
    2423
    25 bool psphotSetVisual (bool mode) {
    26 
    27     isVisual = mode;
    28     return true;
    29 }
    3024
    3125bool psphotVisualShowMask (int kapaFD, psImage *inImage, const char *name, int channel) {
     
    3832
    3933    psStats *stats = psStatsAlloc (PS_STAT_ROBUST_MEDIAN | PS_STAT_ROBUST_STDEV);
    40     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 0);
     34    psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS);
    4135    if (!psImageBackground(stats, NULL, inImage, NULL, 0, rng)) {
    4236        fprintf (stderr, "failed to get background values\n");
     
    8478
    8579    psStats *stats = psStatsAlloc (PS_STAT_ROBUST_MEDIAN | PS_STAT_ROBUST_STDEV);
    86     psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS, 0);
     80    psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS);
    8781    if (!psImageBackground(stats, NULL, inImage, NULL, 0, rng)) {
    8882        fprintf (stderr, "failed to get background values\n");
     
    135129bool psphotVisualShowImage (pmReadout *readout) {
    136130
    137     if (!isVisual) return true;
     131    if (!pmVisualIsVisual()) return true;
    138132
    139133    if (kapa == -1) {
     
    141135        if (kapa == -1) {
    142136            fprintf (stderr, "failure to open kapa; visual mode disabled\n");
    143             isVisual = false;
     137            pmVisualSetVisual(false);
    144138            return false;
    145139        }
     
    164158    pmReadout *backgnd;
    165159
    166     if (!isVisual) return true;
     160    if (!pmVisualIsVisual()) return true;
    167161
    168162    if (kapa == -1) {
     
    170164        if (kapa == -1) {
    171165            fprintf (stderr, "failure to open kapa; visual mode disabled\n");
    172             isVisual = false;
     166            pmVisualSetVisual(false);
    173167            return false;
    174168        }
     
    199193bool psphotVisualShowSignificance (psImage *image) {
    200194
    201     if (!isVisual) return true;
     195    if (!pmVisualIsVisual()) return true;
    202196
    203197    if (kapa == -1) {
     
    205199        if (kapa == -1) {
    206200            fprintf (stderr, "failure to open kapa; visual mode disabled\n");
    207             isVisual = false;
     201            pmVisualSetVisual(false);
    208202            return false;
    209203        }
     
    228222    KiiOverlay *overlay;
    229223
    230     if (!isVisual) return true;
     224    if (!pmVisualIsVisual()) return true;
    231225
    232226    if (kapa == -1) {
     
    306300    KiiOverlay *overlay;
    307301
    308     if (!isVisual) return true;
     302    if (!pmVisualIsVisual()) return true;
    309303
    310304    if (kapa == -1) {
     
    423417    psEllipseAxes axes;
    424418
    425     if (!isVisual) return true;
     419    if (!pmVisualIsVisual()) return true;
    426420
    427421    if (kapa == -1) {
     
    478472    Graphdata graphdata;
    479473
    480     if (!isVisual) return true;
     474    if (!pmVisualIsVisual()) return true;
    481475
    482476    if (kapa3 == -1) {
     
    484478        if (kapa3 == -1) {
    485479            fprintf (stderr, "failure to open kapa; visual mode disabled\n");
    486             isVisual = false;
     480            pmVisualSetVisual(false);
    487481            return false;
    488482        }
     
    694688bool psphotVisualShowRoughClass (psArray *sources) {
    695689
    696     if (!isVisual) return true;
     690    if (!pmVisualIsVisual()) return true;
    697691
    698692    if (kapa == -1) {
     
    723717bool psphotVisualShowPSFModel (pmReadout *readout, pmPSF *psf) {
    724718
    725     if (!isVisual) return true;
     719    if (!pmVisualIsVisual()) return true;
    726720
    727721    if (kapa2 == -1) {
     
    729723        if (kapa2 == -1) {
    730724            fprintf (stderr, "failure to open kapa; visual mode disabled\n");
    731             isVisual = false;
     725            pmVisualSetVisual(false);
    732726            return false;
    733727        }
     
    801795    bool status;
    802796
    803     if (!isVisual) return true;
     797    if (!pmVisualIsVisual()) return true;
    804798
    805799    if (kapa2 == -1) {
     
    807801        if (kapa2 == -1) {
    808802            fprintf (stderr, "failure to open kapa; visual mode disabled\n");
    809             isVisual = false;
     803            pmVisualSetVisual(false);
    810804            return false;
    811805        }
     
    961955    bool status;
    962956
    963     if (!isVisual) return true;
     957    if (!pmVisualIsVisual()) return true;
    964958
    965959    if (kapa2 == -1) {
     
    967961        if (kapa2 == -1) {
    968962            fprintf (stderr, "failure to open kapa; visual mode disabled\n");
    969             isVisual = false;
     963            pmVisualSetVisual(false);
    970964            return false;
    971965        }
     
    12141208    KapaSection section;  // put the positive profile in one and the residuals in another?
    12151209
    1216     if (!isVisual) return true;
     1210    if (!pmVisualIsVisual()) return true;
    12171211
    12181212    if (kapa3 == -1) {
     
    12201214        if (kapa3 == -1) {
    12211215            fprintf (stderr, "failure to open kapa; visual mode disabled\n");
    1222             isVisual = false;
     1216            pmVisualSetVisual(false);
    12231217            return false;
    12241218        }
     
    12861280    psEllipseAxes axes;
    12871281
    1288     if (!isVisual) return true;
     1282    if (!pmVisualIsVisual()) return true;
    12891283
    12901284    if (kapa == -1) {
     
    13871381    KiiOverlay *overlay;
    13881382
    1389     if (!isVisual) return true;
     1383    if (!pmVisualIsVisual()) return true;
    13901384
    13911385    if (kapa == -1) {
     
    14641458    KapaSection section;
    14651459
    1466     if (!isVisual) return true;
     1460    if (!pmVisualIsVisual()) return true;
    14671461
    14681462    if (kapa3 == -1) {
     
    14701464        if (kapa3 == -1) {
    14711465            fprintf (stderr, "failure to open kapa; visual mode disabled\n");
    1472             isVisual = false;
     1466            pmVisualSetVisual(false);
    14731467            return false;
    14741468        }
     
    16041598bool psphotVisualShowResidualImage (pmReadout *readout) {
    16051599
    1606     if (!isVisual) return true;
     1600    if (!pmVisualIsVisual()) return true;
    16071601
    16081602    if (kapa == -1) {
     
    16101604        if (kapa == -1) {
    16111605            fprintf (stderr, "failure to open kapa; visual mode disabled\n");
    1612             isVisual = false;
     1606            pmVisualSetVisual(false);
    16131607            return false;
    16141608        }
     
    16311625    Graphdata graphdata;
    16321626
    1633     if (!isVisual) return true;
     1627    if (!pmVisualIsVisual()) return true;
    16341628
    16351629    if (kapa3 == -1) {
     
    16371631        if (kapa3 == -1) {
    16381632            fprintf (stderr, "failure to open kapa; visual mode disabled\n");
    1639             isVisual = false;
     1633            pmVisualSetVisual(false);
    16401634            return false;
    16411635        }
     
    17121706# else
    17131707
    1714 bool psphotSetVisual (bool mode){}
    17151708bool psphotVisualShowImage (pmConfig *config, pmReadout *readout) { return true; }
    17161709bool psphotVisualShowBackground (pmConfig *config, const pmFPAview *view, pmReadout *readout) { return true; }
  • branches/cnb_branches/cnb_branch_20090301/pstamp/scripts/pstamp_finish.pl

    r21410 r23352  
    2121
    2222use PS::IPP::Config qw( :standard );
    23 use PStamp::RequestFile qw( :standard );
    24 use PStamp::Job qw( :standard );
     23use PS::IPP::PStamp::RequestFile qw( :standard );
     24use PS::IPP::PStamp::Job qw( :standard );
    2525
    2626my ( $req_id, $req_name, $req_file, $out_dir, $product, $dbname, $verbose, $save_temps, $redirect_output);
     
    105105    }
    106106
    107     # this function is PStamp::RequestFile::read_request_file
     107    # this function is PS::IPP::PStamp::RequestFile::read_request_file
    108108    my ($header, $rows) = read_request_file($req_file);
    109109
  • branches/cnb_branches/cnb_branch_20090301/pstamp/scripts/pstamp_job_run.pl

    r21410 r23352  
    1313use File::Basename;
    1414use Digest::MD5::File qw( file_md5_hex );
    15 use PStamp::RequestFile qw( :standard );
     15use PS::IPP::PStamp::RequestFile qw( :standard );
    1616
    1717my $verbose;
  • branches/cnb_branches/cnb_branch_20090301/pstamp/scripts/pstampparse.pl

    r21410 r23352  
    1111use Sys::Hostname;
    1212use Getopt::Long qw( GetOptions );
    13 use PStamp::RequestFile qw( :standard );
    14 use PStamp::Job qw( :standard );
     13use PS::IPP::PStamp::RequestFile qw( :standard );
     14use PS::IPP::PStamp::Job qw( :standard );
    1515
    1616my $verbose;
     
    178178    }
    179179
    180     # Call PStamp::Job's locate_images routine to get the parameters for this request specification
     180    # Call PS::IPP::PStamp::Job's locate_images routine to get the parameters for this request specification
    181181    my $images = locate_images($ipprc, $image_db, $req_type, $img_type, $id, $class_id,
    182182            $x, $y, $mjd_min, $mjd_max, $filter, $verbose);
  • branches/cnb_branches/cnb_branch_20090301/pstamp/test/test_lookup.pl

    r20113 r23352  
    99
    1010use Getopt::Long qw( GetOptions );
    11 use PStamp::Job qw( :standard );
     11use PS::IPP::PStamp::Job qw( :standard );
    1212
    1313use PS::IPP::Config qw( :standard );
  • branches/cnb_branches/cnb_branch_20090301/pstest/src/tst_psPolynomial.c

    r5873 r23352  
    289289            fillVectors(x, f, NORD, NPTS, type[k]);
    290290            psTime *now = psTimeGetNow(PS_TIME_UTC);
    291             const psRandom *r = psRandomAlloc(PS_RANDOM_TAUS, now->sec);
     291            const psRandom *r = psRandomAllocSpecific(PS_RANDOM_TAUS, now->sec);
    292292            for (int i = 0; i < NPTS; i++) {
    293293                double errgen = psRandomGaussian(r);
     
    361361            // add random errors to the vector
    362362            psTime *now = psTimeGetNow(PS_TIME_UTC);
    363             const psRandom *r = psRandomAlloc(PS_RANDOM_TAUS, now->sec);
     363            const psRandom *r = psRandomAllocSpecific(PS_RANDOM_TAUS, now->sec);
    364364            for (int i = 0; i < NPTS; i++) {
    365365                double errgen = psRandomGaussian(r);
     
    464464            fillVectors(x, f, NORD, NPTS, type[k]);
    465465            psTime *now = psTimeGetNow(PS_TIME_UTC);
    466             const psRandom *r = psRandomAlloc(PS_RANDOM_TAUS, now->sec);
     466            const psRandom *r = psRandomAllocSpecific(PS_RANDOM_TAUS, now->sec);
    467467            for (int i = 0; i < NPTS; i++) {
    468468                double errgen = psRandomGaussian(r);
  • branches/cnb_branches/cnb_branch_20090301/pswarp/src/Makefile.am

    r18839 r23352  
    11bin_PROGRAMS = pswarp
    2 pswarp_CPPFLAGS = $(PSLIB_CFLAGS) $(PSMODULE_CFLAGS) $(PPSTATS_CFLAGS) $(PSPHOT_CFLAGS) $(PSWARP_CFLAGS)
     2
     3PSWARP_VERSION=`if [ -e ../../VERSION ]; then cat ../../VERSION; else svnversion; fi`
     4PSWARP_BRANCH=`if [ -e ../../BRANCH ]; then cat ../../BRANCH; else svn info | sed -n -e '/URL:/ h' -e '/Repository Root:/ { x; H; x; s|Repository Root: \(.*\)\nURL: \1\(.*\)|\2| ; s|^/|| ; s|/[a-zA-Z]*/src.*|| ; p }'; fi`
     5PSWARP_SOURCE=`if [ -e ../../SOURCE ]; then cat ../../SOURCE; else svn info | sed -n -e 's/Repository UUID: // p'; fi`
     6
     7# Force recompilation of pswarpVersion.c, since it gets the version information
     8pswarpVersion.c: FORCE
     9        touch pswarpVersion.c
     10FORCE: ;
     11
     12pswarp_CPPFLAGS = $(PSLIB_CFLAGS) $(PSMODULE_CFLAGS) $(PPSTATS_CFLAGS) $(PSPHOT_CFLAGS) $(PSWARP_CFLAGS) -DPSWARP_VERSION=\"$(PSWARP_VERSION)\" -DPSWARP_BRANCH=\"$(PSWARP_BRANCH)\" -DPSWARP_SOURCE=\"$(PSWARP_SOURCE)\"
    313pswarp_LDFLAGS = $(PSLIB_LIBS) $(PSMODULE_LIBS) $(PPSTATS_LIBS) $(PSPHOT_LIBS) $(PSWARP_LIBS)
    414
     
    1828        pswarpSetThreads.c              \
    1929        pswarpTransformReadout.c        \
    20         pswarpTransformSources.c \
     30        pswarpTransformSources.c        \
    2131        pswarpTransformTile.c           \
    2232        pswarpVersion.c           
  • branches/cnb_branches/cnb_branch_20090301/pswarp/src/pswarp.c

    r21442 r23352  
    3939    if (!config) usage();
    4040
     41    pswarpVersionPrint();
     42
    4143    // load identify the data sources
    4244    if (!pswarpParseCamera(config)) {
  • branches/cnb_branches/cnb_branch_20090301/pswarp/src/pswarp.h

    r21368 r23352  
    112112 */
    113113bool pswarpSetThreads ();
     114
     115/// Return software version
     116psString pswarpVersion(void);
     117
     118/// Return software souce
     119psString pswarpSource(void);
     120
     121/// Return long software version information
     122psString pswarpVersionLong(void);
     123
     124/// Populate header with version information
     125bool pswarpVersionHeader(
     126    psMetadata *header                  ///< Header to populate
     127    );
     128
     129/// Print version information
     130void pswarpVersionPrint(void);
  • branches/cnb_branches/cnb_branch_20090301/pswarp/src/pswarpArguments.c

    r21368 r23352  
    4141        if ((arg = psArgumentGet(argc, argv, "-psphot-visual"))) {
    4242            psArgumentRemove(arg, &argc, argv);
    43             psphotSetVisual(true);
     43            pmVisualSetVisual(true);
    4444        }
    4545    }
     
    8787
    8888
    89     if (!pmConfigFileSetsMD (config->arguments, &argc, argv, "INPUT", "-file", "-list")) {
    90         psError(PSWARP_ERR_ARGUMENTS, true, "Missing -file (input) or -list (input)");
    91         return NULL;
    92     }
    93 
    94     // the mask and variance entries are optional (build from gain?)
    95     pmConfigFileSetsMD (config->arguments, &argc, argv, "MASK",   "-mask",   "-masklist");
     89    pmConfigFileSetsMD (config->arguments, &argc, argv, "INPUT", "-file", "-list");
     90    pmConfigFileSetsMD (config->arguments, &argc, argv, "MASK", "-mask", "-masklist");
    9691    pmConfigFileSetsMD (config->arguments, &argc, argv, "VARIANCE", "-variance", "-variancelist");
    9792
     
    105100
    106101    // output position is fixed
    107     psMetadataAddStr (config->arguments, PS_LIST_TAIL, "OUTPUT", 0, "", argv[1]);
     102    psMetadataAddStr(config->arguments, PS_LIST_TAIL, "OUTPUT", 0, "", argv[1]);
    108103
    109104    // skycell position is fixed
    110105    array = psArrayAlloc(1);
    111     array->data[0] = psStringCopy (argv[2]);
    112     status = psMetadataAddPtr (config->arguments, PS_LIST_TAIL, "SKYCELL", PS_DATA_ARRAY, "", array);
    113     psFree (array);
     106    array->data[0] = psStringCopy(argv[2]);
     107    status = psMetadataAddPtr(config->arguments, PS_LIST_TAIL, "SKYCELL", PS_DATA_ARRAY, "", array);
     108    psFree(array);
    114109
    115110    psTrace("pswarp", 1, "Done with pswarpArguments...\n");
    116     return (config);
     111    return config;
    117112}
    118113
     
    204199    psTrace("pswarp", 1, "Done with pswarpArguments...\n");
    205200
    206     // Dump configuration, now that's it's settled
    207     psString dump_file =  psMetadataLookupStr(&status, config->arguments, "DUMP_CONFIG");
    208     if (dump_file) {
    209         const char *skyCamera = psMetadataLookupStr(NULL, config->arguments,
    210                                                     "SKYCELL.CAMERA");  ///< Name of camera for skycell
    211         pmConfigCamerasCull(config, skyCamera);
    212         pmConfigRecipesCull(config, "PSWARP,PPSTATS,PSPHOT,MASKS");
    213 
    214         pmFPAfile *input = psMetadataLookupPtr(NULL, config->files, "PSWARP.INPUT"); // Input file
    215         pmConfigDump(config, input->fpa, dump_file);
    216     }
    217 
    218201    return (config);
    219202}
  • branches/cnb_branches/cnb_branch_20090301/pswarp/src/pswarpLoop.c

    r21468 r23352  
    7676    bool status;
    7777
     78    const char *skyCamera = psMetadataLookupStr(NULL, config->arguments,
     79                                                "SKYCELL.CAMERA");  ///< Name of camera for skycell
     80    pmConfigCamerasCull(config, skyCamera);
     81    pmConfigRecipesCull(config, "PSWARP,PPSTATS,PSPHOT,MASKS,JPEG");
     82
     83
    7884    // load the recipe
    7985    psMetadata *recipe = psMetadataLookupPtr (&status, config->recipes, PSWARP_RECIPE);
     
    8187        psError(PSPHOT_ERR_CONFIG, false, "missing recipe %s", PSWARP_RECIPE);
    8288        return false;
     89    }
     90
     91    if (!pswarpSetMaskBits(config)) {
     92        psError(PS_ERR_IO, false, "failed to set mask bits");
     93        return NULL;
    8394    }
    8495
     
    339350    }
    340351
     352    pswarpVersionHeader(hdu->header);
     353
    341354    if (!pmAstromWriteWCS(hdu->header, outFPA, outChip, WCS_NONLIN_TOL)) {
    342355        psError(PS_ERR_UNKNOWN, false, "Unable to generate WCS header.");
     
    455468    }
    456469
     470    // Dump configuration
     471    psString dump_file = psMetadataLookupStr(&status, config->arguments, "DUMP_CONFIG");
     472    if (dump_file) {
     473        pmFPAfile *input = psMetadataLookupPtr(NULL, config->files, "PSWARP.INPUT"); // Input file
     474        pmConfigDump(config, input->fpa, dump_file);
     475    }
     476
    457477    return true;
    458478}
  • branches/cnb_branches/cnb_branch_20090301/pswarp/src/pswarpParseCamera.c

    r21368 r23352  
    1111 */
    1212
    13 # include "pswarp.h"
     13#include "pswarp.h"
     14
     15// Define an input file
     16static pmFPAfile *defineInputFile(pmConfig *config,// Configuration
     17                                  pmFPAfile *bind,    // File to which to bind, or NULL
     18                                  char *filerule,     // Name of file rule
     19                                  char *argname,      // Argument name
     20                                  pmFPAfileType fileType // Type of file
     21    )
     22{
     23    bool status;
     24
     25    // look for the file on the RUN metadata
     26    pmFPAfile *file = pmFPAfileDefineFromRun(&status, config, filerule); // File to return
     27    if (!status) {
     28        psError(PSWARP_ERR_CONFIG, false, "Failed to load file definition for %s", filerule);
     29        return NULL;
     30    }
     31    if (!file) {
     32        // look for the file on the argument list
     33        if (bind) {
     34            file = pmFPAfileBindFromArgs(&status, bind, config, filerule, argname);
     35        } else {
     36            file = pmFPAfileDefineFromArgs(&status, config, filerule, argname);
     37        }
     38        if (!status) {
     39            psError(PSWARP_ERR_CONFIG, false, "Failed to load file definition for %s", filerule);
     40            return false;
     41        }
     42    }
     43
     44    if (!file) {
     45        return NULL;
     46    }
     47
     48    if (file->type != fileType) {
     49        psError(PSWARP_ERR_CONFIG, true, "%s is not of type %s", filerule, pmFPAfileStringFromType(fileType));
     50        return NULL;
     51    }
     52
     53    return file;
     54}
     55
     56
     57
    1458
    1559bool pswarpParseCamera(pmConfig *config)
    1660{
    17     bool status;
    18     bool mdok;                          ///< Status of MD lookup
    19     pmFPAfile *skycell = NULL;
    20     pmConfig *skyConfig = NULL;
     61    psAssert(config, "Require configuration");
    2162
    22     // the input image(s) are required arguments; they define the camera
    23     status = false;
    24     pmFPAfile *input = pmFPAfileDefineFromArgs(&status, config, "PSWARP.INPUT", "INPUT");
    25     if (!input || !status) {
     63    // The input image(s) is required: it defines the camera
     64    pmFPAfile *input = defineInputFile(config, NULL, "PSWARP.INPUT", "INPUT", PM_FPA_FILE_IMAGE);
     65    if (!input) {
    2666        psError(PSWARP_ERR_CONFIG, false, "Failed to build FPA from PSWARP.INPUT");
    2767        return false;
    2868    }
    2969
    30     // the input image(s) are required arguments; they define the camera
    31     status = false;
    32     pmFPAfile *astrom = pmFPAfileDefineFromArgs(&status, config, "PSWARP.ASTROM", "ASTROM");
    33     if (!status) {
    34         psError (PS_ERR_UNKNOWN, false, "failed to load find definition");
    35         return NULL;
    36     }
    37     if (astrom) {
    38         psLogMsg ("pswarp", 3, "using supplied astrometry\n");
    39     } else {
    40         psLogMsg ("pswarp", 3, "using header astrometry\n");
     70    pmFPAfile *astrom = defineInputFile(config, NULL, "PSWARP.ASTROM", "ASTROM", PM_FPA_FILE_CMF);
     71    psLogMsg("pswarp", PS_LOG_INFO, "Astrometry source: %s", astrom ? "supplied" : "header");
     72
     73    pmFPAfile *inMask = defineInputFile(config, input, "PSWARP.MASK", "MASK", PM_FPA_FILE_MASK);
     74    if (!inMask) {
     75        psLogMsg("pswarp", PS_LOG_INFO, "No mask supplied");
    4176    }
    4277
    43     // the mask is not required - but must conform to input camera
    44     pmFPAfile *inMask = pmFPAfileBindFromArgs(&status, input, config, "PSWARP.MASK", "MASK");
    45     if (!status) {
    46         psError (PS_ERR_UNKNOWN, false, "failed to load find definition");
    47         return NULL;
    48     }
    49     if (!inMask) {
    50         psLogMsg ("pswarp", 3, "no mask supplied\n");
     78    pmFPAfile *inVariance = defineInputFile(config, input, "PSWARP.VARIANCE", "VARIANCE",
     79                                            PM_FPA_FILE_VARIANCE);
     80    if (!inVariance) {
     81        psLogMsg("pswarp", PS_LOG_INFO, "No variance supplied");
    5182    }
    5283
    53     // loading the mask here should have invoked pmConfigMaskReadHeader()
    54     if (!pswarpSetMaskBits (config)) {
    55         psError(PS_ERR_IO, false, "failed to set mask bits");
    56         return NULL;
    57     }
    58 
    59     pmFPAfile *inVariance = pmFPAfileBindFromArgs(&status, input, config, "PSWARP.VARIANCE", "VARIANCE");
    60     if (!status) {
    61         psError (PS_ERR_UNKNOWN, false, "failed to load find definition");
    62         return NULL;
    63     }
    64     if (!inVariance) {
    65         psLogMsg ("pswarp", 3, "no variance supplied\n");
    66     }
    67 
    68     // the input skycell is a required argument: it defines the output image
     84    // The input skycell is a required argument: it defines the output image
    6985    // XXX we may need a different skycell structure here
    70     status = pswarpDefineSkycell(&skycell, &skyConfig, config, "PSWARP.SKYCELL", "SKYCELL");
     86    pmFPAfile *skycell = NULL;
     87    pmConfig *skyConfig = NULL;
     88    bool status = pswarpDefineSkycell(&skycell, &skyConfig, config, "PSWARP.SKYCELL", "SKYCELL");
    7189    if (!status) {
    7290        psError(PSWARP_ERR_CONFIG, false, "Failed to build FPA from PSWARP.SKYCELL");
     
    8199        return false;
    82100    }
     101    output->save = true;
     102
    83103    pmFPAfile *outMask = pmFPAfileDefineSkycell(config, output->fpa, "PSWARP.OUTPUT.MASK");
    84104    if (!outMask) {
     
    86106        return false;
    87107    }
    88 
    89     output->save = true;
    90108    outMask->save = true;
    91109
     
    108126    }
    109127
     128    bool mdok;                          // Status of MD lookup
    110129    if (psMetadataLookupBool(&mdok, config->arguments, "PSF")) {
    111130        // This file, PSPHOT.INPUT, is just used as a carrier; output files (eg, PSPHOT.RESID) are defined by
     
    160179            }
    161180        }
    162         psFree (chips);
     181        psFree(chips);
    163182    }
    164183
  • branches/cnb_branches/cnb_branch_20090301/pswarp/src/pswarpVersion.c

    r21323 r23352  
    1818#include <pslib.h>
    1919#include <psmodules.h>
     20#include <psphot.h>
     21#include <ppStats.h>
    2022#include "pswarp.h"
    2123
    22 static const char *cvsTag = "$Name: not supported by cvs2svn $";///< CVS tag name
    2324
    2425psString pswarpVersion(void)
    2526{
    26     psString version = NULL;            ///< Version, to return
    27     psStringAppend(&version, "%s-%s",PACKAGE_NAME,PACKAGE_VERSION);
    28     return version;
     27#ifndef PSWARP_VERSION
     28#error "PSWARP_VERSION is not set"
     29#endif
     30#ifndef PSWARP_BRANCH
     31#error "PSWARP_BRANCH is not set"
     32#endif
     33    return psStringCopy(PSWARP_BRANCH "@" PSWARP_VERSION);
     34}
     35
     36psString pswarpSource(void)
     37{
     38#ifndef PSWARP_SOURCE
     39#error "PSWARP_SOURCE is not set"
     40#endif
     41    return psStringCopy(PSWARP_SOURCE);
    2942}
    3043
    3144psString pswarpVersionLong(void)
    3245{
    33     psString version = pswarpVersion(); ///< Version, to return
    34     psString tag = psStringStripCVS(cvsTag, "Name"); ///< CVS tag
    35     psStringAppend(&version, " (cvs tag %s) %s, %s", tag, __DATE__, __TIME__);
    36     psFree(tag);
     46    psString version = pswarpVersion();  // Version, to return
     47    psString source = pswarpSource();    // Source
     48
     49    psStringPrepend(&version, "pswarp ");
     50    psStringAppend(&version, " from %s, built %s, %s", source, __DATE__, __TIME__);
     51    psFree(source);
     52
     53#ifdef __OPTIMIZE__
     54    psStringAppend(&version, " optimised");
     55#else
     56    psStringAppend(&version, " unoptimised");
     57#endif
     58
    3759    return version;
     60};
     61
     62
     63bool pswarpVersionHeader(psMetadata *header)
     64{
     65    PS_ASSERT_METADATA_NON_NULL(header, false);
     66
     67    psTime *time = psTimeGetNow(PS_TIME_TAI); // The time now
     68    psString timeString = psTimeToISO(time); // The time in an ISO string
     69    psFree(time);
     70    psString history = NULL;               // History string
     71    psStringAppend(&history, "pswarp at %s", timeString);
     72    psFree(timeString);
     73    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, history);
     74    psFree(history);
     75
     76    psLibVersionHeader(header);
     77    psModulesVersionHeader(header);
     78    psphotVersionHeader(header);
     79    ppStatsVersionHeader(header);
     80
     81    psString version = pswarpVersion(); // Software version
     82    psString source  = pswarpSource();  // Software source
     83
     84    psStringPrepend(&version, "pswarp version: ");
     85    psStringPrepend(&source, "pswarp source: ");
     86
     87    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, version);
     88    psMetadataAddStr(header, PS_LIST_TAIL, "HISTORY", PS_META_DUPLICATE_OK, NULL, source);
     89
     90    psFree(version);
     91    psFree(source);
     92
     93    return true;
    3894}
    3995
     96void pswarpVersionPrint(void)
     97{
     98    psTime *time = psTimeGetNow(PS_TIME_TAI); // The time now
     99    psString timeString = psTimeToISO(time); // The time in an ISO string
     100    psFree(time);
     101    psLogMsg("pswarp", PS_LOG_INFO, "pswarp at %s", timeString);
     102    psFree(timeString);
     103
     104    psString pslib = psLibVersionLong();// psLib version
     105    psString psmodules = psModulesVersionLong(); // psModules version
     106    psString psphot = psphotVersionLong(); // psphot version
     107    psString ppStats = ppStatsVersionLong(); // ppStats version
     108    psString pswarp = pswarpVersionLong(); // pswarp version
     109
     110    psLogMsg("pswarp", PS_LOG_INFO, "%s", pslib);
     111    psLogMsg("pswarp", PS_LOG_INFO, "%s", psmodules);
     112    psLogMsg("pswarp", PS_LOG_INFO, "%s", psphot);
     113    psLogMsg("pswarp", PS_LOG_INFO, "%s", ppStats);
     114    psLogMsg("pswarp", PS_LOG_INFO, "%s", pswarp);
     115
     116    psFree(pslib);
     117    psFree(psmodules);
     118    psFree(psphot);
     119    psFree(ppStats);
     120    psFree(pswarp);
     121
     122    return;
     123}
Note: See TracChangeset for help on using the changeset viewer.