IPP Software Navigation Tools IPP Links Communication Pan-STARRS Links

Changeset 23594


Ignore:
Timestamp:
Mar 29, 2009, 6:15:31 PM (17 years ago)
Author:
beaumont
Message:

merged with head

Location:
branches/cnb_branches/cnb_branch_20090301
Files:
6 deleted
313 edited
114 copied

Legend:

Unmodified
Added
Removed
  • branches/cnb_branches/cnb_branch_20090301

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

    r20155 r23594  
    11Revision history for Nebulous
     2
     30.17
     4    - retry database transactions when a deadlock is detected
    25
    360.16
  • branches/cnb_branches/cnb_branch_20090301/Nebulous-Server/bin/neb-admin

    r23352 r23594  
    152152       
    153153    exit unless scalar @rows;
     154   
     155    # compare number of responses to limit below
     156    my $Npending = @rows;
    154157
    155158    print "replicatePending MULTI\n\n";
     
    198201    }
    199202
    200     return 1;
     203    # use a different exit status if we hit the limit (likely more files pending)
     204    if ($Npending == $limit) {
     205        exit 1;
     206    }
     207    exit 0;
    201208}
    202 
    203209
    204210sub removal
  • branches/cnb_branches/cnb_branch_20090301/Nebulous-Server/lib/Nebulous/Server.pm

    r20990 r23594  
    163163
    164164    my $uri;
    165     eval {
    166         {
    167             # create storage_object
    168             my $query = $db->prepare_cached( $sql->new_object );
    169             $query->execute('NULL', $key->path);
    170         }
    171 
    172         my $so_id;
    173         {
    174             # get object ID
    175             my $query = $db->prepare_cached( $sql->last_insert_id );
    176             $query->execute;
    177             ($so_id) = $query->fetchrow_array;
    178             # XXX finish seems to be required when using LAST_INSERT_ID() or we
    179             # get a warning about the stmt handling still be active the next
    180             # time LAST_INSERT_ID() is invoked
    181             $query->finish;
    182         }
    183 
    184         {
    185             # create storage_object_attr
    186             my $query = $db->prepare_cached( $sql->new_object_attr );
    187             $query->execute($so_id);
    188         }
    189 
    190         {
    191            
    192             # create instance with no URI
     165TRANS: while (1) {
     166        eval {
     167            {
     168                # create storage_object
     169                my $query = $db->prepare_cached( $sql->new_object );
     170                $query->execute('NULL', $key->path);
     171            }
     172
     173            my $so_id;
     174            {
     175                # get object ID
     176                my $query = $db->prepare_cached( $sql->last_insert_id );
     177                $query->execute;
     178                ($so_id) = $query->fetchrow_array;
     179                # XXX finish seems to be required when using LAST_INSERT_ID() or we
     180                # get a warning about the stmt handling still be active the next
     181                # time LAST_INSERT_ID() is invoked
     182                $query->finish;
     183            }
     184
     185            {
     186                # create storage_object_attr
     187                my $query = $db->prepare_cached( $sql->new_object_attr );
     188                $query->execute($so_id);
     189            }
     190
     191            {
     192               
     193                # create instance with no URI
    193194#            my $query = $db->prepare_cached( $sql->new_instance );
    194             my $query = $db->prepare_cached( $sql->new_object_instance );
    195             $query->execute($vol_id);
    196         }
    197 
    198         my $ins_id;
    199         {
    200             # get instance ID
    201             my $query = $db->prepare_cached( $sql->last_insert_id );
    202             $query->execute;
    203             ($ins_id) = $query->fetchrow_array;
    204             # XXX finish seems to be required when using LAST_INSERT_ID() or we
    205             # get a warning about the stmt handling still be active the next
    206             # time LAST_INSERT_ID() is invoked
    207             $query->finish;
    208         }
    209 
    210         # Unfortunately, since we want to use the instance row's ID as part of the
    211         # actual on disk file name we can't try to create the file until after
    212         # we've create both a new storage_storage object and instance.
    213 
    214         # TODO add some stuff here to retry if unsucessful
    215         $uri = $self->_create_empty_instance_file($key->path, $so_id, $ins_id, $vol_path, $vol_xattr);
    216         $log->debug("created $uri on volume ID: $vol_id");
    217 
    218         {
    219             # update the instance with URI & vol_id that the file is on
    220             my $query = $db->prepare_cached( $sql->update_instance_uri );
    221             # vol_id, uri, ins_id
    222             $query->execute($vol_id, "$uri", $ins_id);
    223         }
    224 
    225         $db->commit;
    226         $log->debug("commit");
    227     };
    228     if ($@) {
     195                my $query = $db->prepare_cached( $sql->new_object_instance );
     196                $query->execute($vol_id);
     197            }
     198
     199            my $ins_id;
     200            {
     201                # get instance ID
     202                my $query = $db->prepare_cached( $sql->last_insert_id );
     203                $query->execute;
     204                ($ins_id) = $query->fetchrow_array;
     205                # XXX finish seems to be required when using LAST_INSERT_ID() or we
     206                # get a warning about the stmt handling still be active the next
     207                # time LAST_INSERT_ID() is invoked
     208                $query->finish;
     209            }
     210
     211            # Unfortunately, since we want to use the instance row's ID as part of the
     212            # actual on disk file name we can't try to create the file until after
     213            # we've create both a new storage_storage object and instance.
     214
     215            # TODO add some stuff here to retry if unsucessful
     216            $uri = $self->_create_empty_instance_file($key->path, $so_id, $ins_id, $vol_path, $vol_xattr);
     217            $log->debug("created $uri on volume ID: $vol_id");
     218
     219            {
     220                # update the instance with URI & vol_id that the file is on
     221                my $query = $db->prepare_cached( $sql->update_instance_uri );
     222                # vol_id, uri, ins_id
     223                $query->execute($vol_id, "$uri", $ins_id);
     224            }
     225
     226            $db->commit;
     227            $log->debug("commit");
     228        };
     229        if ($@) {
    229230#        and not $key->soft_volume
    230         $db->rollback;
    231         $log->debug("rollback");
    232         $log->logdie("error: $@");
     231            $db->rollback;
     232            $log->debug("rollback");
     233            if ($@ =~ /Deadlock found/) {
     234                $log->warn("database deadlock retrying transaction: $@");
     235                redo TRANS;
     236            }
     237            $log->logdie("error: $@");
     238        }
     239        last;
    233240    }
    234241
     
    269276    $newkey = parse_neb_key($newkey);
    270277
    271     eval {
    272         # rename storage_object
    273         my $query = $db->prepare_cached($sql->rename_object);
    274         # this SQL statment takes the new key name as the first param
    275         my $rows = $query->execute($newkey->path, $key->path);
    276 
    277         # if we affected more then one row something very bad has happened.
    278         unless ($rows == 1) {
    279             $query->finish;
    280             $log->logdie("affected row count is $rows instead of 1");
    281         }
    282 
    283         $db->commit;
    284         $log->debug("commit");
    285     };
    286     if ($@) {
    287         $db->rollback;
    288         $log->debug("rollback");
    289         $log->logdie("database error: $@");
    290     }
     278TRANS: while (1) {
     279        eval {
     280            # rename storage_object
     281            my $query = $db->prepare_cached($sql->rename_object);
     282            # this SQL statment takes the new key name as the first param
     283            my $rows = $query->execute($newkey->path, $key->path);
     284
     285            # if we affected more then one row something very bad has happened.
     286            unless ($rows == 1) {
     287                $query->finish;
     288                $log->logdie("affected row count is $rows instead of 1");
     289            }
     290
     291            $db->commit;
     292            $log->debug("commit");
     293        };
     294        if ($@) {
     295            $db->rollback;
     296            $log->debug("rollback");
     297            if ($@ =~ /Deadlock found/) {
     298                $log->warn("database deadlock retrying transaction: $@");
     299                redo TRANS;
     300            }
     301            $log->logdie("database error: $@");
     302        }
     303        last;
     304    }
    291305
    292306    $log->debug("leaving");
     
    330344    # key1.swap -> key2
    331345
    332     eval {
    333         {
    334             # key1 -> key1.swap
    335             my $query = $db->prepare_cached($sql->rename_object);
    336             # this SQL statment takes the new key name as the first param
    337             my $rows = $query->execute($key1->path . ".swap", $key1->path);
    338 
    339             # if we affected more then one row something very bad has happened.
    340             unless ($rows == 1) {
    341                 $query->finish;
    342                 $log->logdie("affected row count is $rows instead of 1");
    343             }
    344         }
    345 
    346         {
    347             # key2 -> key1
    348             my $query = $db->prepare_cached($sql->rename_object);
    349             # this SQL statment takes the new key name as the first param
    350             my $rows = $query->execute($key1->path, $key2->path);
    351 
    352             # if we affected more then one row something very bad has happened.
    353             unless ($rows == 1) {
    354                 $query->finish;
    355                 $log->logdie("affected row count is $rows instead of 1");
    356             }
    357         }
    358 
    359         {
    360             # key1.swap -> key2
    361             my $query = $db->prepare_cached($sql->rename_object);
    362             # this SQL statment takes the new key name as the first param
    363             my $rows = $query->execute($key2->path, $key1->path . ".swap");
    364 
    365             # if we affected more then one row something very bad has happened.
    366             unless ($rows == 1) {
    367                 $query->finish;
    368                 $log->logdie("affected row count is $rows instead of 1");
    369             }
    370         }
    371 
    372         $db->commit;
    373         $log->debug("commit");
    374     };
    375     if ($@) {
    376         $db->rollback;
    377         $log->debug("rollback");
    378         $log->logdie("database error: $@");
     346TRANS: while (1) {
     347        eval {
     348            {
     349                # key1 -> key1.swap
     350                my $query = $db->prepare_cached($sql->rename_object);
     351                # this SQL statment takes the new key name as the first param
     352                my $rows = $query->execute($key1->path . ".swap", $key1->path);
     353
     354                # if we affected more then one row something very bad has happened.
     355                unless ($rows == 1) {
     356                    $query->finish;
     357                    $log->logdie("affected row count is $rows instead of 1");
     358                }
     359            }
     360
     361            {
     362                # key2 -> key1
     363                my $query = $db->prepare_cached($sql->rename_object);
     364                # this SQL statment takes the new key name as the first param
     365                my $rows = $query->execute($key1->path, $key2->path);
     366
     367                # if we affected more then one row something very bad has happened.
     368                unless ($rows == 1) {
     369                    $query->finish;
     370                    $log->logdie("affected row count is $rows instead of 1");
     371                }
     372            }
     373
     374            {
     375                # key1.swap -> key2
     376                my $query = $db->prepare_cached($sql->rename_object);
     377                # this SQL statment takes the new key name as the first param
     378                my $rows = $query->execute($key2->path, $key1->path . ".swap");
     379
     380                # if we affected more then one row something very bad has happened.
     381                unless ($rows == 1) {
     382                    $query->finish;
     383                    $log->logdie("affected row count is $rows instead of 1");
     384                }
     385            }
     386
     387            $db->commit;
     388            $log->debug("commit");
     389        };
     390        if ($@) {
     391            $db->rollback;
     392            $log->debug("rollback");
     393            if ($@ =~ /Deadlock found/) {
     394                $log->warn("database deadlock retrying transaction: $@");
     395                redo TRANS;
     396            }
     397            $log->logdie("database error: $@");
     398        }
     399        last;
    379400    }
    380401
     
    448469
    449470    my $uri;
    450     eval {
    451         my $so_id;
    452         {
    453             # verify that at least one instance is currently available
    454             my $query = $db->prepare_cached( $sql->get_object_instances );
    455             my $rows = $query->execute($key->path, 1);
    456 
    457             unless ( $rows > 0 ) {
     471TRANS: while (1) {
     472        eval {
     473            my $so_id;
     474            {
     475                # verify that at least one instance is currently available
     476                my $query = $db->prepare_cached( $sql->get_object_instances );
     477                my $rows = $query->execute($key->path, 1);
     478
     479                unless ( $rows > 0 ) {
     480                    $query->finish;
     481                    $log->logdie( "storage object does not exist" );
     482                }
     483
     484                $so_id = $query->fetchrow_hashref->{ 'so_id' };
    458485                $query->finish;
    459                 $log->logdie( "storage object does not exist" );
    460             }
    461 
    462             $so_id = $query->fetchrow_hashref->{ 'so_id' };
    463             $query->finish;
    464         }
    465 
    466         {
    467             my $query = $db->prepare_cached( $sql->new_instance );
    468             $query->execute($so_id, $vol_id);
    469         }
    470 
    471         my $ins_id;
    472         {
    473             my $query = $db->prepare_cached( $sql->last_insert_id );
    474             $query->execute();
    475             ($ins_id) = $query->fetchrow_array;
    476             # XXX finish seems to be required when using LAST_INSERT_ID() or we
    477             # get a warning about the stmt handling still being active the next
    478             # time LAST_INSERT_ID() is invoked
    479             $query->finish;
    480         }
    481 
    482         # Unfortunately, since we want to use the instance row's ID as part of
    483         # the actual on disk file name we can't try to create the file until
    484         # after we've create both a new storage_storage object and instance.
    485 
    486         # TODO add some stuff here to retry if unsucessful
    487         $uri = $self->_create_empty_instance_file($key->path, $so_id, $ins_id, $vol_path, $vol_xattr);
    488 
    489         {
    490             my $query = $db->prepare_cached( $sql->update_instance_uri );
    491             # vol_id, uri, ins_id
    492             $query->execute($vol_id, $uri, $ins_id);
    493         }
    494 
    495         $db->commit;
    496         $log->debug("commit");
    497     };
    498     if ($@) {
    499         $db->rollback;
    500         # handle soft volumes
    501         if (defined $vol_name and defined $key->soft_volume) {
    502             $log->debug("retrying with 'any' volume");
    503             return $self->replicate_object($key->path, 'any');
    504         }
    505         $log->debug("rollback");
    506         $log->logdie("error: $@");
     486            }
     487
     488            {
     489                my $query = $db->prepare_cached( $sql->new_instance );
     490                $query->execute($so_id, $vol_id);
     491            }
     492
     493            my $ins_id;
     494            {
     495                my $query = $db->prepare_cached( $sql->last_insert_id );
     496                $query->execute();
     497                ($ins_id) = $query->fetchrow_array;
     498                # XXX finish seems to be required when using LAST_INSERT_ID() or we
     499                # get a warning about the stmt handling still being active the next
     500                # time LAST_INSERT_ID() is invoked
     501                $query->finish;
     502            }
     503
     504            # Unfortunately, since we want to use the instance row's ID as part of
     505            # the actual on disk file name we can't try to create the file until
     506            # after we've create both a new storage_storage object and instance.
     507
     508            # TODO add some stuff here to retry if unsucessful
     509            $uri = $self->_create_empty_instance_file($key->path, $so_id, $ins_id, $vol_path, $vol_xattr);
     510
     511            {
     512                my $query = $db->prepare_cached( $sql->update_instance_uri );
     513                # vol_id, uri, ins_id
     514                $query->execute($vol_id, $uri, $ins_id);
     515            }
     516
     517            $db->commit;
     518            $log->debug("commit");
     519        };
     520        if ($@) {
     521            $db->rollback;
     522            # handle soft volumes
     523            if (defined $vol_name and defined $key->soft_volume) {
     524                $log->debug("retrying with 'any' volume");
     525                return $self->replicate_object($key->path, 'any');
     526            }
     527            $log->debug("rollback");
     528            if ($@ =~ /Deadlock found/) {
     529                $log->warn("database deadlock retrying transaction: $@");
     530                redo TRANS;
     531            }
     532            $log->logdie("error: $@");
     533        }
     534        last;
    507535    }
    508536
     
    545573    my $write_lock;
    546574
    547     eval {
    548         {
    549             # this will set update locks
    550             my $query = $db->prepare_cached( $sql->get_object_locks );
    551             my $rows = $query->execute( $key->path );
    552             unless ( $rows == 1 ) {
     575TRANS: while (1) {
     576        eval {
     577            {
     578                # this will set update locks
     579                my $query = $db->prepare_cached( $sql->get_object_locks );
     580                my $rows = $query->execute( $key->path );
     581                unless ( $rows == 1 ) {
     582                    $query->finish;
     583                    $log->logdie( "storage object does not exist" );
     584                }
     585
     586                my $row = $query->fetchrow_hashref;
    553587                $query->finish;
    554                 $log->logdie( "storage object does not exist" );
    555             }
    556 
    557             my $row = $query->fetchrow_hashref;
    558             $query->finish;
    559 
    560             $so_id      = $row->{ 'so_id' };
    561             $read_lock  = $row->{ 'read_lock' };
    562             $write_lock = $row->{ 'write_lock' };
    563         }
    564 
    565         if ($type eq 'write') {
    566             # can't set a write lock twice and
    567             # can't set a write lock if there are read locks
    568             if ($write_lock) {
    569                 $log->logdie("can not write lock twice -- retry");
    570             }
    571            
    572             if ($read_lock > 0) {
    573                 $log->logdie("can not write lock after read lock -- retry");
    574             }
    575 
    576             {
    577                 my $query = $db->prepare_cached( $sql->set_write_lock );
    578                 my $rows = $query->execute($key->path);
    579            
    580                 # if we affected more then one row something very bad has happened.
    581                 unless ($rows == 1) {
    582                     $log->logdie("affected row count is $rows instead of 1");
    583                 }
    584 
    585             }
    586         } elsif ($type eq 'read') {
    587             # can't set a read lock if there's a write lock
    588             if ($write_lock) {
    589                 $log->logdie("can not read lock after write lock -- retry");
    590             }
    591 
    592             {
    593                 my $query = $db->prepare_cached( $sql->increment_read_lock );
    594                 my $rows = $query->execute($key->path);
    595            
    596                 # if we affected more then one row something very bad has happened.
    597                 unless ($rows == 1) {
    598                     $log->logdie("affected row count is $rows instead of 1");
    599                 }
    600             }
    601         }
    602 
    603         $db->commit;
    604         $log->debug("commit");
    605     };
    606     if ($@) {
    607         $db->rollback;
    608         $log->debug("rollback");
    609         $log->logdie("error: $@");
     588
     589                $so_id      = $row->{ 'so_id' };
     590                $read_lock  = $row->{ 'read_lock' };
     591                $write_lock = $row->{ 'write_lock' };
     592            }
     593
     594            if ($type eq 'write') {
     595                # can't set a write lock twice and
     596                # can't set a write lock if there are read locks
     597                if ($write_lock) {
     598                    $log->logdie("can not write lock twice -- retry");
     599                }
     600               
     601                if ($read_lock > 0) {
     602                    $log->logdie("can not write lock after read lock -- retry");
     603                }
     604
     605                {
     606                    my $query = $db->prepare_cached( $sql->set_write_lock );
     607                    my $rows = $query->execute($key->path);
     608               
     609                    # if we affected more then one row something very bad has happened.
     610                    unless ($rows == 1) {
     611                        $log->logdie("affected row count is $rows instead of 1");
     612                    }
     613
     614                }
     615            } elsif ($type eq 'read') {
     616                # can't set a read lock if there's a write lock
     617                if ($write_lock) {
     618                    $log->logdie("can not read lock after write lock -- retry");
     619                }
     620
     621                {
     622                    my $query = $db->prepare_cached( $sql->increment_read_lock );
     623                    my $rows = $query->execute($key->path);
     624               
     625                    # if we affected more then one row something very bad has happened.
     626                    unless ($rows == 1) {
     627                        $log->logdie("affected row count is $rows instead of 1");
     628                    }
     629                }
     630            }
     631
     632            $db->commit;
     633            $log->debug("commit");
     634        };
     635        if ($@) {
     636            $db->rollback;
     637            $log->debug("rollback");
     638            if ($@ =~ /Deadlock found/) {
     639                $log->warn("database deadlock retrying transaction: $@");
     640                redo TRANS;
     641            }
     642            $log->logdie("error: $@");
     643        }
     644        last;
    610645    }
    611646
     
    648683    my $write_lock;
    649684
    650     eval {
    651         {
    652             # this will set update locks
    653             my $query = $db->prepare_cached( $sql->get_object_locks );
    654             my $rows = $query->execute($key->path);
    655             unless ($rows == 1) {
     685TRANS: while (1) {
     686        eval {
     687            {
     688                # this will set update locks
     689                my $query = $db->prepare_cached( $sql->get_object_locks );
     690                my $rows = $query->execute($key->path);
     691                unless ($rows == 1) {
     692                    $query->finish;
     693                    $log->logdie("storage object does not exist");
     694                }
     695
     696                my $row = $query->fetchrow_hashref;
    656697                $query->finish;
    657                 $log->logdie("storage object does not exist");
    658             }
    659 
    660             my $row = $query->fetchrow_hashref;
    661             $query->finish;
    662 
    663             $so_id      = $row->{ 'so_id' };
    664             $read_lock  = $row->{ 'read_lock' };
    665             $write_lock = $row->{ 'write_lock' };
    666         }
    667 
    668         if ($type eq 'write') {
    669             # can't remove a write lock if it doesn't exist
    670             if ($read_lock) {
    671                 $log->logdie("can not have a write lock under a read lock");
    672             }
    673 
    674             unless ($write_lock) {
    675                 $log->logdie("can not remove non-existant write lock");
    676             }
    677 
    678             {
    679                 my $query = $db->prepare_cached( $sql->delete_write_lock );
    680                 my $rows = $query->execute($key->path);
    681            
    682                 # if we affected more then one row something very bad has happened.
    683                 unless ($rows == 1) {
    684                     $log->logdie("affected row count is $rows instead of 1");
    685                 }
    686             }
    687         } elsif ($type eq 'read') {
    688             # can't remove a read lock if there's a write lock and
    689             # can't remove a read lock if there aren't any
    690             if ($write_lock) {
    691                 $log->logdie("can not have a read lock under a write lock");
    692             }
    693                
    694             if ($read_lock == 0) {
    695                 $log->logdie("can not remove non-existant read lock");
    696             }
    697 
    698             {
    699                 my $query = $db->prepare_cached( $sql->decrement_read_lock );
    700                 my $rows = $query->execute($key->path);
    701            
    702                 # if we affected more then one row something very bad has happened.
    703                 unless ($rows == 1) {
    704                     $log->logdie("affected row count is $rows instead of 1");
    705                 }
    706 
    707             }
    708         }
    709         $db->commit;
    710         $log->debug("commit");
    711     };
    712     if ($@) {
    713         $db->rollback;
    714         $log->debug("rollback");
    715         $log->logdie("error: $@");
     698
     699                $so_id      = $row->{ 'so_id' };
     700                $read_lock  = $row->{ 'read_lock' };
     701                $write_lock = $row->{ 'write_lock' };
     702            }
     703
     704            if ($type eq 'write') {
     705                # can't remove a write lock if it doesn't exist
     706                if ($read_lock) {
     707                    $log->logdie("can not have a write lock under a read lock");
     708                }
     709
     710                unless ($write_lock) {
     711                    $log->logdie("can not remove non-existant write lock");
     712                }
     713
     714                {
     715                    my $query = $db->prepare_cached( $sql->delete_write_lock );
     716                    my $rows = $query->execute($key->path);
     717               
     718                    # if we affected more then one row something very bad has happened.
     719                    unless ($rows == 1) {
     720                        $log->logdie("affected row count is $rows instead of 1");
     721                    }
     722                }
     723            } elsif ($type eq 'read') {
     724                # can't remove a read lock if there's a write lock and
     725                # can't remove a read lock if there aren't any
     726                if ($write_lock) {
     727                    $log->logdie("can not have a read lock under a write lock");
     728                }
     729                   
     730                if ($read_lock == 0) {
     731                    $log->logdie("can not remove non-existant read lock");
     732                }
     733
     734                {
     735                    my $query = $db->prepare_cached( $sql->decrement_read_lock );
     736                    my $rows = $query->execute($key->path);
     737               
     738                    # if we affected more then one row something very bad has happened.
     739                    unless ($rows == 1) {
     740                        $log->logdie("affected row count is $rows instead of 1");
     741                    }
     742
     743                }
     744            }
     745            $db->commit;
     746            $log->debug("commit");
     747        };
     748        if ($@) {
     749            $db->rollback;
     750            $log->debug("rollback");
     751            if ($@ =~ /Deadlock found/) {
     752                $log->warn("database deadlock retrying transaction: $@");
     753                redo TRANS;
     754            }
     755            $log->logdie("error: $@");
     756        }
     757        last;
    716758    }
    717759
     
    756798    $key = parse_neb_key($key);
    757799
    758     eval {
    759         my $query;
    760 
    761         if ($flags eq 'create') {
    762             $query = $db->prepare_cached( $sql->new_object_xattr );
    763         } else {
    764             # replace
    765             $query = $db->prepare_cached( $sql->replace_object_xattr );
    766         }
    767 
    768         # name, value, ext_id
    769         my $rows = $query->execute($name, $value, $key->path);
    770         $query->finish;
    771 
    772         # if we affected more then one row something very bad has happened.
    773         if ($flags eq 'create') {
    774             unless ($rows == 1) {
    775                 $log->logdie( "affected row count is $rows instead of 1" );
    776             }
    777         } else {
    778             # replace_object_xattr can effect either 1 or 2 rows.  2 rows in
    779             # the case of a replace and 1 if the xattr didn't already exist.
    780             unless ($rows == 1 or $rows == 2) {
    781                 $log->logdie( "affected row count is $rows instead of 2" );
    782             }
    783         }
    784 
    785         $db->commit;
    786         $log->debug("commit");
    787     };
    788     if ($@) {
    789         $db->rollback;
    790         $log->debug("rollback");
    791         $log->logdie("database error: $@");
     800TRANS: while (1) {
     801        eval {
     802            my $query;
     803
     804            if ($flags eq 'create') {
     805                $query = $db->prepare_cached( $sql->new_object_xattr );
     806            } else {
     807                # replace
     808                $query = $db->prepare_cached( $sql->replace_object_xattr );
     809            }
     810
     811            # name, value, ext_id
     812            my $rows = $query->execute($name, $value, $key->path);
     813            $query->finish;
     814
     815            # if we affected more then one row something very bad has happened.
     816            if ($flags eq 'create') {
     817                unless ($rows == 1) {
     818                    $log->logdie( "affected row count is $rows instead of 1" );
     819                }
     820            } else {
     821                # replace_object_xattr can effect either 1 or 2 rows.  2 rows in
     822                # the case of a replace and 1 if the xattr didn't already exist.
     823                unless ($rows == 1 or $rows == 2) {
     824                    $log->logdie( "affected row count is $rows instead of 2" );
     825                }
     826            }
     827
     828            $db->commit;
     829            $log->debug("commit");
     830        };
     831        if ($@) {
     832            $db->rollback;
     833            $log->debug("rollback");
     834            if ($@ =~ /Deadlock found/) {
     835                $log->warn("database deadlock retrying transaction: $@");
     836                redo TRANS;
     837            }
     838            $log->logdie("database error: $@");
     839        }
     840        last;
    792841    }
    793842
     
    919968    $key = parse_neb_key($key);
    920969
    921     eval {
    922         my $query = $db->prepare_cached( $sql->remove_object_xattr );
    923         # ext_id, name
    924         my $rows = $query->execute($key->path, $name);
    925         $query->finish;
    926 
    927         # if we affected more then one row something very bad has happened.
    928         unless ($rows == 1) {
    929             $log->logdie( "affected row count is $rows instead of 1" );
    930         }
    931 
    932         $db->commit;
    933         $log->debug("commit");
    934     };
    935     if ($@) {
    936         $db->rollback;
    937         $log->debug("rollback");
    938         $log->logdie("database error: $@");
    939     }
     970TRANS: while (1) {
     971        eval {
     972            my $query = $db->prepare_cached( $sql->remove_object_xattr );
     973            # ext_id, name
     974            my $rows = $query->execute($key->path, $name);
     975            $query->finish;
     976
     977            # if we affected more then one row something very bad has happened.
     978            unless ($rows == 1) {
     979                $log->logdie( "affected row count is $rows instead of 1" );
     980            }
     981
     982            $db->commit;
     983            $log->debug("commit");
     984        };
     985        if ($@) {
     986            $db->rollback;
     987            $log->debug("rollback");
     988            if ($@ =~ /Deadlock found/) {
     989                $log->warn("database deadlock retrying transaction: $@");
     990                redo TRANS;
     991            }
     992            $log->logdie("database error: $@");
     993        }
     994        last;
     995    }
    940996
    941997    $log->debug("leaving");
     
    10991155    $log->debug( "entered - @_" );
    11001156
    1101     eval {
    1102         my $so_id;
    1103         my $instances;
    1104         # get so_id
    1105         {
    1106             my $query = $db->prepare_cached( $sql->get_object_from_uri );
    1107             my $rows = $query->execute( $uri );
    1108 
    1109             unless ( $rows > 0 ) {
     1157TRANS: while (1) {
     1158        eval {
     1159            my $so_id;
     1160            my $instances;
     1161            # get so_id
     1162            {
     1163                my $query = $db->prepare_cached( $sql->get_object_from_uri );
     1164                my $rows = $query->execute( $uri );
     1165
     1166                unless ( $rows > 0 ) {
     1167                    $query->finish;
     1168                    $log->logdie( "no instance is associated with uri" );
     1169                }
     1170
     1171                $so_id = $query->fetchrow_hashref->{ 'so_id' };
    11101172                $query->finish;
    1111                 $log->logdie( "no instance is associated with uri" );
    1112             }
    1113 
    1114             $so_id = $query->fetchrow_hashref->{ 'so_id' };
    1115             $query->finish;
    1116 
    1117         }
    1118 
    1119         {
    1120             my $query = $db->prepare_cached( $sql->get_instance_count );
    1121             $query->execute( $so_id );
    1122 
    1123             $instances = $query->fetchrow_hashref->{ 'count(ins_id)' };
    1124             $query->finish;
    1125         }
    1126 
    1127         # remove instance
    1128         {
    1129             my $query = $db->prepare_cached( $sql->delete_instance );
    1130             my $rows = $query->execute( $uri );
    1131             $query->finish;
    1132            
    1133             # if we affected something other then two rows something very bad
    1134             # has happened
    1135             unless ( $rows == 1 ) {
    1136                 $log->logdie( "affected row count is $rows instead of 1" );
    1137             }
    1138         }
    1139 
    1140         # if we just deleted the last instance associated with a storage object
    1141         # remove it too
    1142         if ( $instances == 1 ) {
    1143             # we just removed the last instance
    1144             my $query = $db->prepare_cached( $sql->delete_object );
    1145             my $rows = $query->execute( $so_id );
    1146             $query->finish;
    1147 
    1148             # TODO: this will have to be changed in order to support hardlinks
    1149             unless ( $rows == 1 ) {
    1150                 $log->logdie( "affected row count is $rows instead of 2" );
    1151             }
    1152         }
    1153 
    1154         $db->commit;
    1155         $log->debug("commit");
    1156     };
    1157     if ( $@ ) {
    1158         $db->rollback;
    1159         $log->debug("rollback");
    1160         $log->logdie( "database error: $@" );
     1173
     1174            }
     1175
     1176            {
     1177                my $query = $db->prepare_cached( $sql->get_instance_count );
     1178                $query->execute( $so_id );
     1179
     1180                $instances = $query->fetchrow_hashref->{ 'count(ins_id)' };
     1181                $query->finish;
     1182            }
     1183
     1184            # remove instance
     1185            {
     1186                my $query = $db->prepare_cached( $sql->delete_instance );
     1187                my $rows = $query->execute( $uri );
     1188                $query->finish;
     1189               
     1190                # if we affected something other then two rows something very bad
     1191                # has happened
     1192                unless ( $rows == 1 ) {
     1193                    $log->logdie( "affected row count is $rows instead of 1" );
     1194                }
     1195            }
     1196
     1197            # if we just deleted the last instance associated with a storage object
     1198            # remove it too
     1199            if ( $instances == 1 ) {
     1200                # we just removed the last instance
     1201                my $query = $db->prepare_cached( $sql->delete_object );
     1202                my $rows = $query->execute( $so_id );
     1203                $query->finish;
     1204
     1205                # TODO: this will have to be changed in order to support hardlinks
     1206                unless ( $rows == 1 ) {
     1207                    $log->logdie( "affected row count is $rows instead of 2" );
     1208                }
     1209            }
     1210
     1211            $db->commit;
     1212            $log->debug("commit");
     1213        };
     1214        if ( $@ ) {
     1215            $db->rollback;
     1216            $log->debug("rollback");
     1217            if ($@ =~ /Deadlock found/) {
     1218                $log->warn("database deadlock retrying transaction: $@");
     1219                redo TRANS;
     1220            }
     1221            $log->logdie( "database error: $@" );
     1222        }
     1223        last;
    11611224    }
    11621225
  • branches/cnb_branches/cnb_branch_20090301/Nebulous/scripts/stats.pl

    r23352 r23594  
    3333        my $stat = Statistics::Descriptive::Sparse->new();
    3434        $stat->add_data(@$duration);
    35         printf("%-40s %f\n", "$method: mean duration: ", $stat->mean());
     35        printf("%-40s : %f\n", "$method - mean duration", $stat->mean());
    3636    }
    3737    {
     
    4040        $stat->add_data(@$times);
    4141        $total_stat->add_data(@$times);
    42         printf("%-40s %f\n","$method: calls/s: ", $stat->count / ($stat->max - $stat->min));
     42        printf("%-40s : %f\n","$method - calls/s", $stat->count / ($stat->max - $stat->min));
    4343    }
    4444}
    4545
    46 print "max : ", $total_stat->max, "\n";
    47 print "min : ", $total_stat->min, "\n";
    48 print "total s : ", ($total_stat->max - $total_stat->min), "\n";
    49 print "count : ", $total_stat->count, "\n";
    50 print "total : calls/s: ", $total_stat->count / ($total_stat->max - $total_stat->min), "\n";
     46print "\n";
     47printf("%-40s : %f\n", "first timestamp", $total_stat->min);
     48printf("%-40s : %f\n", "last timestamp", $total_stat->max);
     49printf("%-40s : %f\n", "total wallclock seconds", ($total_stat->max - $total_stat->min));
     50printf("%-40s : %f\n", "total call count", $total_stat->count);
     51printf("%-40s : %f\n", "total calls/s:", $total_stat->count / ($total_stat->max - $total_stat->min));
  • branches/cnb_branches/cnb_branch_20090301/Ohana

  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/libohana/src/IOBufferOps.c

    r17483 r23594  
    2727int ReadtoIOBuffer (IOBuffer *buffer, int fd) {
    2828
    29   int Nread, Nfree;
     29  int Nread, Nfree, Nwant;
    3030
    3131  if (fd == 0) {
     
    3434  }
    3535
     36  // if we run out of space, double Nblock
    3637  Nfree = buffer[0].Nalloc - buffer[0].Nbuffer;
    3738  if (Nfree < buffer[0].Nblock) {
     
    4445  }
    4546
    46   Nread = read (fd, &buffer[0].buffer[buffer[0].Nbuffer], buffer[0].Nblock);
    47   if (DEBUG) fprintf (stderr, "read IO buffer: (%lx) %d from %d\n", (unsigned long) buffer, Nread, buffer[0].Nblock);
     47  // ensure we never read more than space available
     48  Nwant = MIN (Nfree, buffer[0].Nblock);
     49  Nread = read (fd, &buffer[0].buffer[buffer[0].Nbuffer], Nwant);
     50  if (DEBUG) fprintf (stderr, "read IO buffer: (%lx) %d from %d\n", (unsigned long) buffer, Nread, Nwant);
    4851
    4952  /* on success, increase the block size for the next read */
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/cmd.basic/break.c

    r7917 r23594  
    88    remove_argument (N, &argc, argv);
    99    value = -1;
    10     if (!strcasecmp (argv[N], "on")) value = TRUE;
    11     if (!strcasecmp (argv[N], "off")) value = FALSE;
     10    if (!strcasecmp (argv[N], "on")) value = 1;
     11    if (!strcasecmp (argv[N], "off")) value = 0;
    1212    if (value == -1) {
    1313      gprint (GP_ERR, "USAGE: break -auto [on / off]\n");
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/cmd.basic/run_if.c

    r16462 r23594  
    113113        status = multicommand (input);
    114114        if (ThisList == 0) add_history (input);
    115         if (auto_break && !status) return (FALSE);
     115        if (auto_break && !status) {
     116          free (input);
     117          return (FALSE);
     118        }
    116119      }
    117120    }
  • 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/include/pantasks.h

    r21153 r23594  
    244244int CheckControllerOutput (void);
    245245int PrintControllerOutput (void);
     246void PrintControllerBusyJobs ();
    246247
    247248int AddHost (char *hostname, int max_threads);
     
    260261
    261262// functions related to the server threads
     263void *CheckJobsAndTasksThread (void *data);
     264
    262265void CheckTasksSetState (int state);
    263266int CheckTasksGetState (void);
    264 void *CheckTasksThread (void *data);
    265267
    266268void CheckJobsSetState (int state);
    267269int CheckJobsGetState (void);
    268 void *CheckJobsThread (void *data);
     270
     271// void *CheckTasksThread (void *data);
     272// void *CheckJobsThread (void *data);
    269273
    270274void CheckControllerSetState (int state);
     
    283287void CheckInputs (void);
    284288
    285 void SerialThreadLock (void);
    286 void SerialThreadUnlock (void);
     289void ClientThreadLock (void);
     290void ClientThreadUnlock (void);
     291void CommandThreadLock (void);
     292void CommandThreadUnlock (void);
     293void ControlThreadLock (void);
     294void ControlThreadUnlock (void);
     295void JobTaskThreadLock (void);
     296void JobTaskThreadUnlock (void);
    287297
    288298int InitPassword (void);
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/include/shell.h

    r21153 r23594  
    166166int           gprint                    PROTO((gpDest dest, char *format, ...));
    167167int           gwrite                    PROTO((char *buffer, int size, int N, gpDest dest));
     168int           gprint_syserror           PROTO((gpDest dest, int myError, char *format, ...));
     169int           gprintv                   PROTO((gpDest dest, char *format, va_list argp));
    168170
    169171/* socket functions */
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/lib.shell/SocketOps.c

    r21041 r23594  
    55# define DEBUG 0
    66
     7// these three static variables are only modified in the setup command before
     8// the threads are started.  Thread-safety is not a problem for these.
    79static int NVALID;
    810static int Nvalid;
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/lib.shell/gprint.c

    r22423 r23594  
    287287
    288288  int status;
    289   gpStream *stream;
    290289  va_list argp; 
    291290
     291  va_start (argp, format);
     292  status = gprintv (dest, format, argp);
     293  va_end (argp);
     294  return (status);
     295}
     296
     297int gprintv (gpDest dest, char *format, va_list argp) {
     298
     299  int status;
     300  gpStream *stream;
     301
    292302  // this thread only writes to its own stream
    293303  stream = gprintGetStream (dest);
    294 
    295   va_start (argp, format);
    296304
    297305  if (stream[0].mode == GP_FILE) {
     
    303311    vPrintIOBuffer (stream[0].buffer, format, argp);
    304312  }
    305   va_end (argp);
    306313  return (TRUE);
    307314}
     
    332339}
    333340
    334 /* I'm going to need to have different output targets for different threads
    335    we can do this with these functions:
    336 
    337    pthread_t pthread_self(void);
    338    int pthread_equal(pthread_t thread1, pthread_t thread2);
    339    // returns TRUE if equal, FALSE if not
    340    
    341 */
    342 
     341# define MAX_ERROR_LENGTH 256           // Maximum length string for error messages
     342
     343// print an error (based on errno values) to gprint destination
     344int gprint_syserror (gpDest dest, int myError, char *format, ...) {
     345
     346  char errorBuf[MAX_ERROR_LENGTH];
     347  char *errorMsg;
     348  va_list argp; 
     349
     350  // there are two strerror_r implementations; choose the right one:
     351#if ((_POSIX_C_SOURCE >= 200112L || _XOPEN_SOURCE >= 600) && ! _GNU_SOURCE)
     352  errorMsg = strerror_r (myError, errorBuf, MAX_ERROR_LENGTH);
     353#else
     354  strerror_r (myError, errorBuf, MAX_ERROR_LENGTH);
     355  errorMsg = errorBuf;
     356#endif
     357
     358  va_start (argp, format);
     359  gprintv (dest, format, argp);
     360  va_end (argp);
     361
     362  gprintv (dest, "%s\n", errorMsg);
     363  return TRUE;
     364}
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/CheckController.c

    r14590 r23594  
    11# include "pantasks.h"
    22
    3 static struct timeval start;
    4 void TimerMark ();
    5 float TimerElapsed (int reset);
     3void TimerMark (struct timeval *start);
     4float TimerElapsed (struct timeval *start, int reset);
    65
    76int CheckController () {
     
    1110  Job *job;
    1211  IOBuffer buffer;
     12  struct timeval start;
    1313
    1414  /* get the list of completed jobs (exit / crash), update the job status */
     
    1717  /*** check EXIT jobs ***/
    1818  InitIOBuffer (&buffer, 0x100);
    19   // TimerMark ();
    20   // status = ControllerCommand ("stop", CONTROLLER_PROMPT, &buffer);
    21   // if (VerboseMode()) gprint (GP_ERR, "stop controller %f\n", TimerElapsed(TRUE));
    2219
    23   TimerMark ();
     20  TimerMark (&start);
    2421  FlushIOBuffer (&buffer);
     22
    2523  status = ControllerCommand ("jobstack exit", CONTROLLER_PROMPT, &buffer);
    26   if (VerboseMode()) gprint (GP_ERR, "check exit stack %f\n", TimerElapsed(TRUE));
     24  if (VerboseMode()) gprint (GP_ERR, "check exit stack %f\n", TimerElapsed(&start, TRUE));
    2725  if (!status) goto escape;
    2826
     
    3432  status = sscanf (buffer.buffer, "%*s %d", &Njobs);
    3533  if (status != 1) goto escape;
    36   if (VerboseMode()) gprint (GP_ERR, "parse %d jobs on stack %f\n", Njobs, TimerElapsed(TRUE));
     34  if (VerboseMode()) gprint (GP_ERR, "parse %d jobs on stack %f\n", Njobs, TimerElapsed(&start, TRUE));
    3735
    3836  p = buffer.buffer;
     
    4644    status = sscanf (p, "%d", &JobID);
    4745
     46    // the operations within this locked block only interact with the controller or
     47    // modify the properties of the selected job
     48    JobTaskLock();
    4849    job = FindControllerJob (JobID);
    4950    if (job == NULL) {
    5051      gprint (GP_ERR, "misplaced job? %d not in EXIT job list\n", JobID);
     52      JobTaskUnlock();
    5153      continue;
    5254    }
    5355    /* this checks the individual job status, grabs stdout/stderr */
    5456    CheckControllerJob (job);
     57    JobTaskUnlock();
    5558  }
    56   if (VerboseMode()) gprint (GP_ERR, "clear %d exit jobs %f\n", i, TimerElapsed(TRUE));
     59  if (VerboseMode()) gprint (GP_ERR, "clear %d exit jobs %f\n", i, TimerElapsed(&start, TRUE));
    5760
    5861  /*** check CRASH jobs ***/
     
    6770  status = sscanf (buffer.buffer, "%*s %d", &Njobs);
    6871  if (status != 1) goto escape;
    69   if (VerboseMode()) gprint (GP_ERR, "check crash stack %f\n", TimerElapsed(TRUE));
     72  if (VerboseMode()) gprint (GP_ERR, "check crash stack %f\n", TimerElapsed(&start, TRUE));
    7073
    7174  p = buffer.buffer;
     
    7780    }
    7881    p = q + 1;
    79    
    8082    status = sscanf (p, "%d", &JobID);
     83
     84    // the operations within this locked block only interact with the controller or
     85    // modify the properties of the selected job
     86    JobTaskLock();
    8187    job = FindControllerJob (JobID);
    8288    if (job == NULL) {
    8389      gprint (GP_ERR, "misplaced job? %d not in CRASH job list\n", JobID);
     90      JobTaskUnlock();
    8491      continue;
    8592    }
    8693    /* this checks the individual job status, grabs stdout/stderr */
    8794    CheckControllerJob (job);
     95    JobTaskUnlock();
    8896  }
    89   if (VerboseMode()) gprint (GP_ERR, "clear %d crash jobs %f\n", i, TimerElapsed(TRUE));
     97  if (VerboseMode()) gprint (GP_ERR, "clear %d crash jobs %f\n", i, TimerElapsed(&start, TRUE));
    9098
    9199  FlushIOBuffer (&buffer);
    92   // status = ControllerCommand ("run", CONTROLLER_PROMPT, &buffer);
    93100  FreeIOBuffer (&buffer);
    94101  return (TRUE);
     
    96103 escape:
    97104  FlushIOBuffer (&buffer);
    98   // status = ControllerCommand ("run", CONTROLLER_PROMPT, &buffer);
    99105  FreeIOBuffer (&buffer);
    100106  return (FALSE);
    101107}
    102108
    103 void TimerMark () {
    104     gettimeofday (&start, (void *) NULL);
     109void TimerMark (struct timeval *start) {
     110    gettimeofday (start, (void *) NULL);
    105111}
    106112
    107 float TimerElapsed (int reset) {
     113float TimerElapsed (struct timeval *start, int reset) {
    108114
    109115  float dtime;
     
    111117
    112118  gettimeofday (&stop, (void *) NULL);
    113   dtime = DTIME (stop, start);
    114   if (reset) gettimeofday (&start, (void *) NULL);
     119  dtime = DTIME (stop, start[0]);
     120  if (reset) gettimeofday (start, (void *) NULL);
    115121  return (dtime);
    116122}
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/CheckJobs.c

    r15871 r23594  
    1818  next_timeout = 1.0;
    1919
     20  JobTaskLock();
    2021  /** test all jobs: ready to test?  finished? **/
    2122  while ((job = NextJob ()) != NULL) {
     
    7778        /* set taskarg variables */
    7879        for (i = 0; i < job[0].argc; i++) {
    79             sprintf (varname, "taskarg:%d", i);
    80             set_str_variable (varname, job[0].argv[i]);
     80          sprintf (varname, "taskarg:%d", i);
     81          set_str_variable (varname, job[0].argv[i]);
    8182        }
    8283        set_int_variable ("taskarg:n", job[0].argc);
     
    8485        /* set options variables */
    8586        for (i = 0; i < job[0].optc; i++) {
    86             sprintf (varname, "options:%d", i);
    87             set_str_variable (varname, job[0].optv[i]);
     87          sprintf (varname, "options:%d", i);
     88          set_str_variable (varname, job[0].optv[i]);
    8889        }
    8990        set_int_variable ("options:n", job[0].optc);
     
    109110          if (VerboseMode()) gprint (GP_LOG, "job %s (%d) crash\n", task[0].name, job[0].JobID);
    110111          if (task[0].crash != NULL) {
     112            // we need to unlock JobTask since JobTaskLock is called inside CommandLock in the client thread
     113            JobTaskUnlock();
     114            CommandLock();
    111115            exec_loop (task[0].crash);
     116            CommandUnlock();
     117            JobTaskLock();
    112118          }
    113119        }
     
    133139            }
    134140          }
    135           if (macro != NULL) exec_loop (macro);
     141          if (macro != NULL) {
     142            // we need to unlock JobTask since JobTaskLock is called inside CommandLock in the client thread
     143            JobTaskUnlock();
     144            CommandLock();
     145            exec_loop (macro);
     146            CommandUnlock();
     147            JobTaskLock();
     148          }
    136149        }
    137150
     
    146159        DeleteJob (job);
    147160        continue;
    148         break;
    149161
    150162      default:
     
    156168    /* check for timeout - (local jobs only)
    157169       we only check timeout after a poll (forces at least one poll)
    158      */
     170    */
    159171    if (job[0].mode == JOB_LOCAL) {
    160172      if (GetTaskTimer(job[0].start, FALSE) < task[0].timeout_period) {
     
    179191      /* set taskarg variables */
    180192      for (i = 0; i < job[0].argc; i++) {
    181           sprintf (varname, "taskarg:%d", i);
    182           set_str_variable (varname, job[0].argv[i]);
     193        sprintf (varname, "taskarg:%d", i);
     194        set_str_variable (varname, job[0].argv[i]);
    183195      }
    184196      set_int_variable ("taskarg:n", job[0].argc);
     
    193205      /* run task[0].timeout macro, if it exists */
    194206      if (task[0].timeout != NULL) {
     207        // we need to unlock JobTask since JobTaskLock is called inside CommandLock in the client thread
     208        JobTaskUnlock();
     209        CommandLock();
    195210        exec_loop (task[0].timeout);
     211        CommandUnlock();
     212        JobTaskLock();
    196213      }
    197214
     
    205222  }
    206223  // fprintf (stderr, "check %d jobs\n", Ncheck);
     224  JobTaskUnlock();
    207225  return (next_timeout);
    208226}
     
    210228/*
    211229
    212   job / task timeline:
    213 
    214   task:
    215   0           exec     
    216   start       create
    217   task clock  new job
    218 
    219   job:
    220   0           1xpoll     2xpoll     3xpoll
    221   start       check      check      check
    222   job clock   status     status     status
    223 
    224   .           .          .          timeout
    225                                     run
    226                                     timeout
    227 
    228   must be at least one poll before timeout
    229   (timeout >= poll)
     230   job / task timeline:
     231
     232   task:
     233   0           exec     
     234   start       create
     235   task clock  new job
     236
     237   job:
     238   0           1xpoll     2xpoll     3xpoll
     239   start       check      check      check
     240   job clock   status     status     status
     241
     242   .           .          .          timeout
     243   run
     244   timeout
     245
     246   must be at least one poll before timeout
     247   (timeout >= poll)
    230248*/
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/CheckPassword.c

    r8548 r23594  
    22# define DEBUG 0
    33
     4// this static var is only used by InitPassword and CheckPassword below.
     5// Both functions are only called by the main thread.
    46static char PASSWORD[256];
    57
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/CheckTasks.c

    r23352 r23594  
    77  int status;
    88  float time_running, next_timeout, fuzz;
    9   // struct timeval now;
    109
    1110  // actual maximum delay is controlled in job_threads.c
    1211  next_timeout = 1.0;
    1312
     13  JobTaskLock();
    1414  /** test all tasks: ready to test? ready to run? **/
    1515  while ((task = NextTask ()) != NULL) {
     
    4848    // add random offset between 0 and 5% of exec_period
    4949    // XXX this should be optional
    50     fuzz = 0.1*task[0].exec_period*drand48();
     50    fuzz = task[0].exec_period*(0.5*drand48() - 0.25);
    5151    task[0].last.tv_usec = 1e6*(fuzz - (int)fuzz);
    5252    task[0].last.tv_sec += (int) fuzz;
     
    5454    /* ready to run? : run task.exec macro */
    5555    if (task[0].exec != NULL) {
     56      // we need to unlock JobTask since JobTaskLock is called inside CommandLock in the client thread
     57      JobTaskUnlock();
     58      CommandLock();
    5659      status = exec_loop (task[0].exec);
     60      CommandUnlock();
     61      JobTaskLock();
    5762      if (!status) {
    5863        continue;
    5964      }
    6065    }
    61 
    62     // gettimeofday (&now, (void *) NULL);
    63     // fprintf (stderr, "t1: %d %6d  - \n", now.tv_sec, now.tv_usec);
    6466
    6567    /* check if there are errors with this task */
     
    6870    }
    6971   
    70     // gettimeofday (&now, (void *) NULL);
    71     // fprintf (stderr, "t2: %d %6d  - \n", now.tv_sec, now.tv_usec);
    72 
    7372    /* construct job from task */
    7473    job = CreateJob (task);
     74    if (!job) {
     75      continue;
     76    }
     77
    7578    if (DEBUG) fprintf (stderr, "create job: (%zx) %d of %d\n", (size_t) job[0].stdout_buff.buffer, job[0].stdout_buff.Nbuffer, job[0].stdout_buff.Nalloc);
    7679
    77     // gettimeofday (&now, (void *) NULL);
    78     // fprintf (stderr, "t3: %d %6d  - \n", now.tv_sec, now.tv_usec);
    79 
    80     /* execute job - XXX add status test */
    81     SubmitJob (job);
    82 
    83     // fprintf (stderr, "nl: %d %6d  - ",
    84     // task[0].last.tv_sec, task[0].last.tv_usec);
    85 
    86     /* increment job counters */
    87     task[0].Njobs ++;
    88     task[0].Npending ++;
    89 
    90     // fprintf (stderr, "%d %6d\n",
    91     // task[0].last.tv_sec, task[0].last.tv_usec);
     80    /* execute job */
     81    if (!SubmitJob (job)) {
     82      DeleteJob (job);
     83      continue;
     84    }
     85    task[0].Njobs ++; // number of jobs successfully submitted
    9286
    9387    /* increment Nrun for inclusive ranges with Nmax */
    9488    BumpTimeRanges (task[0].ranges, task[0].Nranges);
    9589  }
     90  JobTaskUnlock();
    9691  return (next_timeout);
    9792}
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/ControllerOps.c

    r20032 r23594  
    1212
    1313/* local static variables to track the controller host properties */
     14/* these are used by AddHost and DeleteHost, and are only called by controller_host.c (clientThread) */
     15/* or by RestartController : lock between these two? */
    1416static Host *hosts = NULL;
    1517static int Nhosts = 0;
     
    3133}
    3234
     35// XXX possible race condition problem: if we delete a host while the controller
     36// is being restarted.  to fix this, we need to keep the deletion in controller_thread,
     37// but perhaps mark it in the client_thread?
    3338int DeleteHost (char *hostname) {
    3439
     
    261266  }
    262267
     268  // This function is called by the JobTaskThread via SubmitJob.  We need to unlock the
     269  // JobTaskLock to avoid a dead lock with the JobTaskLock called in CheckController
     270  JobTaskUnlock();
     271  ControlLock(__func__);
    263272  InitIOBuffer (&buffer, 0x100);
    264273  status = ControllerCommand (cmd, CONTROLLER_PROMPT, &buffer);
    265274  free (cmd);
     275  ControlUnlock(__func__);
     276  JobTaskLock();
     277
    266278
    267279  /* extract the job PID from the controller response */
     
    274286  }
    275287  sscanf (p, "%*s %s", string);
     288  FreeIOBuffer (&buffer);
     289
    276290  job[0].pid = atoi (string);
    277   FreeIOBuffer (&buffer);
     291  if (job[0].pid < 0) {
     292    return (FALSE);
     293  }
    278294  return (TRUE);
    279295}
     
    411427  if ((status == -1) && (errno == EPIPE)) {
    412428    StopController ();
    413     gprint (GP_ERR, "controller is down (pipe closed), restarting\n");
     429    fprintf (stderr, "controller is down (pipe closed), restarting\n");
    414430    if (!RestartController ()) {
    415431      return (FALSE);
     
    434450    if (status ==  0) {
    435451      StopController ();
    436       gprint (GP_ERR, "controller is down (EOF), restarting\n");
     452      fprintf (stderr, "controller is down (EOF), restarting\n");
    437453      if (!RestartController ()) {
    438454        return (FALSE);
     
    441457    }
    442458    if (status == -1) {
    443       gprint (GP_ERR, "controller is not responding (%d tries)\n", j);
     459      fprintf (stderr, "controller is not responding (%d tries)\n", j);
    444460      gwrite (buffer[0].buffer, 1, buffer[0].Nbuffer, GP_ERR);
    445461    }
    446462  }
    447463  if (status == -1) {
    448     gprint (GP_ERR, "controller still not responding, giving up\n");
     464    fprintf (stderr, "controller still not responding, giving up\n");
    449465    return (FALSE);
    450466  }
     
    456472    bzero (buffer[0].buffer + buffer[0].Nbuffer, buffer[0].Nalloc - buffer[0].Nbuffer);
    457473  }
    458   /* if (VerboseMode()) gprint (GP_ERR, "message received, %d cycles\n", i); */
     474  if (VerboseMode()) fprintf (stderr, "message received, %d cycles\n", i);
    459475  return (TRUE);
    460476}
     
    492508}
    493509
     510void PrintControllerBusyJobs () {
     511
     512  int status;
     513  char command[1024];
     514  IOBuffer buffer;
     515
     516  /* check if controller is running */
     517  status = CheckControllerStatus ();
     518  if (!status) {
     519    return;
     520  }
     521
     522  sprintf (command, "jobstack busy");
     523  InitIOBuffer (&buffer, 0x100);
     524
     525  status = ControllerCommand (command, CONTROLLER_PROMPT, &buffer);
     526
     527  if (status) {
     528    gprint (GP_LOG, " jobs currently running remotely:\n");
     529    gwrite (buffer.buffer, 1, buffer.Nbuffer, GP_LOG);
     530  } else {
     531    gprint (GP_LOG, "controller is not responding\n");
     532  }
     533  FreeIOBuffer (&buffer);
     534  return;
     535}
     536
    494537int PrintControllerOutput () {
    495538
     
    581624  InitIOBuffer (&buffer, 0x100);
    582625
    583   // XXX lock the host table? SerialThreadLock ();
     626  // XXX lock the host table? no: that would risk a dead lock between client and controller threads:
    584627  gprint (GP_ERR, "pcontrol restarted, reloading hosts\n");
    585628  for (i = 0; i < Nhosts; i++) {
     
    588631    status = ControllerCommand (command, CONTROLLER_PROMPT, &buffer);
    589632  }
    590   // SerialThreadUnlock ();
    591633
    592634  if (status) gwrite (buffer.buffer, 1, buffer.Nbuffer, GP_LOG);
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/InputQueue.c

    r16449 r23594  
    11# include "pantasks.h"
     2// we use fprintf for DEBUG statements to avoid deadlocking issues
    23
    34static int Ninputs = 0;
     
    2324void AddNewInput (char *input) {
    2425
     26  // XXX define the InputMutex
    2527  SerialThreadLock ();
    26   if (DEBUG) gprint (GP_LOG, "adding a new input (%s)\n", input);
     28
     29  if (DEBUG) fprintf (stderr, "adding a new input (%s)\n", input);
    2730  inputs[Ninputs] = input;
    2831  Ninputs ++;
     
    3134    REALLOCATE (inputs, char *, NINPUTS);
    3235  }
    33   if (DEBUG) gprint (GP_LOG, "done new input (%s)\n", input);
     36  if (DEBUG) fprintf (stderr, "done new input (%s)\n", input);
    3437  SerialThreadUnlock ();
    3538}
     
    4043  int i, j;
    4144
    42   if (DEBUG) gprint (GP_LOG, "deleting an input (%s)\n", input);
     45  if (DEBUG) fprintf (stderr, "deleting an input (%s)\n", input);
     46
     47  // XXX lock here
    4348  for (i = 0; i < Ninputs; i++) {
    4449    if (inputs[i] == input) {
     
    5257        REALLOCATE (inputs, char *, NINPUTS);
    5358      }
    54       if (DEBUG) gprint (GP_LOG, "deleted an input\n");
     59      // XXX unlock here
     60      if (DEBUG) fprintf (stderr, "deleted an input\n");
    5561      return TRUE;
    5662    }
    5763  }
    5864  // did not find the input
     65  // XXX unlock here
    5966  return FALSE;
    6067}
     
    6673  char *input, *line, *outline, tmp;
    6774
    68   if (Ninputs < 1) return;
     75  // XXX lock here
     76  if (Ninputs < 1) {
     77    // XXX unlock here
     78    return;
     79  }
    6980
    7081  input = inputs[0];
    71   if (DEBUG) gprint (GP_LOG, "got an input (%s)\n", input);
     82  if (DEBUG) fprintf (stderr, "got an input (%s)\n", input);
    7283 
    7384  Nbytes = snprintf (&tmp, 0, "input %s", input);
    7485  ALLOCATE (line, char, Nbytes + 1);
    7586  snprintf (line, Nbytes + 1, "input %s", input);
     87  // XXX unlock here
    7688
    7789  status = command (line, &outline, TRUE);
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/JobIDOps.c

    r17419 r23594  
    11# include "pantasks.h"
    22
    3 # define MAX_N_JOBS 1000
     3# define MAX_N_JOBS 10000
    44static char *JobIDList;
    55static int   JobIDPtr;
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/JobOps.c

    r18160 r23594  
    8888  }
    8989
    90   /* check if controller is running */
    91   status = CheckControllerStatus ();
    92   if (!status) {
    93     return;
    94   }
    95 
    96   sprintf (command, "jobstack busy");
    97   InitIOBuffer (&buffer, 0x100);
    98 
    99   SerialThreadLock ();
    100   status = ControllerCommand (command, CONTROLLER_PROMPT, &buffer);
    101   SerialThreadUnlock ();
    102 
    103   if (status) {
    104     gprint (GP_LOG, " jobs currently running remotely:\n");
    105     gwrite (buffer.buffer, 1, buffer.Nbuffer, GP_LOG);
    106   } else {
    107     gprint (GP_LOG, "controller is not responding\n");
    108   }
    109   FreeIOBuffer (&buffer);
    11090  return;
    11191}
     
    120100
    121101  job[0].JobID = NextJobID ();
     102  if (job[0].JobID < 0) {
     103    free (job);
     104    return NULL;
     105  }
     106
    122107  job[0].pid = 0;
    123108  job[0].mode = JOB_LOCAL;
     
    169154    REALLOCATE (jobs, Job *, NJOBS);
    170155  }
     156
     157  /* increment job counters */
     158  task[0].Npending ++;
     159
    171160  return (jobs[Njobs-1]);
    172161}
     
    265254int SubmitJob (Job *job) {
    266255
     256  int status;
     257
    267258  if (job[0].mode == JOB_LOCAL) {
    268259    if (DEBUG) fprintf (stderr, "submit job: (%zx) %d of %d\n", (size_t) job[0].stdout_buff.buffer, job[0].stdout_buff.Nbuffer, job[0].stdout_buff.Nalloc);
    269     SubmitLocalJob (job);
     260    status = SubmitLocalJob (job);
    270261  } else {
    271     SubmitControllerJob (job);
     262    status = SubmitControllerJob (job);
     263  }
     264  if (!status) {
     265    return FALSE;
    272266  }
    273267
     
    285279  if (job[0].mode == JOB_LOCAL) {
    286280    CheckLocalJob (job);
    287   } else {
    288     /* controller jobs are now checked en masse by CheckController */
    289     /* CheckControllerJob (job); */
     281    /* controller jobs are checked en masse by CheckController */
    290282  }
    291283  return (job[0].state);
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/ListenClients.c

    r16905 r23594  
    22# define DEBUG 0
    33
     4// XXX make the calling functions thread-safe
    45static int NCLIENTS;
    56static int Nclients;
     
    910void InitClients () {
    1011
     12  ClientLock();
    1113  Nclients = 0;
    1214  NCLIENTS = 10;
    1315  ALLOCATE (clients, int, NCLIENTS);
    1416  ALLOCATE (buffers, IOBuffer *, NCLIENTS);
     17  ClientUnlock();
    1518}
    1619
     
    1821void AddNewClient (int client) {
    1922
    20   if (DEBUG) gprint (GP_LOG, "adding a new client (%d)\n", client);
     23  ClientLock();
     24  if (DEBUG) fprintf (stderr, "adding a new client (%d)\n", client);
    2125  clients[Nclients] = client;
    2226  ALLOCATE (buffers[Nclients], IOBuffer, 1);
     
    2832    REALLOCATE (buffers, IOBuffer *, NCLIENTS);
    2933  }
     34  ClientUnlock();
    3035}
    3136
     
    3540  int i, j;
    3641
    37   if (DEBUG) gprint (GP_LOG, "deleting a client (%d)\n", client);
     42  ClientLock();
     43  if (DEBUG) fprintf (stderr, "deleting a client (%d)\n", client);
    3844  for (i = 0; i < Nclients; i++) {
    3945    if (clients[i] == client) {
     
    5157        REALLOCATE (buffers, IOBuffer *, NCLIENTS);
    5258      }
     59      ClientUnlock();
    5360      return TRUE;
    5461    }
    5562  }
    5663  // did not find the client
     64  ClientUnlock();
    5765  return FALSE;
    5866}
     
    7078  gprintInit ();  // each thread needs to init the printing system
    7179
    72   // define server output log files
    73   if (VarConfig ("PANTASKS_SERVER_STDOUT", "%s", log_stdout) != NULL) {
    74     gprintSetFileThisThread (GP_LOG, log_stdout);
    75   } else {
    76     strcpy (log_stdout, "stdout");
    77   }
    78   if (VarConfig ("PANTASKS_SERVER_STDERR", "%s", log_stderr) != NULL) {
    79     gprintSetFileThisThread (GP_ERR, log_stderr);
    80   } else {
    81     strcpy (log_stderr, "stderr");
    82   }
     80  /* set buffers for the output for this client */
     81  gprintSetBuffer (GP_LOG);
     82  gprintSetBuffer (GP_ERR);
    8383
    8484  while (1) {
     
    9090
    9191    /* place all of the clients in the fdSet */
    92     Ncurrent = Nclients;
    9392    Nmax = 0;
    9493    FD_ZERO (&fdSet);
     94    ClientLock();
     95    Ncurrent = Nclients;
     96    ClientUnlock();
    9597    for (i = 0; i < Ncurrent; i++) {
    9698      Nmax = MAX (Nmax, clients[i]);
     
    100102
    101103    /* block until we have some data on the pipes (or timeout) */
    102     if (DEBUG) gprint (GP_ERR, "listening to %d clients\n", Ncurrent);
     104    if (DEBUG) fprintf (stderr, "listening to %d clients\n", Ncurrent);
    103105    status = select (Nmax, &fdSet, NULL, NULL, &timeout);
    104106    if (status == -1) {
     
    122124      if ((Nread == 0) || (Nread == -2)) {
    123125        /* error: do something */
    124         if (DEBUG && (Nread == 0)) gprint (GP_ERR, "socket is closed\n");
    125         if (DEBUG && (Nread == -2)) gprint (GP_ERR, "error reading from socket\n");
     126        if (DEBUG && (Nread == 0)) fprintf (stderr, "socket is closed\n");
     127        if (DEBUG && (Nread == -2)) fprintf (stderr, "error reading from socket\n");
    126128        DeleteClient (clients[i]);
    127         continue;
     129        break;  // the other thread could also have modified the list; restart with new Ncurrent
    128130      }
    129131
    130       if (DEBUG) gprint (GP_ERR, "read %d total bytes\n", buffers[i][0].Nbuffer);
     132      if (DEBUG) fprintf (stderr, "read %d total bytes\n", buffers[i][0].Nbuffer);
    131133
    132134      /* see if we have a complete message waiting; if not, keep waiting for messages */
     
    141143      if (*line) {
    142144
    143         /* set buffers for the output for this client */
    144         gprintSetBuffer (GP_LOG);
    145         gprintSetBuffer (GP_ERR);
    146 
    147145        /* run the command, return the exit status */
     146        CommandLock();
    148147        status = multicommand (line);
     148        CommandUnlock();
    149149        SendMessage (clients[i], "STATUS %d", status);
    150150
     
    156156          SendMessageFixed (clients[i], 0, "");
    157157        }         
     158        FlushIOBuffer (outbuffer);
    158159
    159160        // return the stdout messages first
     
    164165          SendMessageFixed (clients[i], 0, "");
    165166        }         
    166        
    167         /* clear and reset the output buffers to their last output file names */
    168         gprintSetFileAllThreads (GP_LOG, NULL);
    169         gprintSetFileAllThreads (GP_ERR, NULL);
     167        FlushIOBuffer (outbuffer);
    170168      }
    171169      free (line);
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/LocalJob.c

    r18161 r23594  
    127127
    128128  pid = fork ();
     129  if (pid == -1) {
     130    gprint_syserror (GP_ERR, errno, "error starting local job: ");
     131    goto pipe_error;
     132  }
     133
    129134  if (!pid) { /* must be child process */
    130135    if (VerboseMode()) gprint (GP_ERR, "starting local job\n");
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/Makefile

    r18085 r23594  
    3434$(SRC)/pantasks.$(ARCH).o \
    3535$(SRC)/thread_locks.$(ARCH).o \
    36 $(SRC)/job_threads.$(ARCH).o \
    37 $(SRC)/task_threads.$(ARCH).o \
     36$(SRC)/jobs_and_tasks_thread.$(ARCH).o \
    3837$(SRC)/controller_threads.$(ARCH).o
    3938
     
    4140$(SRC)/pantasks_server.$(ARCH).o \
    4241$(SRC)/server_run.$(ARCH).o \
    43 $(SRC)/server_load.$(ARCH).o \
    44 $(SRC)/InputQueue.$(ARCH).o \
    4542$(SRC)/ListenClients.$(ARCH).o \
    4643$(SRC)/server.$(ARCH).o \
     
    4946$(SRC)/CheckPassword.$(ARCH).o \
    5047$(SRC)/thread_locks.$(ARCH).o \
    51 $(SRC)/job_threads.$(ARCH).o \
    52 $(SRC)/task_threads.$(ARCH).o \
    53 $(SRC)/controller_threads.$(ARCH).o \
    54 $(SRC)/input_threads.$(ARCH).o
     48$(SRC)/jobs_and_tasks_thread.$(ARCH).o \
     49$(SRC)/controller_threads.$(ARCH).o
    5550
    5651funcs = \
     
    6661
    6762cmds = \
    68 $(SRC)/pulse.$(ARCH).o \
    6963$(SRC)/status.$(ARCH).o \
    7064$(SRC)/flush.$(ARCH).o \
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/controller.c

    r18085 r23594  
    5050  }
    5151
     52  ControlLock(__func__);
    5253  status = (*func)(argc - 1, argv + 1);
     54  ControlUnlock(__func__);
    5355  return (status);
    5456}
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/controller_host.c

    r19125 r23594  
    1515
    1616  if (argc != 3) goto usage;
     17  if (max_threads && strcasecmp (argv[1], "ADD")) goto usage;
    1718
    1819  /* start controller connection (if needed) */
     
    2728  if (!strcasecmp (argv[1], "ADD")) {
    2829    AddHost (argv[2], max_threads);
    29   } else {
    30     if (max_threads) goto usage;
    31   }
     30  }
    3231
    3332  if (!strcasecmp (argv[1], "DELETE")) {
     
    4241  InitIOBuffer (&buffer, 0x100);
    4342
    44   SerialThreadLock ();
    4543  status = ControllerCommand (command, CONTROLLER_PROMPT, &buffer);
    46   SerialThreadUnlock ();
    4744
    4845  if (status) gwrite (buffer.buffer, 1, buffer.Nbuffer, GP_LOG);
     
    5754  return (FALSE);
    5855}
    59 
    60 /* should I keep an internal host table so I can reload the
    61    hosts if the controller exits?
    62 
    63    alternatively, that could be a user-level choice
    64 */
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/controller_jobstack.c

    r18085 r23594  
    2424  InitIOBuffer (&buffer, 0x100);
    2525
    26   SerialThreadLock ();
    2726  status = ControllerCommand (command, CONTROLLER_PROMPT, &buffer);
    28   SerialThreadUnlock ();
    2927
    3028  if (status) {
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/controller_status.c

    r8548 r23594  
    2323  InitIOBuffer (&buffer, 0x100);
    2424
    25   SerialThreadLock ();
    2625  status = ControllerCommand (command, CONTROLLER_PROMPT, &buffer);
    27   SerialThreadUnlock ();
    2826
    2927  if (status) {
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/controller_threads.c

    r15791 r23594  
    3434
    3535    // one run of the task checker
    36     SerialThreadLock ();
     36    ControlLock(__func__);
    3737    CheckController ();
     38    ControlUnlock(__func__);
     39
     40    ControlLock(__func__);
    3841    CheckControllerOutput ();
    39     SerialThreadUnlock ();
     42    ControlUnlock(__func__);
     43
    4044    if (VerboseMode() == 2) fprintf (stderr, "C");
    4145    // fprintf (stderr, "**** C ****");
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/controller_verbose.c

    r18085 r23594  
    2424  InitIOBuffer (&buffer, 0x100);
    2525
    26   SerialThreadLock ();
    2726  status = ControllerCommand (command, CONTROLLER_PROMPT, &buffer);
    28   SerialThreadUnlock ();
    2927
    3028  if (status) {
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/delete.c

    r13542 r23594  
    1111    JobID = atoi (argv[2]);
    1212
     13    JobTaskLock();
    1314    job = FindJob (JobID);
    1415    if (job == NULL) {
    1516      gprint (GP_LOG, "job not found\n");
     17      JobTaskUnlock();
    1618      return (TRUE);
    1719    }
     
    2123        job[0].state = JOB_HUNG;
    2224        if (VerboseMode()) gprint (GP_LOG, "child process %d is hung, cannot kill\n", job[0].pid);
     25        JobTaskUnlock();
    2326        return (FALSE);
    2427      }
     
    2730        job[0].state = JOB_HUNG;
    2831        if (VerboseMode()) gprint (GP_LOG, "child process %d is hung, cannot kill\n", job[0].pid);
     32        JobTaskUnlock();
    2933        return (FALSE);
    3034      }
     
    3236    DeleteJob (job);
    3337    gprint (GP_LOG, "job removed\n");
     38    JobTaskUnlock();
    3439    return (TRUE);
    3540  }
     
    4146
    4247usage:
    43     gprint (GP_ERR, "USAGE: delete job (JobID)\n");
    44     gprint (GP_ERR, "USAGE: delete task (TaskName)\n");
    45     return (FALSE);
     48  gprint (GP_ERR, "USAGE: delete job (JobID)\n");
     49  gprint (GP_ERR, "USAGE: delete task (TaskName)\n");
     50  return (FALSE);
    4651}
    4752
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/flush.c

    r14590 r23594  
    66
    77  if (!strcasecmp (argv[1], "jobs")) {
     8    JobTaskLock();
    89    FlushJobs ();
     10    JobTaskUnlock();
    911    return (TRUE);
    1012  }
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/init.c

    r16453 r23594  
    1818int halt            PROTO((int, char **));
    1919int flush_jobs      PROTO((int, char **));
    20 int pulse           PROTO((int, char **));
    2120int showtask        PROTO((int, char **));
    2221int status_sys      PROTO((int, char **));
     
    4039  {1, "options",    task_options,  "define optional variables associated with the job task"},
    4140  {1, "periods",    task_periods,  "define time scales for a task"},
    42   {1, "pulse",      pulse,         "set the scheduler update period"},
    4341  {1, "run",        run,           "run the scheduler"},
    4442  {1, "flush",      flush_jobs,    "flush all jobs from the queue"},
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/init_server.c

    r16903 r23594  
    1414int task_stdout     PROTO((int, char **));
    1515int task_stderr     PROTO((int, char **));
    16 int pulse           PROTO((int, char **));
    1716int flush_jobs      PROTO((int, char **));
    1817int status_server   PROTO((int, char **));
     
    4140  {1, "npending",   task_npending, "define maximum number of outstanding jobs for a task"},
    4241  {1, "periods",    task_periods,  "define time scales for a task"},
    43   {1, "pulse",      pulse,         "set the scheduler update period"},
    4442  {1, "flush",      flush_jobs,    "flush all jobs from the queue"},
    4543  {1, "server",     server,        "server-specific commands"},
     
    6765  InitJobs ();
    6866  InitJobIDs ();
    69   InitInputs ();
    7067
    7168  for (i = 0; i < sizeof (cmds) / sizeof (Command); i++) {
     
    7875  FreeJobs ();
    7976  FreeJobIDs ();
    80   FreeInputs ();
    8177}
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/kill.c

    r13542 r23594  
    1212  JobID = atoi (argv[1]);
    1313
     14  JobTaskLock();
    1415  job = FindJob (JobID);
    1516  if (job == NULL) {
    1617    gprint (GP_LOG, "job not found\n");
     18    JobTaskUnlock();
    1719    return (TRUE);
    1820  }
     
    2224      job[0].state = JOB_HUNG;
    2325      if (VerboseMode()) gprint (GP_LOG, "child process %d is hung, cannot kill\n", job[0].pid);
     26      JobTaskUnlock();
    2427      return (FALSE);
    2528    }
     
    2831      job[0].state = JOB_HUNG;
    2932      if (VerboseMode()) gprint (GP_LOG, "child process %d is hung, cannot kill\n", job[0].pid);
     33      JobTaskUnlock();
    3034      return (FALSE);
    3135    }
     
    3337  DeleteJob (job);
    3438  gprint (GP_LOG, "job removed\n");
     39  JobTaskUnlock();
    3540  return (TRUE);
    3641}
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/notes.txt

    r7892 r23594  
     1
     2stdout_cntl:
     3  GetJobOutout
     4    CheckControllerJob
     5      CheckController
     6        controller_threads (controlThread)
     7  StartController
     8  ControllerCommand
     9    CheckController
     10      controller_threads (controlThread)
     11    controller_check (clientThread)
     12    controller_host (clientThread)
     13    controller_jobstack (clientThread)
     14    controller_run (clientThread)
     15    controller_status (clientThread)
     16    controller_verbose (clientThread)
     17    DeleteControllerJob
     18      CheckControllerJob
     19        CheckController
     20          controller_threads (controlThread)
     21    CheckControllerJobStatus
     22      CheckControllerJob
     23        CheckController
     24          controller_threads (controlThread)
     25    SubmitControllerJob
     26      SubmitJob
     27        CheckTasks (JobTaskThread)
     28    PrintControllerBusyJobs
     29    KillControllerJob
     30    QuitController
     31    RestartController   
     32  CheckControllerOutput
     33    controller_output (clientThread)
     34    controller_threads (controlThread)
     35
     36
     37
     38
     39
     40
     41
     4220090322
     43
     44  We've been surviving with a slightly broken threading / locking
     45  model.  I would like to clean it up.  Previously, the threads where
     46  blocking at a very coarse level, and there were certain interactions
     47  that were not thread-safe.  Here are my notes on re-working this:
     48
     49  * we have 6 threads:
     50
     51    * main (top-level parent) : after it spawns the 5 child threads,
     52      this thread waits for new clients and adds them to the list of
     53      active clients with 'AddNewClient'
     54
     55    * clientsThread (ListenClients): this thread is listening for
     56      commands from the clients; when it receives a complete command,
     57      it executes the command using 'multicommand'.
     58
     59    * tasksThread
     60      CheckTasks
     61        NextTask
     62
     63
     64
     65    * jobsThread
     66
     67    * controllerThread
     68      CheckControllerStatus : race condition is irrelevant
     69
     70    * inputsThread
     71      AddNewInput called by clientThread
     72      (not sure this is really being used:
     73           server input (filename) calls 'input'
     74           server module (filename) calls 'module'
     75
     76  * functions which need to be thread-safe:
     77    * AddNewClient
     78    * gprint and supporting functions must be thread safe (extensively
     79      used...)
     80
     81
     82* race condition is irrelevant for this variable
     83static int ControllerStatus = FALSE;
     84
     85static int stdin_cntl, stdout_cntl, stderr_cntl;
     86GetJobOutput -> CheckControllerJob -> CheckController -> controllerThread
     87ControllerCommand -> controllerThread / clientThread
     88CheckControllerOutput -> controllerThread / clientThread
     89StartController -> controllerThread / clientThread
     90StopController
     91
     92
     93
     94static IOBuffer stdout_buffer;
     95static IOBuffer stderr_buffer;
     96static int ControllerPID = 0;
     97
     98/* local static variables to track the controller host properties */
     99static Host *hosts = NULL;
     100static int Nhosts = 0;
     101static int NHOSTS = 0;
     102
     103
     104
     105
     106
     107
     108
     109
     110
     111
     112
     113
     114
     115
     116
     117
     118
     119
     120
     121
     122
     123
     124
    1125
    2126PanTasks Client / Server design
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/pantasks.c.in

    r16453 r23594  
    1010void program_init (int *argc, char **argv) {
    1111 
    12   pthread_t jobsThread;
    13   pthread_t tasksThread;
     12  pthread_t JobsAndTasksThread;
    1413  pthread_t controllerThread;
    1514
     
    5049
    5150  /* start up the background threads here */
    52   pthread_create (&tasksThread,      NULL, &CheckTasksThread,      NULL);
    53   pthread_create (&jobsThread,       NULL, &CheckJobsThread,       NULL);
    54   pthread_create (&controllerThread, NULL, &CheckControllerThread, NULL);
     51  // pthread_create (&tasksThread,      NULL, &CheckTasksThread,           NULL);
     52  // pthread_create (&jobsThread,       NULL, &CheckJobsThread,            NULL);
     53  pthread_create (&JobsAndTasksThread, NULL, &CheckJobsAndTasksThread, NULL);
     54  pthread_create (&controllerThread,   NULL, &CheckControllerThread,   NULL);
    5555  return;
    5656}
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/pantasks_server.c.in

    r16453 r23594  
    1717 
    1818  char log_stdout[128], log_stderr[128];
    19   pthread_t jobsThread;
    20   pthread_t tasksThread;
    21   pthread_t inputsThread;
     19  pthread_t JobsAndTasksThread;
    2220  pthread_t clientsThread;
    2321  pthread_t controllerThread;
     
    6361
    6462  /* start up the background threads here */
    65   pthread_create (&clientsThread,    NULL, &ListenClients,         NULL);
    66   pthread_create (&tasksThread,      NULL, &CheckTasksThread,      NULL);
    67   pthread_create (&jobsThread,       NULL, &CheckJobsThread,       NULL);
    68   pthread_create (&controllerThread, NULL, &CheckControllerThread, NULL);
    69   pthread_create (&inputsThread,     NULL, &CheckInputsThread,     NULL);
     63  pthread_create (&clientsThread,       NULL, &ListenClients,           NULL);
     64  pthread_create (&JobsAndTasksThread,  NULL, &CheckJobsAndTasksThread, NULL);
     65  pthread_create (&controllerThread,    NULL, &CheckControllerThread,   NULL);
    7066
    7167  /* in this loop, we listen for incoming connections, validate, and
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/server.c

    r16463 r23594  
    55int input           PROTO((int, char **));
    66int module          PROTO((int, char **));
    7 int server_load     PROTO((int, char **));
    87int server_run      PROTO((int, char **));
    98int server_stop     PROTO((int, char **));
     
    2019  {1, "input",  input,  "load input file on server"},
    2120  {1, "module", module, "load module file on server"},
    22   {1, "load",   server_load, "load input file on server"},
    2321  {1, "run",    server_run,  "run scheduler"},
    2422  {1, "stop",   server_stop, "stop scheduler"},
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/server_run.c

    r11084 r23594  
    1111  CheckJobsSetState (TRUE);
    1212  CheckControllerSetState (TRUE);
    13   CheckInputsSetState (TRUE);
    1413  return (TRUE);
    1514}
     
    2322
    2423  CheckTasksSetState (FALSE);
    25   // CheckJobsSetState (FALSE);
    26   // CheckControllerSetState (FALSE);
    27   CheckInputsSetState (FALSE);
    2824  return (TRUE);
    2925}
     
    3935  CheckJobsSetState (FALSE);
    4036  CheckControllerSetState (FALSE);
    41   CheckInputsSetState (FALSE);
    4237  return (TRUE);
    4338}
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/showtask.c

    r12468 r23594  
    88  }
    99
     10  JobTaskLock();
    1011  ShowTask (argv[1]);
     12  JobTaskUnlock();
     13
    1114  return (TRUE);
    1215}
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/status_server.c

    r16012 r23594  
    1111  if ((N = get_argument (argc, argv, "-tasks"))) {
    1212    remove_argument (N, &argc, argv);
     13    JobTaskLock();
    1314    ListTasks (FALSE);
     15    JobTaskUnlock();
    1416    return (TRUE);
    1517  }
     
    1719  if ((N = get_argument (argc, argv, "-taskinfo"))) {
    1820    remove_argument (N, &argc, argv);
     21    JobTaskLock();
    1922    ListTasks (TRUE);
     23    JobTaskUnlock();
    2024    return (TRUE);
    2125  }
     
    2327  if ((N = get_argument (argc, argv, "-taskstats"))) {
    2428    remove_argument (N, &argc, argv);
     29    JobTaskLock();
    2530    if (argc == 2) {
    2631      ListTaskStats (argv[N]);
     
    2833      ListTaskStats (NULL);
    2934    }     
     35    JobTaskUnlock();
    3036    return (TRUE);
    3137  }
     
    3339  if ((N = get_argument (argc, argv, "-taskstatsreset"))) {
    3440    remove_argument (N, &argc, argv);
     41    JobTaskLock();
    3542    if (argc == 2) {
    3643      ResetTaskStats (argv[N]);
     
    3845      ResetTaskStats (NULL);
    3946    }     
     47    JobTaskUnlock();
    4048    return (TRUE);
    4149  }
     
    5664    gprint (GP_LOG, " Controller is stopped\n");
    5765  }
     66
     67  JobTaskLock();
    5868  ListTasks (FALSE);
    5969  ListJobs ();
     70  JobTaskUnlock();
     71
     72  ControlLock(__func__);
     73  PrintControllerBusyJobs();
     74  ControlUnlock(__func__);
     75
    6076  return (TRUE);
    6177
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/task.c

    r14590 r23594  
    1111  if (argc != 2) goto usage;
    1212
     13  JobTaskLock();
    1314  task = FindTask (argv[1]);
    1415  if (task == NULL) { /**** new task ****/
     
    1819    SetNewTask (task);
    1920  }
     21  JobTaskUnlock();
     22
    2023  /* While a task is being defined, it is removed from the task list.  The new task is added to the task list
    2124     when the definition process is complete. 
     
    5558
    5659      case TASK_END:
    57         /* I need to add in a test here to see if all task elements
    58            have been defined.  delete the task if not */
    5960        free (input);
    6061        /* validate the new task: all mandatory elements defined? */
     
    6364          return (FALSE);
    6465        }
     66        JobTaskLock();
    6567        RegisterNewTask ();
     68        JobTaskUnlock();
    6669        return (TRUE);
    6770        break;
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/task_active.c

    r10734 r23594  
    77  if (argc != 2) goto usage;
    88
     9  JobTaskLock();
    910  task = GetNewTask ();
    1011  if (task == NULL) {
    1112    gprint (GP_ERR, "ERROR: not defining or running a task\n");
     13    JobTaskUnlock();
    1214    return (FALSE);
    1315  }
     
    1517  if (!strcasecmp (argv[1], "true")) {
    1618    task[0].active = TRUE;
     19    JobTaskUnlock();
    1720    return (TRUE);
    1821  }
    1922  if (!strcasecmp (argv[1], "false")) {
    2023    task[0].active = FALSE;
     24    JobTaskUnlock();
    2125    return (TRUE);
    2226  }
    2327
    2428  gprint (GP_ERR, "ERROR: invalid option: %s\n", argv[1]);
     29  JobTaskUnlock();
    2530  return (FALSE);
    2631
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/task_command.c

    r7917 r23594  
    1212  }
    1313
     14  JobTaskLock();
    1415  task = GetNewTask ();
    1516  if (task == NULL) {
     
    1718    if (task == NULL) {
    1819      gprint (GP_ERR, "ERROR: not defining or running a task\n");
     20      JobTaskUnlock();
    1921      return (FALSE);
    2022    }
     
    3537    task[0].argv[i] = strcreate (argv[i+1]);
    3638  }
     39  JobTaskUnlock();
    3740  return (TRUE);
    3841}
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/task_host.c

    r7917 r23594  
    2222
    2323  task = GetNewTask ();
     24  JobTaskLock();
    2425  if (task == NULL) {
    2526    task = GetActiveTask ();
    2627    if (task == NULL) {
    2728      gprint (GP_ERR, "ERROR: not defining or running a task\n");
     29      JobTaskUnlock();
    2830      return (FALSE);
    2931    }
     
    3436  task[0].host = NULL;
    3537
    36   if (!strcasecmp (argv[1], "LOCAL")) return (TRUE);
     38  if (!strcasecmp (argv[1], "LOCAL")) {
     39    JobTaskUnlock();
     40    return (TRUE);
     41  }
    3742
    3843  task[0].host = strcreate (argv[1]);
     44  JobTaskUnlock();
    3945  return (TRUE);
    4046}
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/task_macros.c

    r10647 r23594  
    2222  }
    2323
     24  JobTaskLock();
    2425  task = GetNewTask ();
    2526  if (task == NULL) {
    2627    gprint (GP_ERR, "ERROR: not defining or running a task\n");
     28    JobTaskUnlock();
    2729    return (FALSE);
    2830  }
     
    135137        free (input);
    136138        REALLOCATE (macro[0].line, char *, MAX (1, macro[0].Nlines));
     139        JobTaskUnlock();
    137140        return (TRUE);
    138141      }
     
    148151    }
    149152  }
     153  JobTaskUnlock();
    150154  return (TRUE);
    151155}
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/task_nmax.c

    r11055 r23594  
    77  if (argc != 2) goto usage;
    88
     9  JobTaskLock();
    910  task = GetNewTask ();
    1011  if (task == NULL) {
    1112    gprint (GP_ERR, "ERROR: not defining or running a task\n");
     13    JobTaskUnlock();
    1214    return (FALSE);
    1315  }
    1416
    1517  task[0].Nmax = atoi (argv[1]);
     18  JobTaskUnlock();
    1619  return (TRUE);
    1720
     
    2730  if (argc != 2) goto usage;
    2831
     32  JobTaskLock();
    2933  task = GetNewTask ();
    3034  if (task == NULL) {
    3135    gprint (GP_ERR, "ERROR: not defining or running a task\n");
     36    JobTaskUnlock();
    3237    return (FALSE);
    3338  }
    3439
    3540  task[0].NpendingMax = atoi (argv[1]);
     41  JobTaskUnlock();
    3642  return (TRUE);
    3743
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/task_options.c

    r8129 r23594  
    1212  }
    1313
     14  JobTaskLock();
    1415  task = GetNewTask ();
    1516  if (task == NULL) {
     
    1718    if (task == NULL) {
    1819      gprint (GP_ERR, "ERROR: not defining or running a task\n");
     20      JobTaskUnlock();
    1921      return (FALSE);
    2022    }
     
    3537    task[0].optv[i] = strcreate (argv[i+1]);
    3638  }
     39  JobTaskUnlock();
    3740  return (TRUE);
    3841}
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/task_periods.c

    r7917 r23594  
    4040  }
    4141
     42  JobTaskLock();
    4243  task = GetNewTask ();
    4344  if (task == NULL) {
     
    4546    if (task == NULL) {
    4647      gprint (GP_ERR, "ERROR: not defining or running a task\n");
     48      JobTaskUnlock();
    4749      return (FALSE);
    4850    }
     
    5355  if (Timeout) task[0].timeout_period = TimeoutValue;
    5456
     57  JobTaskUnlock();
    5558  return (TRUE);
    5659}
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/task_stdout.c

    r12332 r23594  
    1111  }
    1212
     13  JobTaskLock();
    1314  task = GetNewTask ();
    1415  if (task == NULL) {
     
    1617    if (task == NULL) {
    1718      gprint (GP_ERR, "ERROR: not defining or running a task\n");
     19      JobTaskUnlock();
    1820      return (FALSE);
    1921    }
     
    2123  if (task[0].stdout_dump != NULL) free (task[0].stdout_dump);
    2224  task[0].stdout_dump = strcreate (argv[1]);
     25  JobTaskUnlock();
    2326  return (TRUE);
    2427}
     
    3437  }
    3538
     39  JobTaskLock();
    3640  task = GetNewTask ();
    3741  if (task == NULL) {
     
    3943    if (task == NULL) {
    4044      gprint (GP_ERR, "ERROR: not defining or running a task\n");
     45      JobTaskUnlock();
    4146      return (FALSE);
    4247    }
     
    4449  if (task[0].stderr_dump != NULL) free (task[0].stderr_dump);
    4550  task[0].stderr_dump = strcreate (argv[1]);
     51  JobTaskUnlock();
    4652  return (TRUE);
    4753}
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/task_trange.c

    r15487 r23594  
    1212    if (argc != 1) goto usage;
    1313
     14    JobTaskLock();
    1415    task = GetNewTask ();
    1516    if (task == NULL) {
    1617      gprint (GP_ERR, "ERROR: not defining or running a task\n");
     18      JobTaskUnlock();
    1719      return (FALSE);
    1820    }
     
    2022    task[0].Nranges = 0;
    2123    REALLOCATE (task[0].ranges, TimeRange, 1);
     24    JobTaskUnlock();
    2225    return (TRUE);
    2326  }
     
    4043
    4144  if (argc != 3) goto usage;
    42 
    43   task = GetNewTask ();
    44   if (task == NULL) {
    45     gprint (GP_ERR, "ERROR: not defining or running a task\n");
    46     return (FALSE);
    47   }
    4845
    4946  /* test for Mon[@HH:MM:SS] - both must match */
     
    8380
    8481valid:
     82  JobTaskLock();
     83  task = GetNewTask ();
     84  if (task == NULL) {
     85    gprint (GP_ERR, "ERROR: not defining or running a task\n");
     86    JobTaskUnlock();
     87    return (FALSE);
     88  }
     89
    8590  N = task[0].Nranges;
    8691  task[0].Nranges ++;
     
    8893 
    8994  task[0].ranges[N] = range;
     95  JobTaskUnlock();
    9096  return (TRUE);
    9197
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pantasks/thread_locks.c

    r11084 r23594  
    11# include "pantasks.h"
    22
    3 /* this mutex is used by the serialized threads */
     3/* mutex to lock Client table operations */
     4static pthread_mutex_t ClientMutex = PTHREAD_MUTEX_INITIALIZER;
    45
    5 static pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
    6 
    7 void SerialThreadLock () {
    8     pthread_mutex_lock (&mutex);
     6void ClientLock () {
     7  pthread_mutex_lock (&ClientMutex);
    98}
    109
    11 void SerialThreadUnlock () {
    12     pthread_mutex_unlock (&mutex);
     10void ClientUnlock () {
     11  pthread_mutex_unlock (&ClientMutex);
    1312}
    1413
     14/* mutex to lock Command / Multicommand operations */
     15static pthread_mutex_t CommandMutex = PTHREAD_MUTEX_INITIALIZER;
     16
     17void CommandLock () {
     18  //  fprintf (stderr, "command lock\n");
     19  pthread_mutex_lock (&CommandMutex);
     20}
     21
     22void CommandUnlock () {
     23  //  fprintf (stderr, "command unlock\n");
     24  pthread_mutex_unlock (&CommandMutex);
     25}
     26
     27/* mutex to lock Control operations */
     28static pthread_mutex_t ControlMutex = PTHREAD_MUTEX_INITIALIZER;
     29
     30void ControlLock (char *func) {
     31  // fprintf (stderr, "control lock %s\n", func);
     32  pthread_mutex_lock (&ControlMutex);
     33}
     34
     35void ControlUnlock (char *func) {
     36  // fprintf (stderr, "control unlock %s\n", func);
     37  pthread_mutex_unlock (&ControlMutex);
     38}
     39
     40/* mutex to lock Job / Task operations */
     41static pthread_mutex_t JobTaskMutex = PTHREAD_MUTEX_INITIALIZER;
     42
     43void JobTaskLock () {
     44  //  fprintf (stderr, "jobtask lock\n");
     45  pthread_mutex_lock (&JobTaskMutex);
     46}
     47
     48void JobTaskUnlock () {
     49  //  fprintf (stderr, "jobtask unlock\n");
     50  pthread_mutex_unlock (&JobTaskMutex);
     51}
     52
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pcontrol/JobOps.c

    r21379 r23594  
    202202  ALLOCATE (job, Job, 1);
    203203
     204  job[0].JobID    = NextJobID();
     205  if (job[0].JobID < 0) {
     206    free (job);
     207    return -1;
     208  }
     209
    204210  job[0].argc     = argc;
    205211  job[0].argv     = argv;
     
    220226  job[0].dtime = 0.0;
    221227  job[0].pid = 0;
    222 
    223   job[0].JobID    = NextJobID();
    224228  job[0].host     = NULL;
    225229
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/opihi/pcontrol/job.c

    r19124 r23594  
    1111      return (FALSE);
    1212  }   
     13
     14  if (get_argument (argc, argv, "-h")) goto usage;
     15  if (get_argument (argc, argv, "-help")) goto usage;
     16  if (get_argument (argc, argv, "--help")) goto usage;
    1317
    1418  Host = NULL;
     
    3640
    3741  if (argc < 2) {
    38     gprint (GP_ERR, "USAGE: job [options] (arg0) (arg1) ... (argN)\n");
    39     gprint (GP_ERR, "  arguments of the form @MAX_THREADS@ will be replaced when the job is launched\n");
    4042    FREE (Host);
    41     return (FALSE);
     43    goto usage;
    4244  }
    4345 
     
    4850  }
    4951
     52  // a JobID < 0 mean the job was not accepted
    5053  JobID = AddJob (Host, Mode, Timeout, targc, targv);
    5154  gprint (GP_LOG, "JobID: %d\n", (int) JobID);
    5255  return (TRUE);
     56
     57 usage:
     58    gprint (GP_ERR, "USAGE: job [options] (arg0) (arg1) ... (argN)\n");
     59    gprint (GP_ERR, "  options: -host, +host, -timeout\n");
     60    gprint (GP_ERR, "  arguments of the form @MAX_THREADS@ will be replaced when the job is launched\n");
     61    return (FALSE);
    5362}
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/relastro/src/ImageOps.c

    r23344 r23594  
    297297      mask = TRUE;
    298298    }
     299    if (~finite(catalog[c].measure[m].dR) || ~finite(catalog[c].measure[m].dD)) mask = TRUE;
     300
    299301    raw[i].mask = mask;
    300302
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/relastro/src/UpdateObjects.c

    r21508 r23594  
    9696
    9797      for (k = 0; k < catalog[i].average[j].Nmeasure; k++, m++) {
     98
     99        //exclude measurements which have non-finite astrometry
     100        if (~finite(catalog[i].measure[m].dR) || ~finite(catalog[i].measure[m].dD)) continue;
    98101
    99102        // exclude measurements by previous outlier detection
  • branches/cnb_branches/cnb_branch_20090301/Ohana/src/relastro/src/bcatalog.c

    r23344 r23594  
    88  int mask;
    99  PhotCode *code;
     10  int skipFew = skipPhotCodeKeep = skipPhotCodeSkip = skipTime = skipPhotFlag = skipSigmaLim = skipImagSelect = 0;
    1011
    1112  // XXX in the future, use catalog[0].Nsecfilt only?  allow catalogs to have variable Nsecfilt?
     
    2324  /* exclude stars not in range or with too few measurements */
    2425  for (i = 0; i < catalog[0].Naverage; i++) {
    25     if (catalog[0].average[i].Nmeasure <= SRC_MEAS_TOOFEW) continue;
    26 
     26    if (catalog[0].average[i].Nmeasure <= SRC_MEAS_TOOFEW) {
     27      skipFew++;
     28      continue;
     29    }
     30   
    2731    /* start with all stars good */
    2832    subcatalog[0].average[Naverage] = catalog[0].average[i];
     
    5256          if (photcodesKeep[k][0].code == GetPhotcodeEquivCodebyCode(catalog[0].measure[offset].photcode)) found = TRUE;
    5357        }
    54         if (!found) continue;
     58        if (!found) {
     59          skipPhotCodeKeep++;
     60          continue;
     61        }
    5562      }
    5663      if (NphotcodesSkip > 0) {
     
    6067          if (photcodesSkip[k][0].code == GetPhotcodeEquivCodebyCode(catalog[0].measure[offset].photcode)) found = TRUE;
    6168        }
    62         if (found) continue;
     69        if (found) {
     70          skipPhotCodeSkip++;
     71          continue;
     72        }
    6373      }
    6474
    6575      /* select measurements by time */
    6676      if (TimeSelect) {
    67         if (catalog[0].measure[offset].t < TSTART) continue;
    68         if (catalog[0].measure[offset].t > TSTOP) continue;
     77        if (catalog[0].measure[offset].t < TSTART) {
     78          skipTime++;
     79          continue;
     80        }
     81        if (catalog[0].measure[offset].t > TSTOP) {
     82          skipTime++;
     83          continue;
     84        }
    6985      }
    70 
     86     
    7187      /* select measurements by quality */
    7288      // XXX FIX THIS!!
    7389      // if (DophotSelect && (catalog[0].measure[offset].dophot != DophotValue)) continue;
    74 
     90     
    7591      /* select measurements by quality */
    7692      if (PhotFlagSelect) {
     
    8197          mask = code[0].astromBadMask;
    8298        }
    83         if (mask & catalog[0].measure[offset].photFlags) continue;
     99        if (mask & catalog[0].measure[offset].photFlags) {
     100          skipPhotFlag++;
     101          continue;
     102        }
    84103      }
    85 
     104     
    86105      /* select measurements by measurement error */
    87       if ((SIGMA_LIM > 0) && (catalog[0].measure[offset].dM > SIGMA_LIM)) continue;
    88 
     106      if ((SIGMA_LIM > 0) && (catalog[0].measure[offset].dM > SIGMA_LIM)) {
     107        skipSigmaLim++;
     108        continue;
     109      }
     110     
    89111      /* select measurements by mag limit */
    90112      if (ImagSelect) {
    91113        mag = PhotInst (&catalog[0].measure[offset]);
    92         if (mag < ImagMin) continue;
    93         if (mag > ImagMax) continue;
     114        if (mag < ImagMin || mag > ImagMax) {
     115          skipImagSelect++;
     116          continue;
     117        }
    94118      }
    95 
    96119      // re-assess on each run of relastro if a measurement should be used
    97120
     
    139162
    140163  if (VERBOSE) {
     164    fprintf(stderr, "Reasons for exclusion in bcatalog:\n");
     165    fprintf(stderr, "\ntoo few: %d \nphotCodeSkip: %d \nphotCodeKeep: %d \ntime: %d\n",
     166            skipfew, skipPhotCodeKeep, skipPhotCodeSkip, skipTime);
     167    fprintf(stderr, "photFlag: %d \nmagnitude error: %d \nImag: %d\n",
     168            skipPhotFlag, skipSigmaLim, skipImagSelect);
     169  }
     170
     171  if (VERBOSE) {
    141172    fprintf (stderr, "%d: using %d stars (%d measures) for catalog\n", i,
    142173             subcatalog[0].Naverage, subcatalog[0].Nmeasure);
  • branches/cnb_branches/cnb_branch_20090301/PS-IPP-Config/lib/PS/IPP/Config.pm

    r23352 r23594  
    388388    }
    389389
    390     return 1 if defined $self->{nebulous}; # Already started
     390    return $self->{nebulous} if defined $self->{nebulous}; # Already started
    391391
    392392    my $server = metadataLookupStr( $self->{_siteConfig}, 'NEB_SERVER' ); # Nebulous server
     
    398398    my $neb = eval { Nebulous::Client->new( proxy => $server ); };
    399399    if ($@ or not defined $neb) {
    400         carp "Unable to find NEB_SERVER in camera configuration file.";
     400        carp "Unable to create a Nebulous::Client object with proxy => $server";
    401401        return undef;
    402402    }
     
    404404    $self->{nebulous} = $neb;
    405405
    406     return 1;
     406    return $neb;
     407}
     408
     409sub nebulous
     410{
     411    my $self = shift;
     412    carp "no parameters are allowed" if @_;
     413
     414    # check to see if we already have a live nebulous object
     415    return $self->{nebulous} if defined $self->{nebulous};
     416
     417    # if not, call _neb_start() and return the new object
     418    return $self->_neb_start() or ( carp "Can't start Nebulous" and return undef );
    407419}
    408420
     
    421433
    422434        if ($scheme eq 'neb') {
    423             $self->_neb_start() or ( carp "Can't start Nebulous" and return undef );
    424             my $neb = $self->{nebulous}; # Nebulous handle
     435            my $neb = $self->nebulous; # Nebulous handle
    425436            if ($create_if_doesnt_exist) {
    426437                my $status = eval { $neb->stat( $name ); };
     
    485496        $scheme = lc($scheme);
    486497        if ($scheme eq 'neb') {
    487             $self->_neb_start() or ( carp "Unable to start Nebulous" and return undef );
    488             my $fh = eval { $self->{nebulous}->open_create( $name ); };
     498            my $fh = eval { $self->nebulous->open_create( $name ); };
    489499            if ($@ or not defined $fh) {
    490500                carp "Unable to open/create Nebulous handle $name";
     
    524534        $scheme = lc($scheme);
    525535        if ($scheme eq 'neb') {
    526             $self->_neb_start() or ( carp "Unable to start Nebulous" and return undef );
    527             my $fh = eval { $self->{nebulous}->open_create( $name ) };
     536            my $fh = eval { $self->nebulous->open_create( $name ) };
    528537            if ($@ or not defined $fh) {
    529538                carp "Unable to open/create Nebulous handle $name";
     
    556565    my $scheme = file_scheme($name); # The scheme, e.g., file://, path://
    557566    if (defined $scheme and lc($scheme) eq 'neb') {
    558         $self->_neb_start() or ( carp "Unable to start Nebulous" and return undef );
    559         $name = eval { $self->{nebulous}->create( $name ) };
     567        $name = eval { $self->nebulous->create( $name ) };
    560568        if ($@ or not defined $name) {
    561569            carp "Unable to create Nebulous handle $name";
     
    575583    my $scheme = file_scheme($name); # The scheme, e.g., file://, path://
    576584    if (defined $scheme and lc($scheme) eq 'neb') {
    577         $self->_neb_start() or ( carp "Unable to start Nebulous" and return undef );
    578         my $found = eval { $self->{nebulous}->find_instances( $name ); };
     585        my $found = eval { $self->nebulous->find_instances( $name ); };
    579586        ( carp "Unable to find instances of Nebulous handle $name" and return undef ) if $@;
    580587        return (defined $found ? 1 : 0);
     
    595602    my $scheme = file_scheme($target); # The scheme, e.g., file://, path://
    596603    if (defined $scheme and lc($scheme) eq 'neb') {
    597         $self->_neb_start() or ( carp "Unable to start Nebulous" and return undef );
    598         $target = eval { $self->{nebulous}->create( $target ); };
     604        $target = eval { $self->nebulous->create( $target ); };
    599605        if ($@ or not defined $target) {
    600606            carp "Unable to create Nebulous handle";
     
    646652    my $scheme = file_scheme($name); # The scheme, e.g., file://, path://
    647653    if (defined $scheme and lc($scheme) eq 'neb') {
    648         $self->_neb_start() or ( carp "Unable to start Nebulous" and return undef );
    649         $status = eval { $self->{nebulous}->delete( $name ); };
     654        $status = eval { $self->nebulous->delete( $name ); };
    650655        ( carp "Unable to delete Nebulous handle $name" and return undef ) if $@;
    651656    } else {
  • branches/cnb_branches/cnb_branch_20090301/dbconfig/changes.txt

    r23352 r23594  
    740740ALTER TABLE diffSkyfile ADD COLUMN magicked TINYINT;
    741741
    742 -- drop exiting foreign key constraints
     742-- drop existing foreign key constraints
    743743ALTER TABLE diffInputSkyfile drop FOREIGN KEY diffInputSkyfile_ibfk_1;
    744744ALTER TABLE diffInputSkyfile drop FOREIGN KEY diffInputSkyfile_ibfk_2;
     
    836836show create table detResidImfile;
    837837alter table detResidImfile drop foreign key detResidImfile_ibfk_3;
     838
     839
     840-- Version: 1.1.50  magic and distribution changes
     841
     842ALTER TABLE magicDSRun ADD COLUMN label VARCHAR(64) after cam_id;
     843ALTER TABLE magicDSRun ADD KEY(label);
     844
     845-- replace null values for magicked flags with zero
     846UPDATE rawImfile SET magicked = 0 WHERE magicked IS NULL;
     847UPDATE chipProcessedImfile SET magicked = 0 WHERE magicked IS NULL;
     848UPDATE warpSkyfile SET magicked = 0 WHERE magicked IS NULL;
     849UPDATE diffSkyfile SET magicked = 0 WHERE magicked IS NULL;
     850
     851CREATE TABLE distRun (
     852    dist_id     BIGINT AUTO_INCREMENT,
     853    target_id   BIGINT,
     854    stage       VARCHAR(64),
     855    stage_id    BIGINT,
     856    label       VARCHAR(64),
     857    outroot     VARCHAR(255),
     858    clean       TINYINT,
     859    state       VARCHAR(64),
     860    time_stamp  TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
     861    fault       SMALLINT,
     862    PRIMARY KEY(dist_id),
     863    KEY(state),
     864    KEY(label),
     865    FOREIGN KEY(target_id) REFERENCES distTarget(target_id)
     866)  ENGINE=innodb DEFAULT CHARSET=latin1;
     867
     868CREATE TABLE distComponent (
     869    dist_id     BIGINT,
     870    component   VARCHAR(64),
     871    bytes       INT,
     872    md5sum      VARCHAR(32),
     873    state       VARCHAR(64),
     874    name        VARCHAR(255),
     875    fault       SMALLINT,
     876    PRIMARY KEY(dist_id, component),
     877    KEY(state),
     878    FOREIGN KEY(dist_id) REFERENCES distRun(dist_id)
     879)  ENGINE=innodb DEFAULT CHARSET=latin1;
     880
     881
     882-- change state fields to match the rest of the system
     883UPDATE magicRun SET state = 'new' WHERE state = 'run';
     884UPDATE magicRun SET state = 'full' WHERE state = 'stop';
     885UPDATE magicDSRun SET state = 'new' WHERE state = 'run';
     886UPDATE magicDSRun SET state = 'full' WHERE state = 'stop';
     887
     888ALTER TABLE rawExp ADD COLUMN magicked TINYINT;
     889ALTER TABLE chipRun ADD COLUMN magicked TINYINT;
     890ALTER TABLE warpRun ADD COLUMN magicked TINYINT;
     891ALTER TABLE diffRun ADD COLUMN magicked TINYINT;
     892
     893update rawExp  SET magicked = 0;
     894update chipRun SET magicked = 0;
     895update warpRun SET magicked = 0;
     896update diffRun SET magicked = 0;
     897
     898-- The following only applies to the gpc1 database (and recent copies)
     899update chipRun SET magicked = 1 where chip_id = 11955;
     900
     901CREATE TABLE distTarget (
     902    target_id   BIGINT AUTO_INCREMENT,
     903    obs_mode    VARCHAR(64),
     904    stage       VARCHAR(64),
     905    clean       TINYINT,
     906    state       VARCHAR(64),
     907    comment     VARCHAR(255),
     908    PRIMARY KEY(target_id)
     909)  ENGINE=innodb DEFAULT CHARSET=latin1;
     910
     911
     912CREATE TABLE rcDSProduct (
     913    prod_id     BIGINT AUTO_INCREMENT,
     914    name        VARCHAR(64),
     915    dbname      VARCHAR(64),
     916    dbhost      VARCHAR(64),
     917    prod_root   VARCHAR(255),
     918    PRIMARY KEY(prod_id)
     919)  ENGINE=innodb DEFAULT CHARSET=latin1;
     920
     921CREATE TABLE rcDestination (
     922    dest_id     BIGINT AUTO_INCREMENT,
     923    prod_id     BIGINT,
     924    name        VARCHAR(64),
     925    status_uri  VARCHAR(255),
     926    comment     VARCHAR(255),
     927    last_fileset VARCHAR(255),
     928    state       VARCHAR(64),
     929    PRIMARY KEY(dest_id),
     930    FOREIGN KEY(prod_id) REFERENCES rcDSProduct(prod_id)
     931)  ENGINE=innodb DEFAULT CHARSET=latin1;
     932
     933
     934CREATE TABLE rcInterest (
     935    int_id      BIGINT AUTO_INCREMENT,
     936    dest_id     BIGINT,
     937    target_id   BIGINT,
     938    prod_id     BIGINT,
     939    state       VARCHAR(64),
     940    PRIMARY KEY(int_id),
     941    FOREIGN KEY(dest_id) REFERENCES rcDestination(dest_id),
     942    FOREIGN KEY(target_id) REFERENCES distTarget(target_id),
     943    FOREIGN KEY(prod_id) REFERENCES rcDSProduct(prod_id)
     944)  ENGINE=innodb DEFAULT CHARSET=latin1;
     945
     946CREATE TABLE rcDSFileset (
     947    fs_id       BIGINT AUTO_INCREMENT,
     948    dist_id     BIGINT,
     949    prod_id     BIGINT,
     950    name        VARCHAR(64),
     951    state       VARCHAR(64),
     952    registered  TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
     953    PRIMARY KEY(fs_id),
     954    FOREIGN KEY(dist_id) REFERENCES distRun(dist_id),
     955    FOREIGN KEY(prod_id) REFERENCES rcDSProduct(prod_id)
     956)  ENGINE=innodb DEFAULT CHARSET=latin1;
     957
     958CREATE TABLE rcRun (
     959    rc_id       BIGINT AUTO_INCREMENT,
     960    fs_id       BIGINT,
     961    dest_id     BIGINT,
     962    state       VARCHAR(64),
     963    registered  TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
     964    PRIMARY KEY(rc_id),
     965    FOREIGN KEY(fs_id) REFERENCES rcDSFileset(fs_id),
     966    FOREIGN KEY(dest_id) REFERENCES rcDestination(dest_id)
     967)  ENGINE=innodb DEFAULT CHARSET=latin1;
     968
  • branches/cnb_branches/cnb_branch_20090301/dbconfig/chip.md

    r21310 r23594  
    1111    tess_id     STR         64
    1212    end_stage   STR         64      # Key
     13    magicked    BOOL        f
    1314END
    1415
  • branches/cnb_branches/cnb_branch_20090301/dbconfig/config.md

    r23352 r23594  
    22    pkg_name        STR     ippdb
    33    pkg_namespace   STR     ippdb
    4     pkg_version     STR     1.1.49
     4    pkg_version     STR     1.1.50
    55END
  • branches/cnb_branches/cnb_branch_20090301/dbconfig/diff.md

    r21310 r23594  
    1111    tess_id     STR         64      # Key
    1212    exp_id      S64         0       # fkey(exp_id) ref rawExp(exp_id)
     13    magicked    BOOL        f
    1314END
    1415
  • branches/cnb_branches/cnb_branch_20090301/dbconfig/dist.md

    r23352 r23594  
    33    stage       STR         64
    44    stage_id    S64         0
    5     chip_id     S64         0
    65    label       STR         64      # Key
    76    outroot     STR         255
    87    clean       BOOL        f
    98    state       STR         64      # Key
     9    time_stamp  UTC         0001-01-01T00:00:00Z
    1010    fault       S16         0
    1111END
     
    2121END
    2222
     23distTarget METADATA
     24    target_id   S64        0       # Primary Key
     25    obs_mode    STR        64
     26    clean       BOOL       f
     27    state       STR        64
     28    comment     STR        255
     29END
     30
  • branches/cnb_branches/cnb_branch_20090301/dbconfig/ipp.m4

    r17886 r23594  
    2222include(flatcorr.md)
    2323include(pstamp.md)
     24include(dist.md)
  • branches/cnb_branches/cnb_branch_20090301/dbconfig/magic.md

    r20973 r23594  
    4242
    4343magicDSRun METADATA
    44     magic_ds_id S64         0       # Primary Key fkey(magic_ds_id)
     44    magic_ds_id S64         0       # Primary Key
    4545    magic_id    S64         0       # Primary Key fkey(magic_id) ref magicRun(magic_id)
    4646    state       STR         0       # Key
     
    4848    stage_id    S64         0
    4949    cam_id      S64         0
     50    label       STR         64      # key
    5051    outroot     STR         255
    5152    recoveryroot    STR     255
     
    5556
    5657magicDSFile METADATA
    57     magic_ds_id S64         0       # Primary Key
     58    magic_ds_id S64         0       # Primary Key fkey(magic_ds_id) ref magicDSRun(magic_ds_id)
    5859    component   STR         64
    5960    backup_path_base  STR         255
  • branches/cnb_branches/cnb_branch_20090301/dbconfig/tasks.md

    r20973 r23594  
    171171    fault       S16         0       # Key NOT NULL
    172172    epoch       UTC         0001-01-01T00:00:00Z
     173    magicked    BOOL        f
    173174END
    174175
     
    235236    moon_alt    F32         0.0
    236237    moon_phase  F32         0.0
    237     ignored     BOOL        FALSE
     238    ignored     BOOL        f
    238239    hostname    STR         64
    239240    fault       S16         0       # Key NOT NULL
  • branches/cnb_branches/cnb_branch_20090301/dbconfig/warp.md

    r21310 r23594  
    2121    end_stage   STR         64      # Key
    2222    registered  TAI         NULL
    23 # if magic is T then look for the exp_id in the magic output tables
     23    magicked    BOOL        f
    2424END
    2525
  • branches/cnb_branches/cnb_branch_20090301/glueforge/templates/psdb/configure_ac.tt

    r14443 r23594  
    4040CFLAGS=${TMP_CFLAGS}
    4141
    42 
    4342AC_PATH_PROG([PERL], [perl], [missing])
    4443if test "$PERL" = "missing" ; then
     
    4645fi
    4746
    48 AC_PATH_PROG([DOXYGEN], [doxygen], [])
     47AC_ARG_ENABLE(doxygen,
     48              [AS_HELP_STRING(--enable-doxygen,doxygen-erated documentation)],
     49              [AC_MSG_RESULT(doxygen enabled)
     50               AC_PATH_PROG([DOXYGEN], [doxygen], [])],
     51              [AC_MSG_RESULT(doxygen disabled)])
    4952AM_CONDITIONAL([HAVE_DOXYGEN], [test -n "$DOXYGEN"])
    5053
  • branches/cnb_branches/cnb_branch_20090301/ippMonitor/raw/ipp.php

    r21137 r23594  
    4040
    4141  // make this a DB lookup
    42   $sql = "SELECT projname FROM projects";
     42  $sql = "SELECT projname FROM projects order by projname";
    4343
    4444  $qry = $db->query($sql);
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/chip_imfile.pl

    r23352 r23594  
    3535}
    3636
     37my @ARGS = @ARGV;
     38
    3739# Parse the command-line arguments
    3840my ( $exp_id, $chip_id, $class_id, $chip_imfile_id, $uri, $camera, $outroot, $dbname, $run_state, $reduction, $threads, $verbose,
    39      $no_update, $no_op, $redirect );
     41     $no_update, $no_op, $redirect, $magicked, $deburned );
    4042GetOptions(
    4143    'exp_id=s'          => \$exp_id,    # Exposure identifier
     
    4951    'reduction=s'       => \$reduction, # Reduction class
    5052    'run-state=s'       => \$run_state, # current state of the run (new, update)
     53    'magicked'          => \$magicked,  # magicked state of input file
     54    'deburned=s'        => \$deburned,  # does deburned image exist?
    5155    'threads=s'         => \$threads,   # Number of threads to use for ppImage
    5256    'verbose'           => \$verbose,   # Print to stdout
     
    7781    print STDOUT "\n\n";
    7882    print STDOUT "Starting script $0 on $host\n\n";
    79     print STDOUT "COMMAND IS: @ARGV\n\n";
     83    print STDOUT "FULL COMMAND: $0 @ARGS\n\n";
    8084}
    8185
     
    123127    my $command;
    124128    my $do_stats;
     129
     130    ## get the ppImage recipe for this camera and CHIP reduction
     131    $command = "$ppConfigDump -camera $camera -dump-recipe PPIMAGE -recipe PPIMAGE $recipe_ppImage -";
     132    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     133        run(command => $command, verbose => $verbose);
     134    unless ($success) {
     135        $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     136        &my_die("Unable to perform ppConfigDump: $error_code", $exp_id, $chip_id, $class_id, $PS_EXIT_SYS_ERROR);
     137    }
     138    my $recipeData = $mdcParser->parse(join "", @$stdout_buf) or
     139        &my_die("Unable to parse metadata config doc", $exp_id, $chip_id, $class_id, $PS_EXIT_SYS_ERROR);
     140
     141    ## XXX make the feature more general?
     142    my $useDeburnedImage = metadataLookupBool($recipeData, 'USE.DEBURNED.IMAGE');
     143    if ($useDeburnedImage && $deburned) {
     144        $uri =~ s/fits$/burn.fits/;
     145        &my_die("Couldn't find deburned input file: $uri\n", $exp_id, $chip_id, $class_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($uri);
     146    }
    125147
    126148    if ($run_state eq "new") {
     
    150172    }
    151173
    152     my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     174    ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    153175        run(command => $command, verbose => $verbose);
    154176    unless ($success) {
     
    156178        &my_die("Unable to perform ppImage: $error_code", $exp_id, $chip_id, $class_id, $error_code);
    157179    }
    158 
    159     ## get the ppImage recipe for this camera and CHIP reduction
    160     $command = "$ppConfigDump -camera $camera -dump-recipe PPIMAGE -recipe PPIMAGE $recipe_ppImage -";
    161     ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    162         run(command => $command, verbose => $verbose);
    163     unless ($success) {
    164         $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    165         &my_die("Unable to perform ppConfigDump: $error_code", $exp_id, $chip_id, $class_id, $PS_EXIT_SYS_ERROR);
    166     }
    167     my $recipeData = $mdcParser->parse(join "", @$stdout_buf) or
    168         &my_die("Unable to parse metadata config doc", $exp_id, $chip_id, $class_id, $PS_EXIT_SYS_ERROR);
    169180
    170181    ## allow the output images to be optional, depending on the recipe / reduction class
     
    215226    $command .= " -uri $outputImage";
    216227    $command .= " -path_base $outroot";
     228    $command .= " -magicked" if $magicked;
    217229    $command .= " -hostname $host" if defined $host;
    218230    $command .= " -dbname $dbname" if defined $dbname;
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/detrend_norm_apply.pl

    r23352 r23594  
    8989    'darkmask'         => 'mask',
    9090    'flatmask'         => 'mask',
     91    'ctemask'          => 'mask',
    9192    };
    9293
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/detrend_norm_calc.pl

    r23352 r23594  
    8181    'darkmask'         => 0,
    8282    'flatmask'         => 0,
     83    'ctemask'          => 0,
    8384    };
    8485
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/detrend_process_imfile.pl

    r23352 r23594  
    7979                  'DARK'             => undef,
    8080                  'DARK_PREMASK'     => undef,
     81                  'CTEMASK'          => undef,
    8182                  'SHUTTER'          => 'PPIMAGE.OUTPUT.DETREND',
    8283                  'FLAT_PREMASK'     => 'PPIMAGE.OUTPUT.DETREND',
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/detrend_resid_exp.pl

    r23352 r23594  
    124124    # write the normalizations to a file as a metadata config file in the form: class_id F32 value
    125125    # XXX a possible optimization: if there is only one imfile, skip normalization
     126    # Correcting the resid imfiles and stats requires us to *divide* by the normalization
     127    # we do this by inverting the normalization here:
    126128    my $normsFile;
    127129    ($normsFile, $normsName) = tempfile( "/tmp/$exp_tag.detresid.$det_id.$iter.norms.XXXX", UNLINK => !$save_temps );
     
    129131    foreach my $norm (@$normsMD) {
    130132        my $class_id = $norm->{class_id};
    131         my $normalization = $norm->{norm};
     133        my $normalization = 1.0 / $norm->{norm};
    132134
    133135        $norms{$class_id} = $normalization;
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/detrend_resid_imfile.pl

    r23352 r23594  
    114114    'darkmask'         => '-mask',      # Specify the mask frame
    115115    'flatmask'         => '-mask',      # Specify the mask frame
     116    'ctemask'          => '-mask',      # Specify the mask frame
    116117};
    117118
     
    119120my $FILERULES = { 'FLATMASK'         => 'PPIMAGE.OUTPUT.RESID',
    120121                  'DARKMASK'         => 'PPIMAGE.OUTPUT.RESID',
     122                  'CTEMASK'          => 'PPIMAGE.OUTPUT.RESID',
    121123                  'MASK'             => 'PPIMAGE.OUTPUT.RESID',
    122124                  'BIAS'             => 'PPIMAGE.OUTPUT.RESID',
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/detrend_stack.pl

    r23352 r23594  
    7575my $FILERULES = { 'FLATMASK'         => 'PPMERGE.OUTPUT.MASK',
    7676                  'DARKMASK'         => 'PPMERGE.OUTPUT.MASK',
     77                  'CTEMASK'          => 'PPMERGE.OUTPUT.MASK',
    7778                  'MASK'             => 'PPMERGE.OUTPUT.MASK',
    7879                  'BIAS'             => 'PPMERGE.OUTPUT.BIAS',
     
    9798my $STATRECIPES = {'FLATMASK'         => 'DETSTATS',
    9899                   'DARKMASK'         => 'DETSTATS',
     100                   'CTEMASK'          => 'DETSTATS',
    99101                   'MASK'             => 'DETSTATS',
    100102                   'BIAS'             => 'DETSTATS',
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/diff_skycell.pl

    r23352 r23594  
    9191
    9292# Identify the input and the template
    93 my ($input, $inputMask, $inputVariance, $inputPath); # Input files and path
     93my ($input, $inputMask, $inputVariance, $inputPath, $inputSources); # Input files and path
    9494my ($template, $templateMask, $templateVariance, $templatePath, $templateSources); # Template files and path
    9595my $tess_id;                    # Tesselation identifier
    9696my $camera;                     # Camera
     97my $magicked_0;
     98my $magicked_1;
    9799foreach my $file (@$files) {
    98100    if (defined $file->{template} and $file->{template}) {
     
    103105            $templateVariance = "PPSTACK.OUTPUT.VARIANCE";
    104106            $templateSources = "PSPHOT.OUT.CMF.MEF";  ## this must be consistent with the value in stack_skycell.pl:161
     107            # template is a stack so it doesn't need to be magicked
     108            $magicked_1 = 1;
    105109            ## use an explicit stack name for psphot output objects
    106110        } else {
     
    108112            $templateVariance = "PSWARP.OUTPUT.VARIANCE";
    109113            $templateSources = "PSWARP.OUTPUT.SOURCES";
     114            $magicked_1 = $file->{magicked};
    110115        }
    111116    } else {
    112117        $input = $file->{uri};
    113118        $inputPath = $file->{path_base};
     119        $magicked_0 = $file->{magicked};    # if input is a stack the output can't be "magicked"
    114120        if ($file->{warp_id} == 0) {
    115121            $inputMask = "PPSTACK.OUTPUT.MASK";
    116122            $inputVariance = "PPSTACK.OUTPUT.VARIANCE";
     123            $inputSources = "PSPHOT.OUT.CMF.MEF";  ## this must be consistent with the value in stack_skycell.pl:161
    117124        } else {
    118125            $inputMask = "PSWARP.OUTPUT.MASK";
    119126            $inputVariance = "PSWARP.OUTPUT.VARIANCE";
     127            $inputSources = "PSWARP.OUTPUT.SOURCES";
    120128        }
    121129    }
     
    144152&my_die("Unable to identify camera", $diff_id, $skycell_id, $PS_EXIT_SYS_ERROR) unless defined $camera;
    145153$ipprc->define_camera($camera);
     154
     155# Compute the magicked status of the output.
     156# The output file will be considered magicked if the input has been magicked and the
     157# template is either a stack or a warp that has been magicked.
     158# note that difftool -inputskyfile outputs the magicked boolean as an int not T or F
     159# because the output is constructed from a union of two selects
     160my $magicked = $magicked_0 && $magicked_1;
    146161
    147162# Recipes to use based on reduction class
     
    160175# print "inputVariance: $inputVariance\n";
    161176# print "templateSources: $templateSources\n";
     177# print "inputSources: $inputSources\n";
     178
     179$inputMask = $ipprc->filename($inputMask, $inputPath);
     180$inputVariance = $ipprc->filename($inputVariance, $inputPath);
     181$inputSources = $ipprc->filename($inputSources, $inputPath);
    162182
    163183$templateMask = $ipprc->filename($templateMask, $templatePath);
    164 $inputMask = $ipprc->filename($inputMask, $inputPath);
    165184$templateVariance = $ipprc->filename($templateVariance, $templatePath);
    166 $inputVariance = $ipprc->filename($inputVariance, $inputPath);
    167185$templateSources = $ipprc->filename($templateSources, $templatePath);
    168186
     
    174192print "inputVariance: $inputVariance\n";
    175193print "templateSources: $templateSources\n";
     194print "inputSources: $inputSources\n";
    176195
    177196&my_die("Couldn't find input: $template", $diff_id, $skycell_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($template);
    178197&my_die("Couldn't find input: $templateMask", $diff_id, $skycell_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($templateMask);
    179198&my_die("Couldn't find input: $templateVariance", $diff_id, $skycell_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($templateVariance);
     199&my_die("Couldn't find input: $templateSources", $diff_id, $skycell_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($templateSources);
    180200&my_die("Couldn't find input: $input", $diff_id, $skycell_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($input);
    181201&my_die("Couldn't find input: $inputMask", $diff_id, $skycell_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($inputMask);
    182202&my_die("Couldn't find input: $inputVariance", $diff_id, $skycell_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($inputVariance);
    183 &my_die("Couldn't find input: $templateSources", $diff_id, $skycell_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($templateSources);
     203&my_die("Couldn't find input: $inputSources", $diff_id, $skycell_id, $PS_EXIT_SYS_ERROR) unless $ipprc->file_exists($inputSources);
    184204
    185205# Get the output filenames
     
    198218# Perform subtraction
    199219unless ($no_op) {
    200     my $command = "$ppSub $input $template $outroot";
     220    my $command = "$ppSub $outroot";
     221    $command .= " -inimage $input";
     222    $command .= " -refimage $template";
    201223    $command .= " -inmask $inputMask";
    202224    $command .= " -refmask $templateMask";
    203225    $command .= " -invariance $inputVariance";
    204226    $command .= " -refvariance $templateVariance";
     227    $command .= " -insources $inputSources";
     228    $command .= " -refsources $templateSources";
    205229    $command .= " -stats $outputStats";
    206230    $command .= " -threads $threads" if defined $threads;
     
    211235    $command .= " -F PSPHOT.OUTPUT PSPHOT.OUT.CMF.MEF";
    212236    $command .= " -F PSPHOT.BACKMDL PSPHOT.BACKMDL.MEF";
    213     $command .= " -sources $templateSources";
    214237    $command .= " -photometry";
    215238    $command .= " -tracedest $traceDest -log $logDest";
     
    255278        my $command = "$difftool -adddiffskyfile -diff_id $diff_id -skycell_id $skycell_id -uri $outputName -path_base $outroot";
    256279        $command .= " $cmdflags";
     280        $command .= " -magicked" if $magicked;
    257281        $command .= (" -dtime_script " . ((DateTime->now->mjd - $mjd_start) * 86400));
    258282        $command .= " -hostname $host" if defined $host;
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/dist_component.pl

    r23352 r23594  
    4040my ($dist_id, $camera, $stage, $stage_id, $component, $path_base, $chip_path_base, $clean);
    4141my ($outroot, $run_state, $data_state, $magicked);
    42 my ($dbname, $save_temps, $verbose, $no_update, $no_op, $logfile);
     42my ($dbname, $save_temps, $verbose, $no_update, $logfile);
    4343
    4444GetOptions(
    45            'dist_id=s'  => \$dist_id,# Magic destreak run identifier
     45           'dist_id=s'      => \$dist_id,    # distribution run identifier
    4646           'camera=s'       => \$camera,     # camera for evaluating file rules
    4747           'stage=s'        => \$stage,      # raw, chip, warp, or diff
     
    5252           'state=s'        => \$run_state,  # state of the run
    5353           'data_state=s'   => \$data_state, # data_state for this component
    54            'magicked=s'     => \$magicked,   # data_state for this component
     54           'magicked'       => \$magicked,   # magicked state for this component
    5555           'outroot=s'      => \$outroot,    # "directory" for outputs
    56            'clean=s'        => \$clean,      # create clean distribution
     56           'clean        => \$clean,      # create clean distribution
    5757           'save-temps'     => \$save_temps, # Save temporary files?
    5858           'dbname=s'       => \$dbname,     # Database name
    5959           'verbose'        => \$verbose,    # Print stuff?
    6060           'no-update'      => \$no_update,  # Don't update the database?
    61            'no-op'          => \$no_op,      # Don't do any operations?
    6261           'logfile=s'      => \$logfile,
    6362           ) or pod2usage( 2 );
     
    8685my $basename = basename($path_base);
    8786
    88 #
    89 # are we creating a clean distribution?
    90 if (defined($clean) and ($clean eq "T")) {
    91     $clean = 1;
    92 } else {
    93     $clean = 0;
    94 }
    95 
    9687# making a clean bundle of raw images doesn't make sense
    9788if (($stage eq "raw") and $clean) {
     
    9990    &my_die("cannot create clean run at raw stage", $dist_id, $component, $PS_EXIT_CONFIG_ERROR);
    10091}
    101 
    10292
    10393# create the output directories if it is not a nebulous path and it doesn't exist
     
    134124foreach my $file (@$file_list) {
    135125    my $base = basename($file);
     126    my $path = $ipprc->file_resolve($file);
     127    # if file is not found, just skip it.
     128    # This is not always the right thing to do.
     129    # For example if warpSkyfile is ignored, there won't be many of the data products
     130    # the new config dump will only list the files actually produced.
     131    next if !$path;
     132
    136133    push @base_list, $base;
    137     my $path = $ipprc->file_resolve($file);
    138134    symlink $path, "$tmpdir/$base";
    139135}
     
    142138
    143139    # Here is where we determine whether or not a GPC1 image can be released.
    144 
    145     if ($magicked and ($magicked eq "F")) {
    146         $magicked = 0;
    147     }
    148140
    149141    if ($camera eq "GPC1" and !$magicked) {
     
    181173    $command .= " -chip_mask $mask" if ($stage eq 'chip' and $mask);
    182174    $command .= " -weight $variance" if $variance;
    183     unless (defined $no_op) {
    184         my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    185             run(command => $command, verbose => $verbose);
    186         unless ($success) {
    187             $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    188             &my_die("Unable to perform $command: $error_code", $dist_id, $component, $error_code);
    189         }
    190     } else {
    191         print "skipping command $command\n";
     175    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     176        run(command => $command, verbose => $verbose);
     177    unless ($success) {
     178        $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     179        &my_die("Unable to perform $command: $error_code", $dist_id, $component, $error_code);
    192180    }
    193181}
     
    207195    my $command = "tar -C $tmpdir -czhf $tarfile .";
    208196
    209     unless (defined $no_op) {
    210         my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    211             run(command => $command, verbose => $verbose);
    212         unless ($success) {
    213             $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
    214             &my_die("Unable to perform $command: $error_code", $dist_id, $component, $error_code);
    215         }
    216     } else {
    217         print "skipping command $command\n";
     197    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     198        run(command => $command, verbose => $verbose);
     199    unless ($success) {
     200        $error_code = (($error_code >> 8) or $PS_EXIT_PROG_ERROR);
     201        &my_die("Unable to perform $command: $error_code", $dist_id, $component, $error_code);
    218202    }
    219203
     
    227211    $bytes = $finfo[7];
    228212
    229     if (!$save_temps) {
    230         # delete the temp directory and it's contents
    231         system "rm -r $tmpdir";
    232     }
     213    delete_tmpdir($tmpdir);
    233214}
    234215{
     
    265246        # TODO: these data will eventually come from the CONFIG dump
    266247
    267         my $fh;
    268         open $fh, "/data/ipp004.0/home/bills/ipp/ippScripts/scripts/clean.mdc" or
    269             &my_die("cannot find clean.mdc", $dist_id, $component, $PS_EXIT_UNKNOWN_ERROR);
    270 
    271         my @data = <$fh>;
    272         my $clean_mdc = join "", @data;
     248        my $clean_mdc = get_legacy_file_mdc();
    273249
    274250        my $mdlist = $mdcParser->parse($clean_mdc) or
     
    342318    }
    343319
     320    delete_tmpdir();
     321
    344322    carp($msg);
    345323    exit $exit_code;
    346324}
    347325
     326sub delete_tmpdir
     327{
     328    if (!$save_temps) {
     329        system "rm -r $tmpdir";
     330    }
     331}
     332
     333# list of output data products for runs that were made before the configuration re-work
     334sub get_legacy_file_mdc
     335{
     336    my $list =
     337"
     338#
     339# interesting things we might want to save in this file
     340#   1. whether file is to be distributed in 'clean' mode
     341#   2. whether file is to be cleaned (this should be the same thing)
     342#   3. type of file 'no, not our business, precious'
     343
     344# this data should probably be computed by the relevant program and saved as part
     345# of the configuration dump that is output.
     346
     347
     348PROD_LIST MULTI
     349
     350PROD_LIST   METADATA
     351        STAGE                    STR     RAW
     352    # there is isn't really a file rule for raw images
     353        DUMMY                   BOOL    F
     354END
     355
     356# list of data products for a gpc1 chipProcessedImfile  (made by ppImage)
     357PROD_LIST   METADATA
     358        STAGE                    STR     CHIP
     359        PPIMAGE.CONFIG          BOOL    T
     360#       PPIMAGE.CHIP            BOOL    F
     361#       PPIMAGE.CHIP.MASK       BOOL    F
     362#       PPIMAGE.CHIP.VARIANCE   BOOL    F
     363        PPIMAGE.BIN1            BOOL    T
     364        PPIMAGE.BIN2            BOOL    T
     365        PSPHOT.OUT.CMF.SPL      BOOL    T
     366        PSPHOT.BACKMDL          BOOL    T
     367        PPIMAGE.STATS           BOOL    T
     368        LOG.IMFILE              BOOL    T
     369        TRACE.IMFILE            BOOL    T
     370    # where do we put exposure level data such as LOG.EXP ?
     371END
     372# exposure level output products from camera processing made by psastro and ppImage (jpegs)
     373PROD_LIST   METADATA
     374        STAGE                    STR     CAM
     375        PSASTRO.CONFIG          BOOL    T
     376        PSASTRO.OUTPUT          BOOL    T
     377        PSASTRO.STATS           BOOL    T
     378        PPIMAGE.JPEG1           BOOL    T
     379        PPIMAGE.JPEG2           BOOL    T
     380        LOG.EXP                 BOOL    T
     381        TRACE.EXP               BOOL    T
     382END
     383# chip lelel output products from camera processing made by psastro
     384PROD_LIST   METADATA
     385        STAGE                    STR CAM_CHIP
     386#       PSASTRO.OUTPUT.MASK     BOOL    F
     387END
     388PROD_LIST   METADATA
     389        STAGE                    STR     FAKE
     390#       PPSIM.OUTPUT            BOOL    F
     391END
     392# list of data products for a gpc1 warpSkyfile (pswarp)
     393PROD_LIST   METADATA
     394        STAGE                    STR     WARP
     395        PSWARP.CONFIG           BOOL    T
     396#       PSWARP.OUTPUT           BOOL    F
     397#       PSWARP.OUTPUT.MASK      BOOL    F
     398#       PSWARP.OUTPUT.VARIANCE  BOOL    F
     399        PSWARP.OUTPUT.SOURCES   BOOL    T
     400        PSPHOT.BACKMDL.MEF      BOOL    T
     401        PSPHOT.PSF.SKY.SAVE     BOOL    T
     402        SKYCELL.STATS           BOOL    T
     403        SKYCELL.TEMPLATE        BOOL    T
     404        LOG.EXP                 BOOL    T
     405        TRACE.EXP               BOOL    T
     406END
     407# outputs from diffRun (ppSub)
     408PROD_LIST   METADATA
     409        STAGE                    STR     DIFF
     410        PPSUB.CONFIG            BOOL    T
     411#       PPSUB.OUTPUT            BOOL    F
     412#       PPSUB.OUTPUT.MASK       BOOL    F
     413#       PPSUB.OUTPUT.VARIANCE   BOOL    F
     414        PPSUB.OUTPUT.KERNELS    BOOL    T
     415        PPSUB.OUTPUT.JPEG1      BOOL    T
     416        PPSUB.OUTPUT.JPEG2      BOOL    T
     417        PSPHOT.OUT.CMF.MEF      BOOL    T
     418        PSPHOT.BACKMDL.MEF      BOOL    T
     419        SKYCELL.STATS           BOOL    T
     420        LOG.EXP                 BOOL    T
     421        TRACE.EXP               BOOL    T
     422END
     423PROD_LIST   METADATA
     424        STAGE                    STR     STACK
     425        PPSTACK.CONFIG          BOOL    T
     426#       PPSTACK.OUTPUT          BOOL    F
     427#       PPSTACK.OUTPUT.MASK     BOOL    F
     428#       PPSTACK.OUTPUT.VARIANCE BOOL    F
     429        PPSTACK.TARGET.PSF      BOOL    T
     430        PSPHOT.OUT.CMF.MEF      BOOL    T
     431        PSPHOT.BACKMDL.MEF      BOOL    T
     432        SKYCELL.STATS           BOOL    T
     433        PPSTACK.OUTPUT.JPEG1    BOOL    T
     434        PPSTACK.OUTPUT.JPEG2    BOOL    T
     435        LOG.EXP                 BOOL    T
     436        TRACE.EXP               BOOL    T
     437END
     438";
     439    return $list;
     440}
     441
     442
    348443__END__
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/register_imfile.pl

    r23352 r23594  
    112112
    113113# we require at a minimum: -telescope, -inst, -filelevel, -class_id, -exp_type
    114 if (uc(&value_for_flag ($cmdflags, "-telescope")) eq "NULL") { &my_die ("telescope not found", $exp_id, $tmp_exp_name, $tmp_class_id, $uri, $PS_EXIT_CONFIG_ERROR); }
    115 if (uc(&value_for_flag ($cmdflags, "-inst"))      eq "NULL") { &my_die ("inst      not found", $exp_id, $tmp_exp_name, $tmp_class_id, $uri, $PS_EXIT_CONFIG_ERROR); }
    116 if (uc(&value_for_flag ($cmdflags, "-filelevel")) eq "NULL") { &my_die ("filelevel not found", $exp_id, $tmp_exp_name, $tmp_class_id, $uri, $PS_EXIT_CONFIG_ERROR); }
    117 if (uc(&value_for_flag ($cmdflags, "-class_id"))  eq "NULL") { &my_die ("class_id  not found", $exp_id, $tmp_exp_name, $tmp_class_id, $uri, $PS_EXIT_CONFIG_ERROR); }
    118 if (uc(&value_for_flag ($cmdflags, "-exp_type"))  eq "NULL") { &my_die ("exp_type  not found", $exp_id, $tmp_exp_name, $tmp_class_id, $uri, $PS_EXIT_CONFIG_ERROR); }
     114if (uc(&value_for_flag ($cmdflags, "NULL", "-telescope")) eq "NULL") { &my_die ("telescope not found", $exp_id, $tmp_exp_name, $tmp_class_id, $uri, $PS_EXIT_CONFIG_ERROR); }
     115if (uc(&value_for_flag ($cmdflags, "NULL", "-inst"))      eq "NULL") { &my_die ("inst      not found", $exp_id, $tmp_exp_name, $tmp_class_id, $uri, $PS_EXIT_CONFIG_ERROR); }
     116if (uc(&value_for_flag ($cmdflags, "NULL", "-filelevel")) eq "NULL") { &my_die ("filelevel not found", $exp_id, $tmp_exp_name, $tmp_class_id, $uri, $PS_EXIT_CONFIG_ERROR); }
     117if (uc(&value_for_flag ($cmdflags, "NULL", "-class_id"))  eq "NULL") { &my_die ("class_id  not found", $exp_id, $tmp_exp_name, $tmp_class_id, $uri, $PS_EXIT_CONFIG_ERROR); }
     118if (uc(&value_for_flag ($cmdflags, "NULL", "-exp_type"))  eq "NULL") { &my_die ("exp_type  not found", $exp_id, $tmp_exp_name, $tmp_class_id, $uri, $PS_EXIT_CONFIG_ERROR); }
    119119
    120120my $command = "$regtool -addprocessedimfile";
     
    128128
    129129# determine solar-system parameters
    130 my $longitude = &value_for_flag($cmdflags, "-longitude");
    131 my $latitude  = &value_for_flag($cmdflags, "-latitude");
    132 my $elevation = &value_for_flag($cmdflags, "-elevation");
    133 my $ra        = &value_for_flag($cmdflags, "-ra");
    134 my $dec       = &value_for_flag($cmdflags, "-decl");
    135 my $dateobs   = &value_for_flag($cmdflags, "-dateobs");
     130my $longitude = &value_for_flag($cmdflags, 0.0, "-longitude");
     131my $latitude  = &value_for_flag($cmdflags, 0.0, "-latitude");
     132my $elevation = &value_for_flag($cmdflags, 0.0, "-elevation");
     133my $ra        = &value_for_flag($cmdflags, 0.0, "-ra");
     134my $dec       = &value_for_flag($cmdflags, 0.0, "-decl");
     135my $dateobs   = &value_for_flag($cmdflags, 0.0, "-dateobs");
    136136
    137137# if the needed data is available, pass it to sunmoon:
     
    193193{
    194194    my $cmdflags = shift;
     195    my $default = shift;
    195196    my $flag = shift;
    196197
    197     my $value = 0.0;
     198    my $value = $default;
    198199    if ($cmdflags =~ m|$flag|) {
    199200        ($value) = $cmdflags =~ m|$flag\s+(\S+)|;
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/stack_skycell.pl

    r23352 r23594  
    203203# Perform stacking
    204204unless ($no_op) {
    205     my $command = "$ppStack $listName $outroot";
     205    my $command = "$ppStack -input $listName $outroot";
    206206    $command .= " -stats $outputStats" if $do_stats;;
    207207    $command .= " -recipe PPSTACK $recipe_ppStack";
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/summit_copy.pl

    r23352 r23594  
    4646
    4747pod2usage( -msg => "Unknown option: @ARGV", -exitval => 2 ) if @ARGV;
    48 pod2usage( -msg => "Required options: --uri --filename --exp_name --inst --telescope --class --class_id --workdir",
     48pod2usage( -msg => "Required options: --uri --filename --exp_name --inst --telescope --class --class_id",
    4949       -exitval => 3)
    5050    unless defined $uri
     
    5454    and defined $telescope
    5555    and defined $class
    56     and defined $class_id
    57     and defined $workdir;
     56    and defined $class_id;
    5857
    5958# Look for programs we need
     
    107106$command .= " -class_id $class_id";
    108107$command .= " -uri $filename";
    109 $command .= " -workdir $workdir";
     108# $command .= " -workdir $workdir";
    110109$command .= " -hostname $host";
    111 $command .= " -end_stage $end_stage" if defined $end_stage;
     110# $command .= " -end_stage $end_stage" if defined $end_stage;
    112111$command .= " -dbname $dbname" if defined $dbname;
    113112
  • branches/cnb_branches/cnb_branch_20090301/ippScripts/scripts/warp_skycell.pl

    r23352 r23594  
    3636}
    3737
    38 my ($warp_id, $skycell_id, $warp_skyfile_id, $tess_dir, $camera, $dbname, $outroot, $threads, $run_state, $verbose, $no_update, $no_op, $redirect, $save_temps);
     38my ($warp_id, $skycell_id, $warp_skyfile_id, $tess_dir, $camera, $dbname, $outroot, $threads, $run_state, $magicked, $verbose, $no_update, $no_op, $redirect, $save_temps);
    3939GetOptions(
    4040    'warp_id|i=s'         => \$warp_id, # Warp identifier
     
    4747    'threads=s'           => \$threads,   # Number of threads to use for pswarp
    4848    'run-state=s'         => \$run_state,  # 'new' or 'update'
     49    'magicked'            => \$magicked,  # input run has been magicked already?
    4950    'verbose'             => \$verbose,   # Print to stdout
    5051    'no-update'           => \$no_update, # Don't update the database?
     
    246247            $command .= " -tess_id $tess_dir";
    247248            $command .= " -path_base $outroot"; # needed for logfile lookups
     249            $command .= " -magicked" if $magicked;
    248250
    249251            $command .= " -uri $outputImage" if $accept;
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/Makefile.am

    r23352 r23594  
    11task_files = \
    2         detrend.mkruns.pro \
    32        detrend.norm.pro \
    43        detrend.process.pro \
     
    76        detrend.stack.pro \
    87        detrend.correct.pro \
     8        detrend.cleanup.pro \
    99        flatcorr.pro \
    1010        automate.pro \
     
    3636        simtest.flatcorr.config \
    3737        simtest.flatcorr.auto \
     38        simtest.ctemask.config \
     39        simtest.ctemask.auto \
    3840        simtest.stack.config \
    3941        simtest.stack.auto
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/chip.pro

    r23352 r23594  
    142142    book getword chipPendingImfile $pageName exp_id -var EXP_ID
    143143    book getword chipPendingImfile $pageName exp_tag -var EXP_TAG
     144    book getword chipPendingImfile $pageName raw_magicked -var RAW_MAGICKED
     145    book getword chipPendingImfile $pageName deburned -var DEBURNED
    144146    book getword chipPendingImfile $pageName chip_id -var CHIP_ID
    145147    book getword chipPendingImfile $pageName chip_imfile_id -var CHIP_IMFILE_ID
     
    151153    book getword chipPendingImfile $pageName state -var RUN_STATE
    152154
     155    if ("$RAW_MAGICKED" == "T")
     156        $MAGICKED_ARG = "--magicked"
     157    else
     158        $MAGICKED_ARG = ""
     159    end
     160
    153161    # specify choice of local or remote host based on camera and chip (class_id)
    154162    set.host.for.camera $CAMERA $CLASS_ID
     
    171179    stderr $LOGDIR/chip.imfile.log
    172180
    173     $run = chip_imfile.pl --threads @MAX_THREADS@ --exp_id $EXP_ID --chip_id $CHIP_ID --chip_imfile_id $CHIP_IMFILE_ID --class_id $CLASS_ID --uri $URI --camera $CAMERA --run-state $RUN_STATE --outroot $outroot --redirect-output
     181    $run = chip_imfile.pl --threads @MAX_THREADS@ --exp_id $EXP_ID --chip_id $CHIP_ID --chip_imfile_id $CHIP_IMFILE_ID --class_id $CLASS_ID --uri $URI --camera $CAMERA --run-state $RUN_STATE $MAGICKED_ARG --deburned $DEBURNED --outroot $outroot --redirect-output
    174182    if ("$REDUCTION" != "NULL")
    175183      $run = $run --reduction $REDUCTION
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/detrend.norm.pro

    r23352 r23594  
    99book init detPendingNormImfile
    1010book init detPendingNormExp
    11 
    12 book init detCleanupNormStatImfile
    13 book init detCleanupNormImfile
    14 book init detCleanupNormExp
    1511
    1612macro detnorm.reset
     
    1814  book init detPendingNormImfile
    1915  book init detPendingNormExp
    20 
    21   book init detCleanupNormStatImfile
    22   book init detCleanupNormImfile
    23   book init detCleanupNormExp
    2416end
    2517
     
    2820  book listbook detPendingNormImfile
    2921  book listbook detPendingNormExp
    30 
    31   book listbook detCleanupNormStatImfile
    32   book listbook detCleanupNormImfile
    33   book listbook detCleanupNormExp
    3422end
    3523
     
    5341    active true
    5442  end
    55 
    56   task detrend.cleanup.norm.load
    57     active true
    58   end
    59   task detrend.cleanup.norm.run
    60     active true
    61   end
    62   task detrend.cleanup.normexp.load
    63     active true
    64   end
    65   task detrend.cleanup.normexp.run
    66     active true
    67   end
    68   task detrend.cleanup.normstat.load
    69     active true
    70   end
    71   task detrend.cleanup.normstat.run
    72     active true
    73   end
    7443end
    7544
     
    9160  end
    9261  task detrend.normstat.run
    93     active false
    94   end
    95   task detrend.cleanup.norm.load
    96     active false
    97   end
    98   task detrend.cleanup.norm.run
    99     active false
    100   end
    101   task detrend.cleanup.normexp.load
    102     active false
    103   end
    104   task detrend.cleanup.normexp.run
    105     active false
    106   end
    107   task detrend.cleanup.normstat.load
    108     active false
    109   end
    110   task detrend.cleanup.normstat.run
    11162    active false
    11263  end
     
    11768$detPendingNormImfile_DB = 0
    11869$detPendingNormExp_DB = 0
    119 
    120 $detCleanupNormStatImfile_DB = 0
    121 $detCleanupNormImfile_DB = 0
    122 $detCleanupNormExp_DB = 0
    12370
    12471# select images ready for copy
     
    493440  end
    494441end
    495 
    496 ########## cleanup normstat ###########
    497 task           detrend.cleanup.normstat.load
    498   host         local
    499 
    500   periods      -poll $LOADPOLL
    501   periods      -exec $LOADEXEC
    502   periods      -timeout 30
    503   npending     1
    504   active       true
    505 
    506   stdout NULL
    507   stderr $LOGDIR/detrend.cleanup.normstat.log
    508 
    509   task.exec
    510     $run = dettool -pendingcleanup_normalizedstat
    511     if ($DB:n == 0)
    512       option DEFAULT
    513     else
    514       # save the DB name for the exit tasks
    515       option $DB:$detCleanupNormStatImfile_DB
    516       $run = $run -dbname $DB:$detCleanupNormStatImfile_DB
    517       $detCleanupNormStatImfile_DB ++
    518       if ($detCleanupNormStatImfile_DB >= $DB:n) set detCleanupNormStatImfile_DB = 0
    519     end
    520     add_poll_args run
    521     command $run
    522   end
    523 
    524   # success
    525   task.exit    0
    526     # convert 'stdout' to book format
    527     ipptool2book stdout detCleanupNormStatImfile -key det_id:iteration -uniq -setword dbname $options:0 -setword pantaskState INIT
    528     if ($VERBOSE > 2)
    529       book listbook detCleanupNormStatImfile
    530     end
    531 
    532     # delete existing entries in the appropriate pantaskStates
    533     process_cleanup detCleanupNormStatImfile
    534   end
    535 
    536   # locked list
    537   task.exit    default
    538     showcommand failure
    539   end
    540 
    541   task.exit    crash
    542     showcommand crash
    543   end
    544 
    545   # operation times out?
    546   task.exit    timeout
    547     showcommand timeout
    548   end
    549 end
    550 
    551 # run the ipp_cleanup.pl script on pending images
    552 task           detrend.cleanup.normstat.run
    553   periods      -poll $RUNPOLL
    554   periods      -exec $RUNEXEC
    555   periods      -timeout 60
    556   active       true
    557 
    558   task.exec
    559     book npages detCleanupNormStatImfile -var N
    560     if ($N == 0) break
    561     if ($NETWORK == 0) break
    562    
    563     # look for new images in detCleanupNormStatImfile (pantaskState == INIT)
    564     book getpage detCleanupNormStatImfile 0 -var pageName -key pantaskState INIT
    565     if ("$pageName" == "NULL") break
    566 
    567     book setword detCleanupNormStatImfile $pageName pantaskState RUN
    568     book getword detCleanupNormStatImfile $pageName det_id   -var DET_ID   
    569     book getword detCleanupNormStatImfile $pageName iteration -var ITERATION
    570     book getword detCleanupNormStatImfile $pageName camera -var CAMERA
    571     book getword detCleanupNormStatImfile $pageName state -var CLEANUP_MODE
    572     book getword detCleanupNormStatImfile $pageName dbname -var DBNAME
    573 
    574     # specify choice of local or remote host based on camera and chip (class_id)
    575     set.host.for.camera $CAMERA FPA
    576 
    577     stdout $LOGDIR/detrend.cleanup.normstat.log
    578     stderr $LOGDIR/detrend.cleanup.normstat.log
    579 
    580     # XXX is everything listed here needed?
    581     $run = ipp_cleanup.pl --stage detrend.normstat.imfile --stage_id $DET_ID --iteration $ITERATION --camera $CAMERA --mode $CLEANUP_MODE
    582     add_standard_args run
    583 
    584     # save the pageName for future reference below
    585     options $pageName
    586 
    587     # create the command line
    588     if ($VERBOSE > 1)
    589       echo command $run
    590     end
    591     command $run
    592   end
    593 
    594   # default exit status
    595   task.exit    default
    596     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
    602   end
    603 
    604   # operation timed out?
    605   task.exit    timeout
    606     showcommand timeout
    607     book setword detCleanupNormStatImfile $options:0 pantaskState TIMEOUT
    608   end
    609 end
    610  
    611 ########## cleanup norm (normalized.imfile) ###########
    612 task           detrend.cleanup.norm.load
    613   host         local
    614 
    615   periods      -poll $LOADPOLL
    616   periods      -exec $LOADEXEC
    617   periods      -timeout 30
    618   npending     1
    619   active       true
    620 
    621   stdout NULL
    622   stderr $LOGDIR/detrend.cleanup.norm.log
    623 
    624   task.exec
    625     $run = dettool -pendingcleanup_normalizedimfile
    626     if ($DB:n == 0)
    627       option DEFAULT
    628     else
    629       # save the DB name for the exit tasks
    630       option $DB:$detCleanupNormImfile_DB
    631       $run = $run -dbname $DB:$detCleanupNormImfile_DB
    632       $detCleanupNormImfile_DB ++
    633       if ($detCleanupNormImfile_DB >= $DB:n) set detCleanupNormImfile_DB = 0
    634     end
    635     add_poll_args run
    636     command $run
    637   end
    638 
    639   # success
    640   task.exit    0
    641     # convert 'stdout' to book format
    642     ipptool2book stdout detCleanupNormImfile -key det_id:iteration:class_id -uniq -setword dbname $options:0 -setword pantaskState INIT
    643     if ($VERBOSE > 2)
    644       book listbook detCleanupNormImfile
    645     end
    646 
    647     # delete existing entries in the appropriate pantaskStates
    648     process_cleanup detCleanupNormImfile
    649   end
    650 
    651   # locked list
    652   task.exit    default
    653     showcommand failure
    654   end
    655 
    656   task.exit    crash
    657     showcommand crash
    658   end
    659 
    660   # operation times out?
    661   task.exit    timeout
    662     showcommand timeout
    663   end
    664 end
    665 
    666 # run the ipp_cleanup.pl script on pending images
    667 task           detrend.cleanup.norm.run
    668   periods      -poll $RUNPOLL
    669   periods      -exec $RUNEXEC
    670   periods      -timeout 60
    671   active       true
    672 
    673   task.exec
    674     book npages detCleanupNormImfile -var N
    675     if ($N == 0) break
    676     if ($NETWORK == 0) break
    677    
    678     # look for new images in detCleanupNormImfile (pantaskState == INIT)
    679     book getpage detCleanupNormImfile 0 -var pageName -key pantaskState INIT
    680     if ("$pageName" == "NULL") break
    681 
    682     book setword detCleanupNormImfile $pageName pantaskState RUN
    683     book getword detCleanupNormImfile $pageName det_id   -var DET_ID   
    684     book getword detCleanupNormImfile $pageName iteration -var ITERATION
    685     book getword detCleanupNormImfile $pageName class_id -var CLASS_ID
    686     book getword detCleanupNormImfile $pageName camera -var CAMERA
    687     book getword detCleanupNormImfile $pageName state -var CLEANUP_MODE
    688     book getword detCleanupNormImfile $pageName dbname -var DBNAME
    689 
    690     # specify choice of local or remote host based on camera and chip (class_id)
    691     set.host.for.camera $CAMERA FPA
    692 
    693     stdout $LOGDIR/detrend.cleanup.norm.log
    694     stderr $LOGDIR/detrend.cleanup.norm.log
    695 
    696     # XXX is everything listed here needed?
    697     $run = ipp_cleanup.pl --stage detrend.norm.imfile --stage_id $DET_ID --iteration $ITERATION --class_id $CLASS_ID --camera $CAMERA --mode $CLEANUP_MODE
    698     add_standard_args run
    699 
    700     # save the pageName for future reference below
    701     options $pageName
    702 
    703     # create the command line
    704     if ($VERBOSE > 1)
    705       echo command $run
    706     end
    707     command $run
    708   end
    709 
    710   # default exit status
    711   task.exit    default
    712     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
    718   end
    719 
    720   # operation timed out?
    721   task.exit    timeout
    722     showcommand timeout
    723     book setword detCleanupNormImfile $options:0 pantaskState TIMEOUT
    724   end
    725 end
    726  
    727 ########## cleanup normexp ###########
    728 task           detrend.cleanup.normexp.load
    729   host         local
    730 
    731   periods      -poll $LOADPOLL
    732   periods      -exec $LOADEXEC
    733   periods      -timeout 30
    734   npending     1
    735   active       true
    736 
    737   stdout NULL
    738   stderr $LOGDIR/detrend.normexp.cleanup.log
    739 
    740   task.exec
    741     $run = dettool -pendingcleanup_normalizedexp
    742     if ($DB:n == 0)
    743       option DEFAULT
    744     else
    745       # save the DB name for the exit tasks
    746       option $DB:$detCleanupNormExp_DB
    747       $run = $run -dbname $DB:$detCleanupNormExp_DB
    748       $detCleanupNormExp_DB ++
    749       if ($detCleanupNormExp_DB >= $DB:n) set detCleanupNormExp_DB = 0
    750     end
    751     add_poll_args run
    752     command $run
    753   end
    754 
    755   # success
    756   task.exit    0
    757     # convert 'stdout' to book format
    758     ipptool2book stdout detCleanupNormExp -key det_id:iteration -uniq -setword dbname $options:0 -setword pantaskState INIT
    759     if ($VERBOSE > 2)
    760       book listbook detCleanupNormExp
    761     end
    762 
    763     # delete existing entries in the appropriate pantaskStates
    764     process_cleanup detCleanupNormExp
    765   end
    766 
    767   # locked list
    768   task.exit    default
    769     showcommand failure
    770   end
    771 
    772   task.exit    crash
    773     showcommand crash
    774   end
    775 
    776   # operation times out?
    777   task.exit    timeout
    778     showcommand timeout
    779   end
    780 end
    781 
    782 # run the ipp_cleanup.pl script on pending images
    783 task           detrend.cleanup.normexp.run
    784   periods      -poll $RUNPOLL
    785   periods      -exec $RUNEXEC
    786   periods      -timeout 60
    787   active       true
    788 
    789   task.exec
    790     book npages detCleanupNormExp -var N
    791     if ($N == 0) break
    792     if ($NETWORK == 0) break
    793    
    794     # look for new images in detCleanupNormExp (pantaskState == INIT)
    795     book getpage detCleanupNormExp 0 -var pageName -key pantaskState INIT
    796     if ("$pageName" == "NULL") break
    797 
    798     book setword detCleanupNormExp $pageName pantaskState RUN
    799     book getword detCleanupNormExp $pageName det_id   -var DET_ID   
    800     book getword detCleanupNormExp $pageName iteration -var ITERATION
    801     book getword detCleanupNormExp $pageName camera -var CAMERA
    802     book getword detCleanupNormExp $pageName state -var CLEANUP_MODE
    803     book getword detCleanupNormExp $pageName dbname -var DBNAME
    804 
    805     # specify choice of local or remote host based on camera and chip (class_id)
    806     set.host.for.camera $CAMERA FPA
    807 
    808     stdout $LOGDIR/detrend.cleanup.normexp.log
    809     stderr $LOGDIR/detrend.cleanup.normexp.log
    810 
    811     # XXX is everything listed here needed?
    812     $run = ipp_cleanup.pl --stage detrend.norm.exp --stage_id $DET_ID --iteration $ITERATION --camera $CAMERA --mode $CLEANUP_MODE
    813     add_standard_args run
    814 
    815     # save the pageName for future reference below
    816     options $pageName
    817 
    818     # create the command line
    819     if ($VERBOSE > 1)
    820       echo command $run
    821     end
    822     command $run
    823   end
    824 
    825   # default exit status
    826   task.exit    default
    827     process_exit detCleanupNormExp $options:0 $JOB_STATUS
    828   end
    829 
    830   task.exit    crash
    831     showcommand crash
    832     book setword detCleanupNormExp $options:0 pantaskState CRASH
    833   end
    834 
    835   # operation timed out?
    836   task.exit    timeout
    837     showcommand timeout
    838     book setword detCleanupNormExp $options:0 pantaskState TIMEOUT
    839   end
    840 end
    841  
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/detrend.process.pro

    r23352 r23594  
    88book init detPendingProcessedImfile
    99book init detPendingProcessedExp
    10 book init detCleanupProcessedImfile
    11 book init detCleanupProcessedExp
    1210
    1311macro detproc.reset
    1412  book init detPendingProcessedImfile
    1513  book init detPendingProcessedExp
    16   book init detCleanupProcessedImfile
    17   book init detCleanupProcessedExp
    1814end
    1915
     
    2319  echo detPendingProcessedExp
    2420  book listbook detPendingProcessedExp
    25   echo detCleanupProcessedImfile
    26   book listbook detCleanupProcessedImfile
    27   echo detCleanupProcessedExp
    28   book listbook detCleanupProcessedExp
    2921end
    3022
     
    4234    active true
    4335  end
    44   task detrend.cleanup.process.load
    45     active true
    46   end
    47   task detrend.cleanup.process.run
    48     active true
    49   end
    50   task detrend.cleanup.processexp.load
    51     active true
    52   end
    53   task detrend.cleanup.processexp.run
    54     active true
    55   end
    5636end
    5737
     
    6949    active false
    7050  end
    71   task detrend.cleanup.process.load
    72     active false
    73   end
    74   task detrend.cleanup.process.run
    75     active false
    76   end
    77   task detrend.cleanup.processexp.load
    78     active false
    79   end
    80   task detrend.cleanup.processexp.run
    81     active false
    82   end
    8351end
    8452
     
    8755$detPendingProcessedImfile_DB = 0
    8856$detPendingProcessedExp_DB = 0
    89 $detCleanupProcessedImfile_DB = 0
    90 $detCleanupProcessedExp_DB = 0
    9157
    9258# select images ready for copy
     
    347313  end
    348314end
    349 
    350 ######## cleanup process imfile ########
    351 task           detrend.cleanup.process.load
    352   host         local
    353 
    354   periods      -poll $LOADPOLL
    355   periods      -exec $LOADEXEC
    356   periods      -timeout 30
    357   npending     1
    358   active       true
    359 
    360   stdout NULL
    361   stderr $LOGDIR/detrend.cleanup.process.imfile.log
    362 
    363   task.exec
    364     $run = dettool -pendingcleanup_processedimfile
    365     if ($DB:n == 0)
    366       option DEFAULT
    367     else
    368       # save the DB name for the exit tasks
    369       option $DB:$detCleanupProcessedImfile_DB
    370       $run = $run -dbname $DB:$detCleanupProcessedImfile_DB
    371       $detCleanupProcessedImfile_DB ++
    372       if ($detCleanupProcessedImfile_DB >= $DB:n) set detCleanupProcessedImfile_DB = 0
    373     end
    374     add_poll_args run
    375     command $run
    376   end
    377 
    378   # success
    379   task.exit    0
    380     # convert 'stdout' to book format
    381     ipptool2book stdout detCleanupProcessedImfile -key det_id:exp_id:class_id -uniq -setword dbname $options:0 -setword pantaskState INIT
    382     if ($VERBOSE > 2)
    383       book listbook detCleanupProcessedImfile
    384     end
    385 
    386     # delete existing entries in the appropriate pantaskStates
    387     process_cleanup detCleanupProcessedImfile
    388   end
    389 
    390   # locked list
    391   task.exit    default
    392     showcommand failure
    393   end
    394 
    395   task.exit    crash
    396     showcommand crash
    397   end
    398 
    399   # operation times out?
    400   task.exit    timeout
    401     showcommand timeout
    402   end
    403 end
    404 
    405 # run the ipp_cleanup.pl script on pending images
    406 task           detrend.cleanup.process.run
    407   periods      -poll $RUNPOLL
    408   periods      -exec $RUNEXEC
    409   periods      -timeout 60
    410   active       true
    411 
    412   task.exec
    413     book npages detCleanupProcessedImfile -var N
    414     if ($N == 0) break
    415     if ($NETWORK == 0) break
    416    
    417     # look for new images in detCleanupProcessedImfile (pantaskState == INIT)
    418     book getpage detCleanupProcessedImfile 0 -var pageName -key pantaskState INIT
    419     if ("$pageName" == "NULL") break
    420 
    421     book setword detCleanupProcessedImfile $pageName pantaskState RUN
    422     book getword detCleanupProcessedImfile $pageName det_id   -var DET_ID   
    423     book getword detCleanupProcessedImfile $pageName exp_id   -var EXP_ID   
    424     book getword detCleanupProcessedImfile $pageName class_id -var CLASS_ID
    425     book getword detCleanupProcessedImfile $pageName camera   -var CAMERA
    426     book getword detCleanupProcessedImfile $pageName state    -var CLEANUP_MODE
    427     book getword detCleanupProcessedImfile $pageName dbname   -var DBNAME
    428 
    429     # specify choice of local or remote host based on camera and chip (class_id)
    430     set.host.for.camera $CAMERA FPA
    431 
    432     stdout $LOGDIR/detrend.cleanup.process.imfile.log
    433     stderr $LOGDIR/detrend.cleanup.process.imfile.log
    434 
    435     # XXX is everything listed here needed?
    436     $run = ipp_cleanup.pl --stage detrend.process.imfile --stage_id $DET_ID --exp_id $EXP_ID --class_id $CLASS_ID --camera $CAMERA --mode $CLEANUP_MODE
    437     add_standard_args run
    438 
    439     # save the pageName for future reference below
    440     options $pageName
    441 
    442     # create the command line
    443     if ($VERBOSE > 1)
    444       echo command $run
    445     end
    446     command $run
    447   end
    448 
    449   # default exit status
    450   task.exit    default
    451     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
    459   end
    460 
    461   # operation timed out?
    462   task.exit    timeout
    463     showcommand timeout
    464     book setword detCleanupProcessedImfile $options:0 pantaskState TIMEOUT
    465   end
    466 end
    467  
    468 
    469 ######## cleanup process exp ########
    470 task           detrend.cleanup.processexp.load
    471   host         local
    472 
    473   periods      -poll $LOADPOLL
    474   periods      -exec $LOADEXEC
    475   periods      -timeout 30
    476   npending     1
    477   active       true
    478 
    479   stdout NULL
    480   stderr $LOGDIR/detrend.cleanup.process.exp.log
    481 
    482   task.exec
    483     $run = dettool -pendingcleanup_processedexp
    484     if ($DB:n == 0)
    485       option DEFAULT
    486     else
    487       # save the DB name for the exit tasks
    488       option $DB:$detCleanupProcessedExp_DB
    489       $run = $run -dbname $DB:$detCleanupProcessedExp_DB
    490       $detCleanupProcessedExp_DB ++
    491       if ($detCleanupProcessedExp_DB >= $DB:n) set detCleanupProcessedExp_DB = 0
    492     end
    493     add_poll_args run
    494     command $run
    495   end
    496 
    497   # success
    498   task.exit    0
    499     # convert 'stdout' to book format
    500     ipptool2book stdout detCleanupProcessedExp -key det_id:exp_id -uniq -setword dbname $options:0 -setword pantaskState INIT
    501     if ($VERBOSE > 2)
    502       book listbook detCleanupProcessedExp
    503     end
    504 
    505     # delete existing entries in the appropriate pantaskStates
    506     process_cleanup detCleanupProcessedExp
    507   end
    508 
    509   # locked list
    510   task.exit    default
    511     showcommand failure
    512   end
    513 
    514   task.exit    crash
    515     showcommand crash
    516   end
    517 
    518   # operation times out?
    519   task.exit    timeout
    520     showcommand timeout
    521   end
    522 end
    523 
    524 # run the ipp_cleanup.pl script on pending images
    525 task           detrend.cleanup.processexp.run
    526   periods      -poll $RUNPOLL
    527   periods      -exec $RUNEXEC
    528   periods      -timeout 60
    529   active       true
    530 
    531   task.exec
    532     book npages detCleanupProcessedExp -var N
    533     if ($N == 0) break
    534     if ($NETWORK == 0) break
    535    
    536     # look for new images in detCleanupProcessedExp (pantaskState == INIT)
    537     book getpage detCleanupProcessedExp 0 -var pageName -key pantaskState INIT
    538     if ("$pageName" == "NULL") break
    539 
    540     book setword detCleanupProcessedExp $pageName pantaskState RUN
    541     book getword detCleanupProcessedExp $pageName det_id   -var DET_ID   
    542     book getword detCleanupProcessedExp $pageName exp_id   -var EXP_ID   
    543     book getword detCleanupProcessedExp $pageName camera -var CAMERA
    544     book getword detCleanupProcessedExp $pageName state -var CLEANUP_MODE
    545     book getword detCleanupProcessedExp $pageName dbname -var DBNAME
    546 
    547     # specify choice of local or remote host based on camera and chip (class_id)
    548     set.host.for.camera $CAMERA FPA
    549 
    550     stdout $LOGDIR/detrend.cleanup.process.exp.log
    551     stderr $LOGDIR/detrend.cleanup.process.exp.log
    552 
    553     # XXX is everything listed here needed?
    554     $run = ipp_cleanup.pl --stage detrend.process.exp --stage_id $DET_ID --exp_id $EXP_ID --camera $CAMERA --mode $CLEANUP_MODE
    555     add_standard_args run
    556 
    557     # save the pageName for future reference below
    558     options $pageName
    559 
    560     # create the command line
    561     if ($VERBOSE > 1)
    562       echo command $run
    563     end
    564     command $run
    565   end
    566 
    567   # default exit status
    568   task.exit    default
    569     process_exit detCleanupProcessedExp $options:0 $JOB_STATUS
    570   end
    571 
    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 
    579   # operation timed out?
    580   task.exit    timeout
    581     showcommand timeout
    582     book setword detCleanupProcessedExp $options:0 pantaskState TIMEOUT
    583   end
    584 end
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/detrend.resid.pro

    r23352 r23594  
    88book init detPendingResidImfile
    99book init detPendingResidExp
    10 book init detCleanupResidImfile
    11 book init detCleanupResidExp
    1210
    1311macro detresid.reset
    1412  book init detPendingResidImfile
    1513  book init detPendingResidExp
    16   book init detCleanupResidImfile
    17   book init detCleanupResidExp
    1814end
    1915
     
    2117  book listbook detPendingResidImfile
    2218  book listbook detPendingResidExp
    23   book listbook detCleanupResidImfile
    24   book listbook detCleanupResidExp
    2519end
    2620
     
    3832    active true
    3933  end
    40   task detrend.cleanup.resid.load
    41     active true
    42   end
    43   task detrend.cleanup.resid.run
    44     active true
    45   end
    46   task detrend.cleanup.residexp.load
    47     active true
    48   end
    49   task detrend.cleanup.residexp.run
    50     active true
    51   end
    5234end
    5335
     
    6547    active false
    6648  end
    67   task detrend.cleanup.resid.load
    68     active false
    69   end
    70   task detrend.cleanup.resid.run
    71     active false
    72   end
    73   task detrend.cleanup.residexp.load
    74     active false
    75   end
    76   task detrend.cleanup.residexp.run
    77     active false
    78   end
    7949end
    8050
     
    8252$detPendingResidImfile_DB = 0
    8353$detPendingResidExp_DB = 0
    84 $detCleanupResidImfile_DB = 0
    85 $detCleanupResidExp_DB = 0
    8654
    8755# select images ready for copy
     
    348316  end
    349317end
    350 
    351 ######## cleanup resid imfile ########
    352 task           detrend.cleanup.resid.load
    353   host         local
    354 
    355   periods      -poll $LOADPOLL
    356   periods      -exec $LOADEXEC
    357   periods      -timeout 30
    358   npending     1
    359   active       true
    360 
    361   stdout NULL
    362   stderr $LOGDIR/detrend.cleanup.resid.imfile.log
    363 
    364   task.exec
    365     $run = dettool -pendingcleanup_residimfile
    366     if ($DB:n == 0)
    367       option DEFAULT
    368     else
    369       # save the DB name for the exit tasks
    370       option $DB:$detCleanupResidImfile_DB
    371       $run = $run -dbname $DB:$detCleanupResidImfile_DB
    372       $detCleanupResidImfile_DB ++
    373       if ($detCleanupResidImfile_DB >= $DB:n) set detCleanupResidImfile_DB = 0
    374     end
    375     add_poll_args run
    376     command $run
    377   end
    378 
    379   # success
    380   task.exit    0
    381     # convert 'stdout' to book format
    382     ipptool2book stdout detCleanupResidImfile -key det_id:iteration:exp_id:class_id -uniq -setword dbname $options:0 -setword pantaskState INIT
    383     if ($VERBOSE > 2)
    384       book listbook detCleanupResidImfile
    385     end
    386 
    387     # delete existing entries in the appropriate pantaskStates
    388     process_cleanup detCleanupResidImfile
    389   end
    390 
    391   # locked list
    392   task.exit    default
    393     showcommand failure
    394   end
    395 
    396   task.exit    crash
    397     showcommand crash
    398   end
    399 
    400   # operation times out?
    401   task.exit    timeout
    402     showcommand timeout
    403   end
    404 end
    405 
    406 # run the ipp_cleanup.pl script on pending images
    407 task           detrend.cleanup.resid.run
    408   periods      -poll $RUNPOLL
    409   periods      -exec $RUNEXEC
    410   periods      -timeout 60
    411   active       true
    412 
    413   task.exec
    414     book npages detCleanupResidImfile -var N
    415     if ($N == 0) break
    416     if ($NETWORK == 0) break
    417    
    418     # look for new images in detCleanupResidImfile (pantaskState == INIT)
    419     book getpage detCleanupResidImfile 0 -var pageName -key pantaskState INIT
    420     if ("$pageName" == "NULL") break
    421 
    422     book setword detCleanupResidImfile $pageName pantaskState RUN
    423     book getword detCleanupResidImfile $pageName det_id   -var DET_ID   
    424     book getword detCleanupResidImfile $pageName exp_id   -var EXP_ID   
    425     book getword detCleanupResidImfile $pageName class_id -var CLASS_ID
    426     book getword detCleanupResidImfile $pageName iteration -var ITERATION     
    427     book getword detCleanupResidImfile $pageName camera -var CAMERA
    428     book getword detCleanupResidImfile $pageName state -var CLEANUP_MODE
    429     book getword detCleanupResidImfile $pageName dbname -var DBNAME
    430 
    431     # specify choice of local or remote host based on camera and chip (class_id)
    432     set.host.for.camera $CAMERA FPA
    433 
    434     stdout $LOGDIR/detrend.cleanup.resid.imfile.log
    435     stderr $LOGDIR/detrend.cleanup.resid.imfile.log
    436 
    437     # XXX is everything listed here needed?
    438     $run = ipp_cleanup.pl --stage detrend.resid.imfile --stage_id $DET_ID --exp_id $EXP_ID --class_id $CLASS_ID --iteration $ITERATION --camera $CAMERA --mode $CLEANUP_MODE
    439     add_standard_args run
    440 
    441     # save the pageName for future reference below
    442     options $pageName
    443 
    444     # create the command line
    445     if ($VERBOSE > 1)
    446       echo command $run
    447     end
    448     command $run
    449   end
    450 
    451   # default exit status
    452   task.exit    default
    453     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
    461   end
    462 
    463   # operation timed out?
    464   task.exit    timeout
    465     showcommand timeout
    466     book setword detCleanupResidImfile $options:0 pantaskState TIMEOUT
    467   end
    468 end
    469  
    470 
    471 ######## cleanup resid exp ########
    472 task           detrend.cleanup.residexp.load
    473   host         local
    474 
    475   periods      -poll $LOADPOLL
    476   periods      -exec $LOADEXEC
    477   periods      -timeout 30
    478   npending     1
    479   active       true
    480 
    481   stdout NULL
    482   stderr $LOGDIR/detrend.cleanup.resid.exp.log
    483 
    484   task.exec
    485     $run = dettool -pendingcleanup_residexp
    486     if ($DB:n == 0)
    487       option DEFAULT
    488     else
    489       # save the DB name for the exit tasks
    490       option $DB:$detCleanupResidExp_DB
    491       $run = $run -dbname $DB:$detCleanupResidExp_DB
    492       $detCleanupResidExp_DB ++
    493       if ($detCleanupResidExp_DB >= $DB:n) set detCleanupResidExp_DB = 0
    494     end
    495     add_poll_args run
    496     command $run
    497   end
    498 
    499   # success
    500   task.exit    0
    501     # convert 'stdout' to book format
    502     ipptool2book stdout detCleanupResidExp -key det_id:iteration:exp_id -uniq -setword dbname $options:0 -setword pantaskState INIT
    503     if ($VERBOSE > 2)
    504       book listbook detCleanupResidExp
    505     end
    506 
    507     # delete existing entries in the appropriate pantaskStates
    508     process_cleanup detCleanupResidExp
    509   end
    510 
    511   # locked list
    512   task.exit    default
    513     showcommand failure
    514   end
    515 
    516   task.exit    crash
    517     showcommand crash
    518   end
    519 
    520   # operation times out?
    521   task.exit    timeout
    522     showcommand timeout
    523   end
    524 end
    525 
    526 # run the ipp_cleanup.pl script on pending images
    527 task           detrend.cleanup.residexp.run
    528   periods      -poll $RUNPOLL
    529   periods      -exec $RUNEXEC
    530   periods      -timeout 60
    531   active       true
    532 
    533   task.exec
    534     book npages detCleanupResidExp -var N
    535     if ($N == 0) break
    536     if ($NETWORK == 0) break
    537    
    538     # look for new images in detCleanupResidExp (pantaskState == INIT)
    539     book getpage detCleanupResidExp 0 -var pageName -key pantaskState INIT
    540     if ("$pageName" == "NULL") break
    541 
    542     book setword detCleanupResidExp $pageName pantaskState RUN
    543     book getword detCleanupResidExp $pageName det_id    -var DET_ID   
    544     book getword detCleanupResidExp $pageName exp_id    -var EXP_ID   
    545     book getword detCleanupResidExp $pageName iteration -var ITERATION
    546     book getword detCleanupResidExp $pageName camera    -var CAMERA
    547     book getword detCleanupResidExp $pageName state     -var CLEANUP_MODE
    548     book getword detCleanupResidExp $pageName dbname    -var DBNAME
    549 
    550     # specify choice of local or remote host based on camera and chip (class_id)
    551     set.host.for.camera $CAMERA FPA
    552 
    553     stdout $LOGDIR/detrend.cleanup.resid.exp.log
    554     stderr $LOGDIR/detrend.cleanup.resid.exp.log
    555 
    556     # XXX is everything listed here needed?
    557     $run = ipp_cleanup.pl --stage detrend.resid.exp --stage_id $DET_ID --exp_id $EXP_ID --class_id $CLASS_ID --camera $CAMERA --mode $CLEANUP_MODE
    558     add_standard_args run
    559 
    560     # save the pageName for future reference below
    561     options $pageName
    562 
    563     # create the command line
    564     if ($VERBOSE > 1)
    565       echo command $run
    566     end
    567     command $run
    568   end
    569 
    570   # default exit status
    571   task.exit    default
    572     process_exit detCleanupResidExp $options:0 $JOB_STATUS
    573   end
    574 
    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 
    582   # operation timed out?
    583   task.exit    timeout
    584     showcommand timeout
    585     book setword detCleanupResidExp $options:0 pantaskState TIMEOUT
    586   end
    587 end
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/detrend.stack.pro

    r23352 r23594  
    77
    88book init detPendingStackedImfile
    9 book init detCleanupStackedImfile
    109
    1110macro detstack.reset
    1211  book init detPendingStackedImfile
    13   book init detCleanupStackedImfile
    1412end
    1513
     
    1715  echo detPendingStackedImfile
    1816  book listbook detPendingStackedImfile
    19   echo detCleanupStackedImfile
    20   book listbook detCleanupStackedImfile
    2117end
    2218
     
    2622  end
    2723  task detrend.stack.run
    28     active true
    29   end
    30   task detrend.cleanup.stack.load
    31     active true
    32   end
    33   task detrend.cleanup.stack.run
    3424    active true
    3525  end
     
    4333    active false
    4434  end
    45   task detrend.cleanup.stack.load
    46     active false
    47   end
    48   task detrend.cleanup.stack.run
    49     active false
    50   end
    5135end
    5236
    5337# this variable will cycle through the known database names
    5438$detPendingStackedImfile_DB = 0
    55 $detCleanupStackedImfile_DB = 0
    5639
    5740# select images ready for detrend_stack.pl
     
    182165  end
    183166end
    184 
    185 ########## cleanup stack ###########
    186 task           detrend.cleanup.stack.load
    187   host         local
    188 
    189   periods      -poll $LOADPOLL
    190   periods      -exec $LOADEXEC
    191   periods      -timeout 30
    192   npending     1
    193   active       true
    194 
    195   stdout NULL
    196   stderr $LOGDIR/detrend.cleanup.stack.log
    197 
    198   task.exec
    199     $run = dettool -pendingcleanup_stacked
    200     if ($DB:n == 0)
    201       option DEFAULT
    202     else
    203       # save the DB name for the exit tasks
    204       option $DB:$detCleanupStackedImfile_DB
    205       $run = $run -dbname $DB:$detCleanupStackedImfile_DB
    206       $detCleanupStackedImfile_DB ++
    207       if ($detCleanupStackedImfile_DB >= $DB:n) set detCleanupStackedImfile_DB = 0
    208     end
    209     add_poll_args run
    210     command $run
    211   end
    212 
    213   # success
    214   task.exit    0
    215     # convert 'stdout' to book format
    216     ipptool2book stdout detCleanupStackedImfile -key det_id:iteration:class_id -uniq -setword dbname $options:0 -setword pantaskState INIT
    217     if ($VERBOSE > 2)
    218       book listbook detCleanupStackedImfile
    219     end
    220 
    221     # delete existing entries in the appropriate pantaskStates
    222     process_cleanup detCleanupStackedImfile
    223   end
    224 
    225   # locked list
    226   task.exit    default
    227     showcommand failure
    228   end
    229 
    230   task.exit    crash
    231     showcommand crash
    232   end
    233 
    234   # operation times out?
    235   task.exit    timeout
    236     showcommand timeout
    237   end
    238 end
    239 
    240 # run the ipp_cleanup.pl script on pending images
    241 task           detrend.cleanup.stack.run
    242   periods      -poll $RUNPOLL
    243   periods      -exec $RUNEXEC
    244   periods      -timeout 60
    245   active       true
    246 
    247   task.exec
    248     book npages detCleanupStackedImfile -var N
    249     if ($N == 0) break
    250     if ($NETWORK == 0) break
    251    
    252     # look for new images in detCleanupStackedImfile (pantaskState == INIT)
    253     book getpage detCleanupStackedImfile 0 -var pageName -key pantaskState INIT
    254     if ("$pageName" == "NULL") break
    255 
    256     book setword detCleanupStackedImfile $pageName pantaskState RUN
    257     book getword detCleanupStackedImfile $pageName det_id   -var DET_ID   
    258     book getword detCleanupStackedImfile $pageName iteration -var ITERATION
    259     book getword detCleanupStackedImfile $pageName class_id -var CLASS_ID
    260     book getword detCleanupStackedImfile $pageName camera -var CAMERA
    261     book getword detCleanupStackedImfile $pageName state -var CLEANUP_MODE
    262     book getword detCleanupStackedImfile $pageName dbname -var DBNAME
    263 
    264     # specify choice of local or remote host based on camera and chip (class_id)
    265     set.host.for.camera $CAMERA FPA
    266 
    267     stdout $LOGDIR/detrend.cleanup.stack.log
    268     stderr $LOGDIR/detrend.cleanup.stack.log
    269 
    270     # XXX is everything listed here needed?
    271     $run = ipp_cleanup.pl --stage detrend.stack.imfile --stage_id $DET_ID --iteration $ITERATION --class_id $CLASS_ID --camera $CAMERA --mode $CLEANUP_MODE
    272     add_standard_args run
    273 
    274     # save the pageName for future reference below
    275     options $pageName
    276 
    277     # create the command line
    278     if ($VERBOSE > 1)
    279       echo command $run
    280     end
    281     command $run
    282   end
    283 
    284   # default exit status
    285   task.exit    default
    286     process_exit detCleanupStackedImfile $options:0 $JOB_STATUS
    287   end
    288 
    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 
    296   # operation timed out?
    297   task.exit    timeout
    298     showcommand timeout
    299     book setword detCleanupStackedImfile $options:0 pantaskState TIMEOUT
    300   end
    301 end
    302  
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/dist.pro

    r23352 r23594  
    134134    book getword distToProcess $pageName outroot -var OUTROOT
    135135    book getword distToProcess $pageName dbname -var DBNAME
     136    if ("$CLEAN" = "T")
     137        $CLEAN_ARG = "--clean"
     138    else
     139        $CLEAN_ARG = ""
     140    end
     141    # magicked is output as integer due to the union in the sql
     142    if ($MAGICKED)
     143        $MAGICKED_ARG = "--magicked"
     144    else
     145        $MAGICKED_ARG = ""
     146    end
    136147
    137148#    set.host.for.camera $CAMERA $MAGIC_ID
     
    141152    sprintf logfile "%s/dist.%s.%s.log" $OUTROOT $DIST_ID $COMPONENT
    142153
    143     $run = dist_component.pl --dist_id $DIST_ID --camera $CAMERA --stage $STAGE --stage_id $STAGE_ID --component $COMPONENT --path_base $PATH_BASE --chip_path_base $CHIP_PATH_BASE --state $STATE --data_state $DATA_STATE --magicked $MAGICKED --clean $CLEAN --outroot $OUTROOT --logfile $logfile
     154    $run = dist_component.pl --dist_id $DIST_ID --camera $CAMERA --stage $STAGE --stage_id $STAGE_ID --component $COMPONENT --path_base $PATH_BASE --chip_path_base $CHIP_PATH_BASE --state $STATE --data_state $DATA_STATE $MAGICKED_ARG $CLEAN_ARG --outroot $OUTROOT --logfile $logfile
    144155
    145156    add_standard_args run
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/nebulous.site.pro.in

    r19748 r23594  
    11# customize these variables for your site
     2# and copy the file to share/pantasks/modules directory in your installation
    23
    3 $NEB_DB    = nebulous
    4 $NEB_HOST  = alala
     4$NEB_DB    = your_nebulous_database_name
     5$NEB_HOST  = host_for_nebulous_mysql_database
    56$NEB_USER  = XXX
    67$NEB_PASS  = XXX
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/pantasks.pro

    r22422 r23594  
    1313$KEEP_FAILURES = 0
    1414
    15 $LOADPOLL = 0.25
     15$LOADPOLL = 1.0
    1616$LOADEXEC = 5
    1717$RUNPOLL = 0.5
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/replicate.pro

    r23352 r23594  
    7474
    7575  # modify these after the tasks are tested
    76   periods      -poll 10
    77   periods      -exec 10
     76  periods      -poll 0.5
     77  periods      -exec 5
    7878  periods      -timeout 1500
    7979  npending     1
     
    8484
    8585  task.exec
     86      book npages replicatePending -var N
     87      if ($N > 2000)
     88        process_cleanup replicatePending
     89        break
     90      end     
     91
    8692      # command does not need to be dynamic, but having it so allows us to adjust the periods
    8793      # so that we dont have to wait 10 minutes for things to start up
    8894      # 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
    90       periods      -exec 1800
    91 
    92   end
    93 
    94   # success
    95   task.exit $EXIT_SUCCESS
     95      command neb-admin --host $NEB_HOST --db $NEB_DB --user $NEB_USER --pass $NEB_PASS --pendingreplicate --limit 500 --so_id_start $SO_ID_START --so_id_range $SO_ID_RANGE
     96      # periods      -exec 1800
     97  end
     98
     99  # success : 0 -- we did not hit the limit, advance so_id counter
     100  task.exit 0
    96101    # advance the so_id counter
    97     $SO_ID_START += $SO_ID_RANGE
    98 
     102    $SO_ID_START = $SO_ID_START + $SO_ID_RANGE
     103
     104    # convert 'stdout' to book format
     105    ipptool2book stdout replicatePending -key key -uniq -setword pantaskState INIT
     106
     107    if ($VERBOSE > 2)
     108      book listbook replicatePending
     109    end
     110
     111    # delete existing entries in the appropriate pantaskStates
     112    process_cleanup replicatePending
     113  end
     114
     115  # success : 1 -- we DID hit the limit, do NOT advance so_id counter
     116  task.exit 1
    99117    # convert 'stdout' to book format
    100118    ipptool2book stdout replicatePending -key key -uniq -setword pantaskState INIT
     
    131149# create the desired replicas
    132150task           replicate.run
    133   periods      -poll $RUNPOLL
    134   periods      -exec 30
     151  periods      -poll 0.5
     152  periods      -exec 5
    135153  periods      -timeout 30
    136154
     
    139157    if ($NETWORK == 0) break
    140158    if ($N == 0)
    141         periods -exec 30
     159        periods -exec 5
    142160        break
    143161    end
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/simtest.pro

    r21049 r23594  
    4545    echo "  simtest.setup.detverify : run detrend creation and detrend verification"
    4646    echo "  simtest.setup.flatcorr : run a flat-field correction demonstration"
     47    echo "  simtest.setup.ctemask : run a ctemask demonstration"
    4748    break
    4849  end
     
    126127end
    127128
     129macro simtest.setup.ctemask
     130  $PPSIM_RECIPE = BADCTE.TEST
     131  $SIMTEST_SEQUENCE = simtest.ctemask.config
     132  $SIMTEST_AUTO = simtest.ctemask.auto
     133end
     134
    128135macro simtest.setup.flatcorr
    129136  $PPSIM_RECIPE = FLATCORR
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/summit.copy.pro

    r23352 r23594  
    2727# list of summit imfiles that need to be downloaded
    2828book init pzPendingImfile
     29# list of pzDownloadExps that have completed downloading
     30book init pzPendingAdvance
    2931
    3032macro copy.on
     
    5052      active true
    5153  end
     54  task summit.toadvance
     55      active true
     56  end
    5257  task summit.advance
    5358      active true
     
    7580  end
    7681  task pztool.clearfault
     82      active false
     83  end
     84  task summit.toadvance
    7785      active false
    7886  end
     
    8694$pztoolPendingExp_DB = 0
    8795$pztoolPendingImfile_DB = 0
     96$pztoolPendingAdvance_DB = 0
    8897$pztoolClearFault_DB = 0
    8998$pztoolAdvance_DB = 0;
     
    433442        stderr $LOGDIR/summit.copy.log
    434443
    435         $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
     444        $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 --dbname $DBNAME --timeout 120 --verbose --copies 2
    436445        if ($COMPRESS)
    437446            $run = $run --compress
     
    510519end
    511520
    512 # promote exposures for which all imfiles have been copied
    513 task           summit.advance
    514   host         local
    515 
    516   periods      -poll $LOADPOLL
    517   periods      -exec $LOADEXEC
    518   periods      -timeout 30
    519   npending     1
    520 
    521   stdout NULL
    522   stderr $LOGDIR/summit.advance.log
    523 
    524   task.exec
    525     $run = pztool -advance
    526     if ($DB:n == 0)
    527       option DEFAULT
    528     else
    529       # save the DB name for the exit tasks
    530       option $DB:$pztoolAdvance_DB
    531       $run = $run -dbname $DB:$pztoolAdvance_DB
    532       $pztoolAdvance_DB ++
    533       if ($pztoolAdvance_DB >= $DB:n) set pztoolAdvance_DB = 0
    534     end
    535     add_poll_args run
    536     command $run
    537   end
    538 
    539   # success
    540   task.exit    0
    541   end
    542 
    543   # locked list
    544   task.exit    default
    545     showcommand failure
    546   end
    547 
    548   task.exit    crash
    549     showcommand crash
    550   end
    551 
    552   # operation times out?
    553   task.exit    timeout
    554     showcommand timeout
    555   end
    556 end
    557 
     521# build a book of exposures that have completed downloading
     522task summit.toadvance
     523    host         local
     524
     525    periods      -exec     30
     526    periods      -poll      1
     527    periods      -timeout  120
     528    # trage       16:00 23:59
     529    # trage       00:00 04:00
     530    npending     1
     531
     532    # select entries from the current DB; cycle to the next DB, if it exists
     533    # iff the DB list is not set, use the value defined in .ipprc
     534    task.exec
     535      if ($DB:n == 0)
     536        option DEFAULT
     537        command pztool -toadvance -limit 40
     538      else
     539        # save the DB name for the exit tasks
     540        option $DB:$pztoolPendingAdvance_DB
     541        command pztool -toadvance -limit 60 -dbname $DB:$pztoolPendingAdvance_DB
     542        $pztoolPendingAdvance_DB ++
     543        if ($pztoolPendingAdvance_DB >= $DB:n) set pztoolPendingAdvance_DB = 0
     544      end
     545    end
     546 
     547    # success
     548    task.exit    0
     549        # convert 'stdout' to book format
     550        ipptool2book stdout pzPendingAdvance -key exp_name:camera:telescope -uniq -setword dbname $options:0 -setword pantaskState INIT
     551        book shuffle pzPendingAdvance
     552
     553        # delete existing entries in the appropriate pantaskStates
     554        process_cleanup pzPendingAdvance
     555    end
     556
     557    task.exit     default
     558        showcommand failure
     559    end
     560    task.exit     crash
     561        showcommand crash
     562    end
     563    task.exit     timeout
     564        showcommand timeout
     565    end
     566end
     567
     568task summit.advance
     569    periods      -exec     5
     570    periods      -poll     0.05
     571    periods      -timeout  650
     572    # trage       16:00 23:59
     573    # trage       00:00 04:00
     574
     575    task.exec
     576        if ($NETWORK == 0) break
     577
     578        # if we are waiting on data, make the interval long
     579        book npages pzPendingAdvance -var N
     580        if ($N == 0)
     581            periods -exec 20
     582            break
     583        end
     584        periods -exec 0.05
     585
     586        # find an exp that needs imfiles fetched
     587        book getpage pzPendingAdvance 0 -var pageName -key pantaskState INIT
     588        if ("$pageName" == "NULL") break
     589
     590        # set that exp to run
     591        book setword pzPendingAdvance $pageName pantaskState RUN
     592
     593        book getword pzPendingAdvance $pageName exp_name  -var EXP_NAME
     594        book getword pzPendingAdvance $pageName camera    -var CAMERA
     595        book getword pzPendingAdvance $pageName telescope -var TELESCOPE
     596        book getword pzPendingAdvance $pageName dbname    -var DBNAME
     597
     598        # 2007-08-30T05:09:59Z
     599        substr $DATEOBS 0 4 YEAR
     600        substr $DATEOBS 5 2 MONTH
     601        substr $DATEOBS 8 2 DAY
     602
     603        # we need to set the workdir based on 1) nebulous or not? 2) chip/host relationship
     604        # this function uses workdir_template, default_host, volume_template, volume_default,
     605        # it sets workdir and volume
     606        set.workdir.by.camera $CAMERA $CLASS_ID $workdir_template $default_host workdir_base
     607
     608        $workdir = $workdir_template/$CAMERA/$YEAR\$MONTH\$DAY
     609
     610        # workdir examples:
     611        # file://data/@HOST@.0/gpc1/20080130
     612        # neb://@HOST@.0/gpc1/20080130
     613
     614        stdout $LOGDIR/summit.advance.log
     615        stderr $LOGDIR/summit.advance.log
     616
     617        $run = pztool -advance -exp_name $EXP_NAME -inst $CAMERA -telescope $TELESCOPE -end_stage reg -workdir $workdir -dbname $DBNAME
     618
     619        # store the pageName for future reference below
     620        options $pageName
     621
     622        # create the command line
     623        if ($VERBOSE > 1)
     624          echo command $run
     625        end
     626        command $run
     627    end
     628
     629    # default exit status
     630    task.exit default
     631        process_exit pzPendingAdvance $options:0 $JOB_STATUS
     632    end
     633
     634    task.exit crash
     635        showcommand crash
     636        book setword pzPendingAdvance $options:0 pantaskState CRASH
     637    end
     638
     639    # operation timed out?
     640    task.exit timeout
     641        showcommand timeout
     642        book setword pzPendingAdvance $options:0 pantaskState TIMEOUT
     643    end
     644end
  • branches/cnb_branches/cnb_branch_20090301/ippTasks/warp.pro

    r23352 r23594  
    289289    book getword warpPendingSkyCell $pageName exp_tag -var EXP_TAG
    290290    book getword warpPendingSkyCell $pageName state -var RUN_STATE
     291    book getword warpPendingSkyCell $pageName magicked -var CHIP_MAGICKED
     292    if ("$CHIP_MAGICKED" == "T")
     293        $MAGICKED_ARG = "--magicked"
     294    else
     295        $MAGICKED_ARG = ""
     296    end
     297
    291298
    292299    # set the host and workdir based on the skycell hash
     
    300307    stderr $LOGDIR/warp.skycell.log
    301308
    302     $run = warp_skycell.pl --threads @MAX_THREADS@ --warp_id $WARP_ID --warp_skyfile_id $WARP_SKYFILE_ID --skycell_id $SKYCELL_ID --tess_dir $TESS_DIR --camera $CAMERA --outroot $outroot --redirect-output --run-state $RUN_STATE
     309    $run = warp_skycell.pl --threads @MAX_THREADS@ --warp_id $WARP_ID --warp_skyfile_id $WARP_SKYFILE_ID --skycell_id $SKYCELL_ID --tess_dir $TESS_DIR --camera $CAMERA --outroot $outroot --redirect-output --run-state $RUN_STATE $MAGICKED_ARG
    303310    add_standard_args run
    304311
  • branches/cnb_branches/cnb_branch_20090301/ippTools/configure.ac

    r21308 r23594  
    1818PKG_CHECK_MODULES([PSLIB], [pslib >= 1.1.0])
    1919PKG_CHECK_MODULES([PSMODULES], [psmodules >= 1.1.0])
    20 PKG_CHECK_MODULES([IPPDB], [ippdb >= 1.1.48])
     20PKG_CHECK_MODULES([IPPDB], [ippdb >= 1.1.50])
    2121
    2222PXTOOLS_CFLAGS="${PSLIB_CFLAGS=} ${PSMODULES_CFLAGS=} ${IPPDB_CFLAGS=}"
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/Makefile.am

    r23352 r23594  
    7676     difftool_definebyquery_part2.sql \
    7777     difftool_definebyquery_temp_create.sql \
     78     difftool_definewarpwarp_select.sql \
     79     difftool_definewarpwarp_insert.sql \
    7880     difftool_donecleanup.sql \
    7981     difftool_inputskyfile.sql \
     
    152154     regtool_revertprocessedexp.sql \
    153155     regtool_revertprocessedimfile.sql \
     156     regtool_updateprocessedimfile.sql \
    154157     stacktool_definebyquery_insert.sql \
    155158     stacktool_definebyquery_insert_random_part1.sql \
     
    172175     warptool_donecleanup.sql \
    173176     warptool_exp.sql \
     177     warptool_finished_run_select.sql \
     178     warptool_finish_run.sql \
    174179     warptool_imfile.sql \
    175180     warptool_pendingcleanuprun.sql \
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/camtool_find_processedexp.sql

    r21443 r23594  
    11SELECT DISTINCT
    22    camProcessedExp.*,
     3    chipRun.chip_id,
    34    rawExp.exp_tag,
    45    rawExp.exp_name,
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/chiptool_change_imfile_data_state.sql

    r23352 r23594  
    11-- handle changes in data_state. Used for the modes tocleanedimfile and topurgedimfile
    2 -- args are new data_state, chip_id, class_id, and current expected state for chipRun
     2-- args are new data_state, a possibly empty string for updating the magicked state,
     3-- chip_id and class_id
    34UPDATE chipProcessedImfile
     5JOIN rawImfile USING(exp_id, class_id)
    46    SET
    5     data_state = '%s'
     7    chipProcessedImfile.data_state = '%s'
     8    -- set magicked hook %s
    69WHERE
    710    chip_id = %lld
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/chiptool_completely_processed_exp.sql

    r20608 r23594  
    1111    dvodb,
    1212    tess_id,
    13     end_stage
     13    end_stage,
     14    all_files_magicked as magicked
    1415FROM
    1516    (SELECT
    1617        chipRun.*,
    1718        rawImfile.class_id as rawimfile_class_id,
    18         chipProcessedImfile.class_id
     19        chipProcessedImfile.class_id,
     20        SUM(!chipProcessedImfile.magicked) = 0 as all_files_magicked
    1921    FROM chipRun
    2022    JOIN rawImfile
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/chiptool_pendingimfile.sql

    r21334 r23594  
    44    rawImfile.class_id,
    55    rawImfile.uri,
     6    rawImfile.magicked as raw_magicked,
     7    (rawImfile.user_1 is not NULL and rawImfile.user_1 > 0.5) as deburned,
    68    rawExp.exp_tag,
    79    rawExp.exp_name,
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/difftool_completed_runs.sql

    r20973 r23594  
    11SELECT DISTINCT
    2     diff_id
     2    diff_id,
     3    all_magicked as magicked
    34FROM (
    45    SELECT
    56        COUNT(diffInputSkyfile.skycell_id), COUNT(diffSkyfile.skycell_id),
    6         diffSkyfile.*
     7        diffSkyfile.*,
     8        SUM(!diffSkyfile.magicked) = 0 as all_magicked
    79    FROM diffRun
    810    JOIN diffInputSkyfile USING(diff_id)
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/difftool_inputskyfile.sql

    r20976 r23594  
    99        warpSkyfile.uri,
    1010        warpSkyfile.path_base,
     11        warpSkyfile.magicked as magicked,
    1112        0 as template,
    1213        rawExp.camera
     
    4748        warpSkyfile.uri,
    4849        warpSkyfile.path_base,
     50        warpSkyfile.magicked as magicked,
    4951        1 as template,
    5052        rawExp.camera
     
    8587        stackSumSkyfile.uri,
    8688        stackSumSkyfile.path_base,
     89        0 as magicked,
    8790        0 as template,
    8891        rawExp.camera
     
    117120        stackSumSkyfile.uri,
    118121        stackSumSkyfile.path_base,
     122        0 as magicked,
    119123        1 as template,
    120124        rawExp.camera
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/disttool_pendingcomponent.sql

    r23352 r23594  
    22SELECT
    33    distRun.dist_id,
     4    distRun.label,
    45    stage,
    56    stage_id,
     
    89    rawExp.camera,
    910    outroot,
    10     rawImfile.uri as path_base,
     11    rawImfile.uri as path_base,         -- change this once rawImfile has path_base
    1112    chipProcessedImfile.path_base as chip_path_base,
    1213    NULL as state,
     
    1516FROM distRun
    1617JOIN rawExp ON exp_id = stage_id
    17 JOIN rawImfile using(exp_id)
     18JOIN (                      -- find the last magicked chip run
     19    SELECT
     20        exp_id,
     21        MAX(chip_id) AS chip_id
     22    FROM chipRun
     23    WHERE
     24        chipRun.state = 'full'
     25        AND chipRun.exp_id = exp_id
     26        --   AND chipRun.magicked
     27        -- magicked hook 1 %s
     28        GROUP BY exp_id
     29    ) AS bestChipRun
     30    USING(exp_id)
     31JOIN rawImfile USING(exp_id)
    1832JOIN chipProcessedImfile
    19     ON distRun.chip_id = chipProcessedImfile.chip_id
    20     AND rawImfile.class_id = chipProcessedImfile.class_id
     33    USING(exp_id, chip_id, class_id)
    2134LEFT JOIN distComponent
    2235    ON distRun.dist_id = distComponent.dist_id
     
    2639    AND distRun.stage = 'raw'
    2740    AND distComponent.dist_id IS NULL
     41    -- if magicked add AND rawImfile.magicked here
     42    -- where hook 1 %s
    2843
    2944-- chip stage
     
    3146SELECT
    3247    distRun.dist_id,
     48    distRun.label,
    3349    stage,
    3450    stage_id,
     
    5369    AND distRun.stage = 'chip'
    5470    AND distComponent.dist_id IS NULL
    55 UNION
    56 SELECT
    57     distRun.dist_id,
     71    -- where hook 2 %s
     72UNION
     73SELECT
     74    distRun.dist_id,
     75    distRun.label,
     76    stage,
     77    stage_id,
     78    chipProcessedImfile.class_id AS component,
     79    clean,
     80    rawExp.camera,
     81    outroot,
     82    camProcessedExp.path_base,
     83    chipProcessedImfile.path_base as chip_path_base,
     84    camRun.state,
     85    NULL,
     86    0
     87FROM distRun
     88JOIN camRun ON camRun.cam_id = distRun.stage_id
     89JOIN camProcessedExp USING(cam_id)
     90JOIN chipRun USING(chip_id)
     91JOIN chipProcessedImfile USING(exp_id, chip_id)
     92JOIN rawExp using(exp_id)
     93LEFT JOIN distComponent
     94    ON distRun.dist_id = distComponent.dist_id
     95    AND chipProcessedImfile.class_id = distComponent.component
     96WHERE
     97    distRun.state = 'new'
     98    AND distRun.stage = 'camera'
     99    AND distComponent.dist_id IS NULL
     100    -- where hook 3 %s
     101UNION
     102SELECT
     103    distRun.dist_id,
     104    distRun.label,
     105    stage,
     106    stage_id,
     107    fakeProcessedImfile.class_id AS component,
     108    clean,
     109    rawExp.camera,
     110    outroot,
     111    fakeProcessedImfile.path_base,
     112    NULL,
     113    fakeRun.state,
     114    NULL,
     115    0
     116FROM distRun
     117JOIN fakeRun ON fakeRun.fake_id = distRun.stage_id
     118JOIN fakeProcessedImfile USING(fake_id)
     119JOIN camRun USING(cam_id)
     120JOIN chipRun USING(chip_id, exp_id)
     121JOIN rawExp using(exp_id)
     122LEFT JOIN distComponent
     123    ON distRun.dist_id = distComponent.dist_id
     124    AND fakeProcessedImfile.class_id = distComponent.component
     125WHERE
     126    distRun.state = 'new'
     127    AND distRun.stage = 'fake'
     128    AND distComponent.dist_id IS NULL
     129    -- where hook 4 %s
     130UNION
     131SELECT
     132    distRun.dist_id,
     133    distRun.label,
    58134    stage,
    59135    stage_id,
     
    81157    AND distRun.stage = 'warp'
    82158    AND distComponent.dist_id IS NULL
    83 UNION
    84 SELECT
    85     distRun.dist_id,
     159    -- where hook 5 %s
     160UNION
     161SELECT
     162    distRun.dist_id,
     163    distRun.label,
    86164    stage,
    87165    stage_id,
     
    108186    AND distRun.stage = 'diff'
    109187    AND distComponent.dist_id IS NULL
     188    -- where hook 6 %s
    110189UNION
    111190SELECT DISTINCT
    112191    distRun.dist_id,
     192    distRun.label,
    113193    stage,
    114194    stage_id,
     
    152232    AND distRun.stage = 'stack'
    153233    AND distComponent.dist_id IS NULL
     234    -- where hook 7 %s
    154235) as Foo
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/magicdstool_completed_runs.sql

    r20973 r23594  
    1212        AND magicDSFile.component = rawImfile.class_id
    1313    WHERE
    14         magicDSRun.state = 'run'
     14        magicDSRun.state = 'new'
    1515        AND magicDSRun.stage = 'raw'
    1616    GROUP BY
     
    3030        AND magicDSFile.component = chipProcessedImfile.class_id
    3131    WHERE
    32         magicDSRun.state = 'run'
     32        magicDSRun.state = 'new'
    3333        AND magicDSRun.stage = 'chip'
    3434    GROUP BY
     
    4848        AND magicDSFile.component = warpSkyfile.skycell_id
    4949    WHERE
    50         magicDSRun.state = 'run'
     50        magicDSRun.state = 'new'
    5151        AND magicDSRun.stage = 'warp'
    5252        AND warpSkyfile.fault = 0
     
    7272        AND magicDSFile.component = diffSkyfile.skycell_id
    7373    WHERE
    74         magicDSRun.state = 'run'
     74        magicDSRun.state = 'new'
    7575        AND magicDSRun.stage = 'diff'
    7676        AND diffSkyfile.fault = 0
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/magicdstool_todestreak.sql

    r20973 r23594  
    2626    AND magicDSFile.component = rawImfile.class_id
    2727WHERE
    28     magicDSRun.state = 'run'
     28    magicDSRun.state = 'new'
    2929    AND magicDSRun.stage = 'raw'
    3030    AND magicDSFile.component IS NULL
     
    5757    AND magicDSFile.component = chipProcessedImfile.class_id
    5858WHERE
    59     magicDSRun.state = 'run'
     59    magicDSRun.state = 'new'
    6060    AND magicDSRun.stage = 'chip'
    6161    AND chipRun.state = 'full'
     
    9191    AND magicDSFile.component = warpSkyfile.skycell_id
    9292WHERE
    93     magicDSRun.state = 'run'
     93    magicDSRun.state = 'new'
    9494    AND magicDSRun.stage = 'warp'
    9595    AND warpRun.state = 'full'
     
    127127    AND magicDSFile.component = diffSkyfile.skycell_id
    128128WHERE
    129     magicDSRun.state = 'run'
     129    magicDSRun.state = 'new'
    130130    AND magicDSRun.stage = 'diff'
    131131    AND diffSkyfile.fault = 0
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/magictool_addmask.sql

    r18526 r23594  
    22    magicRun
    33SET
    4     state = 'stop'
     4    state = 'full'
    55WHERE
    6     state != 'stop'
     6    state != 'full'
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/magictool_chipprocessedimfile.sql

    r20706 r23594  
    2626    chipRun.state = 'full'
    2727    AND chipProcessedImfile.fault = 0
    28 --   AND magicRun.state = 'stop'
     28--   AND magicRun.state = 'full'
    2929--   AND magicMask.fault = 0
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/magictool_diffskyfile.sql

    r20701 r23594  
    2424    diffRun.state = 'full'
    2525    AND diffSkyfile.fault = 0
    26 --   AND magicRun.state = 'stop'
     26--   AND magicRun.state = 'full'
    2727--   AND magicMask.fault = 0
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/magictool_inputskyfile.sql

    r20973 r23594  
    99    AND magicInputSkyfile.node = diffSkyfile.skycell_id
    1010WHERE
    11     magicRun.state = 'run'
     11    magicRun.state = 'new'
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/magictool_mask.sql

    r20735 r23594  
    66    USING(magic_id)
    77WHERE
    8     magicRun.state = 'stop'
     8    magicRun.state = 'full'
    99    AND magicMask.fault = 0
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/magictool_rawimfile.sql

    r20706 r23594  
    2424WHERE
    2525    rawImfile.fault = 0
    26 --   AND magicRun.state = 'stop'
     26--   AND magicRun.state = 'full'
    2727--   AND magicMask.fault = 0
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/magictool_tomask.sql

    r18781 r23594  
    1010LEFT JOIN magicNodeResult USING(magic_id, node)
    1111WHERE
    12     magicRun.state = 'run'
     12    magicRun.state = 'new'
    1313    AND magicNodeResult.node = 'root'
    1414    AND magicNodeResult.fault = 0
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/magictool_toprocess_inputs.sql

    r21004 r23594  
    1919    AND magicTree.node = magicNodeResult.node
    2020WHERE
    21     magicRun.state = 'run'
     21    magicRun.state = 'new'
    2222    AND magicNodeResult.magic_id IS NULL
    2323    AND magicNodeResult.node IS NULL
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/magictool_toprocess_tree.sql

    r21099 r23594  
    1515    AND magicTree.node = magicNodeResult.node
    1616WHERE
    17     magicRun.state = 'run'
     17    magicRun.state = 'new'
    1818    -- where hook %s
    1919ORDER BY
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/magictool_toskyfilemask.sql

    r15348 r23594  
    77    USING(magic_id)
    88WHERE
    9     magicRun.state = 'run'
     9    magicRun.state = 'new'
    1010    AND magicSkyfileMask.magic_id IS NULL
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/magictool_totree.sql

    r20474 r23594  
    1212    USING(magic_id)
    1313WHERE
    14     magicRun.state = 'run'
     14    magicRun.state = 'new'
    1515    AND magicTree.node IS NULL
    1616    AND magicRun.fault = 0
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/magictool_warpskyfile.sql

    r20701 r23594  
    2121    warpRun.state = 'full'
    2222    AND warpSkyfile.fault = 0
    23 --   AND magicRun.state = 'stop'
     23--   AND magicRun.state = 'full'
    2424--   AND magicMask.fault = 0
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/pxadmin_create_tables.sql

    r23352 r23594  
    167167    fault SMALLINT NOT NULL,
    168168    epoch TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
     169    magicked TINYINT,
    169170    PRIMARY KEY(exp_id),
    170171    KEY(exp_name),
     
    263264    tess_id VARCHAR(64),
    264265    end_stage VARCHAR(64),
     266    magicked TINYINT,
    265267    PRIMARY KEY(chip_id),
    266268    KEY(chip_id), KEY(exp_id),
     
    826828    end_stage VARCHAR(64),
    827829    registered DATETIME,
     830    magicked TINYINT,
    828831    PRIMARY KEY(warp_id),
    829832    KEY(warp_id),
     
    963966        tess_id VARCHAR(64),
    964967        exp_id  BIGINT,
     968        magicked TINYINT,
    965969        PRIMARY KEY(diff_id),
    966970        KEY(diff_id),
     
    10951099        stage_id BIGINT,
    10961100        cam_id BIGINT,
     1101        label VARCHAR(64),
    10971102        outroot VARCHAR(255),
    10981103        recoveryroot VARCHAR(255),
     
    11021107        KEY(magic_ds_id),
    11031108        KEY(state),
     1109        KEY(magic_id),
     1110        KEY(label),
    11041111        FOREIGN KEY (magic_id)  REFERENCES  magicRun(magic_id)
    11051112) ENGINE=innodb DEFAULT CHARSET=latin1;
     
    12251232        KEY(job_id),
    12261233        FOREIGN KEY (req_id)  REFERENCES  pstampRequest(req_id)
    1227 ) ENGINE=innodb DEFAULT CHARSET=latin1
     1234) ENGINE=innodb DEFAULT CHARSET=latin1;
     1235
     1236CREATE TABLE distTarget (
     1237    target_id   BIGINT AUTO_INCREMENT,
     1238    obs_mode    VARCHAR(64),
     1239    stage       VARCHAR(64),
     1240    clean       TINYINT,
     1241    state       VARCHAR(64),
     1242    comment     VARCHAR(255),
     1243    PRIMARY KEY(target_id)
     1244)  ENGINE=innodb DEFAULT CHARSET=latin1;
     1245
     1246CREATE TABLE distRun (
     1247    dist_id     BIGINT AUTO_INCREMENT,
     1248    target_id   BIGINT,
     1249    stage       VARCHAR(64),
     1250    stage_id    BIGINT,
     1251    label       VARCHAR(64),
     1252    outroot     VARCHAR(255),
     1253    clean       TINYINT,
     1254    state       VARCHAR(64),
     1255    time_stamp  TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
     1256    fault       SMALLINT,
     1257    PRIMARY KEY(dist_id),
     1258    KEY(state),
     1259    KEY(label),
     1260    FOREIGN KEY(target_id) REFERENCES distTarget(target_id)
     1261)  ENGINE=innodb DEFAULT CHARSET=latin1;
     1262
     1263CREATE TABLE distComponent (
     1264    dist_id     BIGINT,
     1265    component   VARCHAR(64),
     1266    bytes       INT,
     1267    md5sum      VARCHAR(32),
     1268    state       VARCHAR(64),
     1269    name        VARCHAR(255),
     1270    fault       SMALLINT,
     1271    PRIMARY KEY(dist_id, component),
     1272    KEY(state),
     1273    FOREIGN KEY(dist_id) REFERENCES distRun(dist_id)
     1274)  ENGINE=innodb DEFAULT CHARSET=latin1;
     1275
     1276
     1277CREATE TABLE rcDSProduct (
     1278    prod_id     BIGINT AUTO_INCREMENT,
     1279    name        VARCHAR(64),
     1280    dbname      VARCHAR(64),
     1281    dbhost      VARCHAR(64),
     1282    prod_root   VARCHAR(255),
     1283    PRIMARY KEY(prod_id)
     1284)  ENGINE=innodb DEFAULT CHARSET=latin1;
     1285
     1286CREATE TABLE rcDestination (
     1287    dest_id     BIGINT AUTO_INCREMENT,
     1288    prod_id     BIGINT,
     1289    name        VARCHAR(64),
     1290    status_uri  VARCHAR(255),
     1291    comment     VARCHAR(255),
     1292    last_fileset VARCHAR(255),
     1293    state       VARCHAR(64),
     1294    PRIMARY KEY(dest_id),
     1295    FOREIGN KEY(prod_id) REFERENCES rcDSProduct(prod_id)
     1296)  ENGINE=innodb DEFAULT CHARSET=latin1;
     1297
     1298
     1299CREATE TABLE rcInterest (
     1300    int_id      BIGINT AUTO_INCREMENT,
     1301    dest_id     BIGINT,
     1302    target_id   BIGINT,
     1303    prod_id     BIGINT,
     1304    state       VARCHAR(64),
     1305    PRIMARY KEY(int_id),
     1306    FOREIGN KEY(dest_id) REFERENCES rcDestination(dest_id),
     1307    FOREIGN KEY(target_id) REFERENCES distTarget(target_id),
     1308    FOREIGN KEY(prod_id) REFERENCES rcDSProduct(prod_id)
     1309)  ENGINE=innodb DEFAULT CHARSET=latin1;
     1310
     1311CREATE TABLE rcDSFileset (
     1312    fs_id       BIGINT AUTO_INCREMENT,
     1313    dist_id     BIGINT,
     1314    prod_id     BIGINT,
     1315    name        VARCHAR(64),
     1316    state       VARCHAR(64),
     1317    registered  TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
     1318    PRIMARY KEY(fs_id),
     1319    FOREIGN KEY(dist_id) REFERENCES distRun(dist_id),
     1320    FOREIGN KEY(prod_id) REFERENCES rcDSProduct(prod_id)
     1321)  ENGINE=innodb DEFAULT CHARSET=latin1;
     1322
     1323CREATE TABLE rcRun (
     1324    rc_id       BIGINT AUTO_INCREMENT,
     1325    fs_id       BIGINT,
     1326    dest_id     BIGINT,
     1327    state       VARCHAR(64),
     1328    registered  TIMESTAMP DEFAULT CURRENT_TIMESTAMP,
     1329    PRIMARY KEY(rc_id),
     1330    FOREIGN KEY(fs_id) REFERENCES rcDSFileset(fs_id),
     1331    FOREIGN KEY(dest_id) REFERENCES rcDestination(dest_id)
     1332)  ENGINE=innodb DEFAULT CHARSET=latin1;
     1333
     1334
     1335
     1336-- This comment line is here to avoid empty query error.
     1337-- Another way to avoid that problem is to omit the semicolon above but I think that is untidy.
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/pxadmin_drop_tables.sql

    r21308 r23594  
    5454DROP TABLE IF EXISTS calRun;
    5555DROP TABLE IF EXISTS flatcorrRun;
     56DROP TABLE IF EXISTS flatcorrExp;
    5657DROP TABLE IF EXISTS flatcorrChipLink;
    5758DROP TABLE IF EXISTS flatcorrCamLink;
     
    6061DROP TABLE IF EXISTS pstampRequest;
    6162DROP TABLE IF EXISTS pstampJob;
     63DROP TABLE IF EXISTS distRun;
     64DROP TABLE IF EXISTS distTarget;
     65DROP TABLE IF EXISTS distComponent;
     66DROP TABLE IF EXISTS rcDSProduct;
     67DROP TABLE IF EXISTS rcDestination;
     68DROP TABLE IF EXISTS rcInterest;
     69DROP TABLE IF EXISTS rcDSFileset;
     70DROP TABLE IF EXISTS rcRun;
     71
    6272SET FOREIGN_KEY_CHECKS=1
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/pztool_find_completed_exp.sql

    r17925 r23594  
    11SELECT DISTINCT
    2     exp_name, -- return should match pzDownloadExp
     2    exp_name,
    33    camera,
    44    telescope,
    5     state,
    6     NULL as epoch    -- epoch
     5    state
    76FROM (
    87    SELECT
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/warptool_change_skyfile_data_state.sql

    r23352 r23594  
    88    warp_id = %lld
    99    AND skycell_id = '%s'
    10     -- 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'
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/warptool_definebyquery.sql

    r20041 r23594  
    99        rawExp.dateobs,
    1010        rawExp.exp_tag,
     11        rawExp.exp_name,
    1112        rawExp.exp_type,
    1213        rawExp.filelevel,
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/warptool_pendingcleanuprun.sql

    r19521 r23594  
    1313USING (exp_id)
    1414WHERE
    15     (warpRun.state = 'goto_cleaned' OR warpRun.state = 'goto_purged')
     15    (warpRun.state = 'goto_cleaned' OR warpRun.state = 'goto_scrubbed' OR warpRun.state = 'goto_purged')
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/warptool_pendingcleanupskyfile.sql

    r19521 r23594  
    1010    USING(warp_id)
    1111WHERE
    12     (warpRun.state = 'goto_cleaned' AND warpSkyfile.data_state = 'full')
     12   ((warpRun.state = 'goto_cleaned' AND warpSkyfile.data_state = 'full')
    1313    OR
    14     (warpRun.state = 'goto_purged' AND warpSkyfile.data_state != 'purged')
     14    (warpRun.state = 'goto_scrubbed' AND warpSkyfile.data_state = 'full')
     15    OR
     16    (warpRun.state = 'goto_purged'   AND warpSkyfile.data_state != 'purged'))
  • branches/cnb_branches/cnb_branch_20090301/ippTools/share/warptool_towarped.sql

    r21308 r23594  
    99    rawExp.camera,
    1010    rawExp.exp_tag,
    11     warpRun.workdir
     11    warpRun.workdir,
     12    chipRun.magicked
    1213FROM warpRun
    1314JOIN warpSkyCellMap
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src

    • Property svn:ignore
      •  

        old new  
        3232flatcorr
        3333pstamptool
         34disttool
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/Makefile.am

    r20789 r23594  
    66        dettool \
    77        difftool \
     8        disttool \
    89        flatcorr \
    910        magictool \
     
    4546        dettool.h \
    4647        difftool.h \
     48        disttool.h \
    4749        flatcorr.h \
    4850        faketool.h \
     
    152154    difftoolConfig.c
    153155
     156disttool_CFLAGS = $(PSLIB_CFLAGS) $(PSMODULES_CFLAGS) $(IPPDB_CFLAGS)
     157disttool_LDADD = $(PSLIB_LIBS) $(PSMODULES_LIBS) $(IPPDB_LIBS) libpxtools.la
     158disttool_SOURCES = \
     159    disttool.c \
     160    disttoolConfig.c
     161
    154162stacktool_CFLAGS = $(PSLIB_CFLAGS) $(PSMODULES_CFLAGS) $(IPPDB_CFLAGS)
    155163stacktool_LDADD = $(PSLIB_LIBS) $(PSMODULES_LIBS) $(IPPDB_LIBS) libpxtools.la
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/camtool.c

    r23352 r23594  
    109109    psMetadata *where = psMetadataAlloc();
    110110    pxcamGetSearchArgs (config, where);
    111     PXOPT_COPY_STR(config->args, where, "-label", "label", "==");
     111    PXOPT_COPY_STR(config->args, where, "-label",     "chipRun.label",     "==");
     112    PXOPT_COPY_STR(config->args, where, "-reduction", "chipRun.reduction", "==");
    112113
    113114    if (!psListLength(where->list)
     
    223224
    224225    psMetadata *where = psMetadataAlloc();
    225     PXOPT_COPY_S64(config->args, where, "-cam_id", "cam_id", "==");
    226226    pxcamGetSearchArgs (config, where);
    227     PXOPT_COPY_STR(config->args, where, "-label", "camRun.label", "==");
    228     PXOPT_COPY_STR(config->args, where, "-state", "camRun.state", "==");
     227    PXOPT_COPY_S64(config->args, where, "-cam_id",    "camRun.cam_id", "==");
     228    PXOPT_COPY_STR(config->args, where, "-label",     "camRun.label", "==");
     229    PXOPT_COPY_STR(config->args, where, "-state",     "camRun.state", "==");
     230    PXOPT_COPY_STR(config->args, where, "-reduction", "camRun.reduction", "==");
    229231
    230232    if (!psListLength(where->list)
     
    271273
    272274    psMetadata *where = psMetadataAlloc();
    273     PXOPT_COPY_S64(config->args, where, "-cam_id", "cam_id", "==");
    274275    pxcamGetSearchArgs (config, where);
    275     PXOPT_COPY_STR(config->args, where, "-label", "label", "==");
     276    PXOPT_COPY_S64(config->args, where, "-cam_id",    "camRun.cam_id", "==");
     277    PXOPT_COPY_STR(config->args, where, "-label",     "camRun.label", "==");
     278    PXOPT_COPY_STR(config->args, where, "-reduction", "camRun.reduction", "==");
    276279
    277280    PXOPT_LOOKUP_U64(limit, config->args, "-limit", false, false);
     
    334337
    335338    psMetadata *where = psMetadataAlloc();
    336     PXOPT_COPY_S64(config->args, where, "-cam_id",   "cam_id",   "==");
    337     PXOPT_COPY_S64(config->args, where, "-chip_id",  "chip_id",  "==");
    338     PXOPT_COPY_STR(config->args, where, "-class",    "class",    "==");
    339     PXOPT_COPY_STR(config->args, where, "-class_id", "class_id", "==");
    340339    pxcamGetSearchArgs (config, where);
    341     PXOPT_COPY_STR(config->args, where, "-label", "camRun.label", "==");
     340    PXOPT_COPY_S64(config->args, where, "-cam_id",    "camRun.cam_id",                "==");
     341    PXOPT_COPY_STR(config->args, where, "-label",     "camRun.label",                 "==");
     342    PXOPT_COPY_STR(config->args, where, "-reduction", "camRun.reduction",             "==");
     343    PXOPT_COPY_S64(config->args, where, "-chip_id",   "chipRun.chip_id",              "==");
     344    PXOPT_COPY_STR(config->args, where, "-class_id",  "chipProcessedImfile.class_id", "==");
     345
     346    // XXX is this used? PXOPT_COPY_STR(config->args, where, "-class",    "class",         "==");
    342347
    343348    PXOPT_LOOKUP_BOOL(simple, config->args, "-simple", false);
     
    649654    // generate restrictions
    650655    psMetadata *where = psMetadataAlloc();
    651     PXOPT_COPY_S64(config->args, where, "-cam_id",   "cam_id",   "==");
    652656    pxcamGetSearchArgs (config, where);
    653     PXOPT_COPY_STR(config->args, where, "-label", "camRun.label", "==");
     657    PXOPT_COPY_S64(config->args, where, "-cam_id",    "camRun.cam_id",    "==");
     658    PXOPT_COPY_STR(config->args, where, "-label",     "camRun.label",     "==");
     659    PXOPT_COPY_STR(config->args, where, "-reduction", "camRun.reduction", "==");
    654660
    655661    psString query = pxDataGet("camtool_find_processedexp.sql");
     
    674680    }
    675681
     682    // order by cam_id so that the postage stamp parser can easliy find the 'latest' astrometry
     683    psStringAppend(&query, " ORDER BY cam_id");
     684
    676685    // treat limit == 0 as "no limit"
    677686    if (limit) {
     
    681690    }
    682691
    683     // order by cam_id so that the postage stamp parser can easliy find the 'latest' astrometry
    684     psStringAppend(&query, "\nORDER BY cam_id");
    685 
    686692    if (!p_psDBRunQuery(config->dbh, query)) {
    687693        psError(PS_ERR_UNKNOWN, false, "database error");
     
    720726
    721727    psMetadata *where = psMetadataAlloc();
    722     PXOPT_COPY_S64(config->args, where, "-cam_id", "camRun.cam_id", "==");
    723728    pxcamGetSearchArgs (config, where);
    724     PXOPT_COPY_STR(config->args, where, "-label", "camRun.label", "==");
    725     PXOPT_COPY_S16(config->args, where, "-code", "camProcessedExp.fault", "==");
     729    PXOPT_COPY_S64(config->args, where, "-cam_id",    "camRun.cam_id",         "==");
     730    PXOPT_COPY_STR(config->args, where, "-label",     "camRun.label",          "==");
     731    PXOPT_COPY_STR(config->args, where, "-reduction", "camRun.reduction",      "==");
     732    PXOPT_COPY_S16(config->args, where, "-code",      "camProcessedExp.fault", "==");
    726733
    727734    if (!psListLength(where->list) && !psMetadataLookupBool(NULL, config->args, "-all")) {
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/camtoolConfig.c

    r23352 r23594  
    5252    psMetadata *definebyqueryArgs = psMetadataAlloc();
    5353    pxcamSetSearchArgs(definebyqueryArgs);
    54     psMetadataAddStr(definebyqueryArgs, PS_LIST_TAIL, "-label", 0, "search for label", NULL);
     54    psMetadataAddStr(definebyqueryArgs, PS_LIST_TAIL, "-label",              0, "search by chipRun label", NULL);
     55    psMetadataAddStr(definebyqueryArgs, PS_LIST_TAIL, "-reduction",          0, "search by chipRun reduction class", NULL);
    5556
    5657    psMetadataAddStr(definebyqueryArgs, PS_LIST_TAIL, "-set_workdir",        0, "define workdir", NULL);
     
    6869    // XXX need to allow multiple exp_ids
    6970    psMetadata *updaterunArgs = psMetadataAlloc();
     71    pxcamSetSearchArgs(updaterunArgs);
    7072    psMetadataAddS64(updaterunArgs, PS_LIST_TAIL, "-cam_id",             0, "search by cam_id", 0);
    71     pxcamSetSearchArgs(updaterunArgs);
    72     psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-label", 0, "search for label", NULL);
    73     psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-state", 0, "search for state", NULL);
    74 
     73    psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-label",              0, "search by camRun label", NULL);
     74    psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-state",              0, "search by camRun state", NULL);
     75    psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-reduction",          0, "search by camRun reduction class", NULL);
    7576    psMetadataAddBool(updaterunArgs, PS_LIST_TAIL, "-all",               0, "allow everything to be queued without search terms", false);
    76     psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-set_state",              0, "set state", NULL);
    77     psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-set_label",              0, "set label", NULL);
     77    psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-set_state",          0, "set state", NULL);
     78    psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-set_label",          0, "set label", NULL);
    7879
    7980    // -pendingexp
    8081    psMetadata *pendingexpArgs = psMetadataAlloc();
    81     psMetadataAddS64(pendingexpArgs, PS_LIST_TAIL, "-cam_id",            0, "search by camtool ID", 0);
    8282    pxcamSetSearchArgs(pendingexpArgs);
    83     psMetadataAddStr(pendingexpArgs, PS_LIST_TAIL, "-label", 0, "search for label", NULL);
     83    psMetadataAddS64(pendingexpArgs, PS_LIST_TAIL, "-cam_id",            0, "search by cam_id", 0);
     84    psMetadataAddStr(pendingexpArgs, PS_LIST_TAIL, "-label",             0, "search by camRun label", NULL);
     85    psMetadataAddStr(pendingexpArgs, PS_LIST_TAIL, "-reduction",         0, "search by camRun reduction class", NULL);
    8486    psMetadataAddU64(pendingexpArgs, PS_LIST_TAIL, "-limit",             0, "limit result set to N items", 0);
    8587    psMetadataAddBool(pendingexpArgs, PS_LIST_TAIL, "-simple",           0, "use the simple output format", false);
     
    8789    // -pendingimfile
    8890    psMetadata *pendingimfileArgs = psMetadataAlloc();
    89     psMetadataAddS64(pendingimfileArgs, PS_LIST_TAIL, "-cam_id", 0,            "search by camtool ID", 0);
    9091    pxcamSetSearchArgs(pendingimfileArgs);
    91     psMetadataAddStr(pendingimfileArgs, PS_LIST_TAIL, "-label", 0, "search for label", NULL);
    92     psMetadataAddStr(pendingimfileArgs, PS_LIST_TAIL, "-class", 0,            "search by class", NULL);
     92    psMetadataAddS64(pendingimfileArgs, PS_LIST_TAIL, "-cam_id",   0,            "search by camtool ID", 0);
     93    psMetadataAddStr(pendingimfileArgs, PS_LIST_TAIL, "-label",    0,            "search by camRun label", NULL);
     94    psMetadataAddStr(pendingimfileArgs, PS_LIST_TAIL, "-reduction",0,            "search by camRun reduction class", NULL);
    9395    psMetadataAddStr(pendingimfileArgs, PS_LIST_TAIL, "-class_id", 0,            "search by class ID", NULL);
    94     psMetadataAddBool(pendingimfileArgs, PS_LIST_TAIL, "-simple", 0,            "use the simple output format", false);
     96    psMetadataAddBool(pendingimfileArgs, PS_LIST_TAIL, "-simple",  0,            "use the simple output format", false);
     97
     98    // XXX is this used? psMetadataAddStr(pendingimfileArgs, PS_LIST_TAIL, "-class",    0,            "search by class", NULL);
    9599
    96100    // -addprocessedexp
     
    165169    // -processedexp
    166170    psMetadata *processedexpArgs = psMetadataAlloc();
    167     psMetadataAddS64(processedexpArgs, PS_LIST_TAIL, "-cam_id", 0,            "search by camtool ID", 0);
    168171    pxcamSetSearchArgs(processedexpArgs);
    169     psMetadataAddStr(processedexpArgs, PS_LIST_TAIL, "-label", 0, "search for label", NULL);
     172    psMetadataAddS64(processedexpArgs, PS_LIST_TAIL, "-cam_id",   0,            "search by cam_id", 0);
     173    psMetadataAddStr(processedexpArgs, PS_LIST_TAIL, "-label",    0,            "search by camRun label", NULL);
     174    psMetadataAddStr(processedexpArgs, PS_LIST_TAIL, "-reduction",0,            "search by camRun reduction class", NULL);
    170175
    171176    psMetadataAddU64(processedexpArgs, PS_LIST_TAIL, "-limit",  0,            "limit result set to N items", 0);
     
    178183    // XXX need to allow multiple exp_ids
    179184    psMetadata *revertprocessedexpArgs = psMetadataAlloc();
    180     psMetadataAddS64(revertprocessedexpArgs, PS_LIST_TAIL, "-cam_id",  0,            "search by cam_id", 0);
    181185    pxcamSetSearchArgs(revertprocessedexpArgs);
    182     psMetadataAddStr(revertprocessedexpArgs, PS_LIST_TAIL, "-label", 0, "search for label", NULL);
     186    psMetadataAddS64(revertprocessedexpArgs, PS_LIST_TAIL, "-cam_id",   0,            "search by cam_id", 0);
     187    psMetadataAddStr(revertprocessedexpArgs, PS_LIST_TAIL, "-label",    0,            "search by camRun label", NULL);
     188    psMetadataAddStr(revertprocessedexpArgs, PS_LIST_TAIL, "-reduction",0,            "search by camRun reduction class", NULL);
     189    psMetadataAddS16(revertprocessedexpArgs, PS_LIST_TAIL, "-code",     0,            "search by fault code", 0);
    183190
    184191    psMetadataAddBool(revertprocessedexpArgs, PS_LIST_TAIL, "-all",  0,            "allow everything to be queued without search terms", false);
    185     psMetadataAddS16(revertprocessedexpArgs, PS_LIST_TAIL, "-code",  0,            "search by fault code", 0);
    186192
    187193    // -updateprocessedexp
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/chiptool.c

    r23352 r23594  
    209209            return false;
    210210        }
    211 
     211        //
    212212        // queue the exp
    213213        if (!pxchipQueueByExpTag(config, exp_id, workdir, label, reduction, expgroup, dvodb, tess_id, end_stage)) {
     
    415415    PXOPT_LOOKUP_F32(n_cr, config->args,           "-n_cr", false, false);
    416416    PXOPT_LOOKUP_STR(path_base, config->args,      "-path_base", false, false);
     417    PXOPT_LOOKUP_BOOL(magicked, config->args,      "-magicked", false);
    417418
    418419    // default values
     
    490491                                   path_base,
    491492                                   code,
    492                                    0    // magic_ds_id
     493                                   magicked
    493494            )) {
    494495        // rollback
     
    540541    PXOPT_COPY_STR(config->args, where, "-reduction", "chipRun.reduction", "==");
    541542    PXOPT_COPY_STR(config->args, where, "-label", "chipRun.label", "LIKE");
     543    PXOPT_COPY_S32(config->args, where, "-magicked", "chipRun.magicked", "==");
    542544
    543545    psString query = pxDataGet("chiptool_processedimfile.sql");
     
    11371139        }
    11381140
    1139         // set chipRun.state to 'stop'
    1140         if (!pxchipRunSetState(config, chipRun->chip_id, "full")) {
     1141        // set chipRun.state to 'stop' and update the magicked state
     1142        if (!pxchipRunSetState(config, chipRun->chip_id, "full", chipRun->magicked)) {
    11411143            psError(PS_ERR_UNKNOWN, false, "failed to change chipRun.state for chip_id: %" PRId64, chipRun->chip_id);
    11421144            psFree(chipRun);
     
    12091211    }
    12101212
     1213    psString set_magic = "";
     1214    if (!strcmp(data_state, "full")) {
     1215        // copy the magicked state from the input to the output when transitioning to full state
     1216        set_magic = "\n , chipProcessedImfile.magicked = rawImfile.magicked";
     1217    }
     1218
    12111219    // note only updates if chipRun.state = run_state
    1212     if (!p_psDBRunQueryF(config->dbh, query, data_state, chip_id, class_id, run_state)) {
     1220    // XXX note that we have removed this constraint for now
     1221    if (!p_psDBRunQueryF(config->dbh, query, data_state, set_magic, chip_id, class_id)) {
     1222        psFree(query);
    12131223        psError(PS_ERR_UNKNOWN, false, "database error");
    12141224        // rollback
     
    12271237    query = pxDataGet("chiptool_change_exp_state.sql");
    12281238    if (!p_psDBRunQueryF(config->dbh, query, data_state, chip_id, data_state)) {
     1239        psFree(query);
    12291240        // rollback
    12301241        if (!psDBRollback(config->dbh)) {
     
    12341245        return false;
    12351246    }
     1247    psFree(query);
    12361248
    12371249    if (!psDBCommit(config->dbh)) {
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/chiptoolConfig.c

    r23352 r23594  
    6666    pxchipSetSearchArgs (updaterunArgs);
    6767    psMetadataAddS64(updaterunArgs, PS_LIST_TAIL, "-chip_id",              0,            "search by chip ID", 0);
    68     psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-state", 0,            "set state", NULL);
     68    psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-state", 0,            "search by state", NULL);
    6969    psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-label",  0,          "search by label", NULL);
    7070    psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-set_state", 0,        "set state", NULL);
     
    147147    psMetadataAddStr(addprocessedimfileArgs, PS_LIST_TAIL, "-path_base",  0,            "define base output location", NULL);
    148148    psMetadataAddS16(addprocessedimfileArgs, PS_LIST_TAIL, "-code",  0,            "set fault code", 0);
     149    psMetadataAddBool(addprocessedimfileArgs, PS_LIST_TAIL, "-magicked",  0,        "define magicked status", false);
    149150
    150151    // -processedimfile
     
    155156    psMetadataAddStr(processedimfileArgs,  PS_LIST_TAIL, "-reduction",          0, "search by reduction class", NULL);
    156157    psMetadataAddStr(processedimfileArgs,  PS_LIST_TAIL, "-label",              0, "search by chipRun label (LIKE comparison)", NULL);
     158    psMetadataAddBool(processedimfileArgs, PS_LIST_TAIL, "-magicked",  0,        "search by magicked status", false);
    157159    pxchipSetSearchArgs(processedimfileArgs);
    158160    psMetadataAddU64(processedimfileArgs, PS_LIST_TAIL, "-limit",  0,           "limit result set to N items", 0);
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/difftool.c

    r23352 r23594  
    4141static bool definepoprunMode(pxConfig *config);
    4242static bool definebyqueryMode(pxConfig *config);
     43static bool definewarpwarpMode(pxConfig *config);
    4344static bool pendingcleanuprunMode(pxConfig *config);
    4445static bool pendingcleanupskyfileMode(pxConfig *config);
     
    4849static bool importrunMode(pxConfig *config);
    4950
    50 static bool setdiffRunState(pxConfig *config, psS64 diff_id, const char *state);
     51static bool setdiffRunState(pxConfig *config, psS64 diff_id, const char *state, bool magicked);
    5152static bool diffRunComplete(pxConfig *config);
    5253
     
    7980        MODECASE(DIFFTOOL_MODE_DEFINEPOPRUN,          definepoprunMode);
    8081        MODECASE(DIFFTOOL_MODE_DEFINEBYQUERY,         definebyqueryMode);
     82        MODECASE(DIFFTOOL_MODE_DEFINEWARPWARP,        definewarpwarpMode);
    8183        MODECASE(DIFFTOOL_MODE_PENDINGCLEANUPRUN,     pendingcleanuprunMode);
    8284        MODECASE(DIFFTOOL_MODE_PENDINGCLEANUPSKYFILE, pendingcleanupskyfileMode);
     
    131133            registered,
    132134            tess_id,
    133             exp_id
     135            exp_id,
     136            false
    134137    );
    135138    if (!run) {
     
    168171    if (state) {
    169172        // set detRun.state to state
    170         return setdiffRunState(config, diff_id, state);
     173        return setdiffRunState(config, diff_id, state, false);
    171174    }
    172175
     
    282285
    283286    if (count == 2) {
    284         if (!setdiffRunState(config, diff_id, "new")) {
     287        if (!setdiffRunState(config, diff_id, "new", false)) {
    285288            if (!psDBRollback(config->dbh)) {
    286289                psError(PS_ERR_UNKNOWN, false, "database error");
     
    506509    PXOPT_LOOKUP_STR(hostname, config->args, "-hostname", false, false);
    507510    PXOPT_LOOKUP_F32(good_frac, config->args, "-good_frac", false, false);
     511    PXOPT_LOOKUP_BOOL(magicked, config->args, "-magicked", false);
    508512
    509513    if (!psDBTransaction(config->dbh)) {
     
    537541                           good_frac,
    538542                           code,
    539                            0        // magic_ds_id
     543                           magicked
    540544          )) {
    541545        if (!psDBRollback(config->dbh)) {
     
    730734
    731735
    732 static bool setdiffRunState(pxConfig *config, psS64 diff_id, const char *state)
     736static bool setdiffRunState(pxConfig *config, psS64 diff_id, const char *state, bool magicked)
    733737{
    734738    PS_ASSERT_PTR_NON_NULL(state, false);
     
    740744    }
    741745
    742     char *query = "UPDATE diffRun SET state = '%s' WHERE diff_id = %"PRId64;
    743     if (!p_psDBRunQueryF(config->dbh, query, state, diff_id)) {
     746    char *query = "UPDATE diffRun SET state = '%s', magicked = %d WHERE diff_id = %"PRId64;
     747
     748    if (!p_psDBRunQueryF(config->dbh, query, state, magicked, diff_id)) {
    744749        psError(PS_ERR_UNKNOWN, false,
    745750                "failed to change state for diff_id %"PRId64, diff_id);
     
    792797            registered,
    793798            tess_id,
    794             exp_id
     799            exp_id,
     800            false       // magicked
    795801    );
    796802
     
    10021008    psTrace("difftool", 1, query, warpQuery, diffQuery, expQuery, stackQuery);
    10031009
     1010    if (!psDBTransaction(config->dbh)) {
     1011        psError(PS_ERR_UNKNOWN, false, "database error");
     1012        return false;
     1013    }
    10041014
    10051015    if (!p_psDBRunQueryF(config->dbh, query, warpQuery, expQuery, diffQuery)) {
    10061016        psError(PS_ERR_UNKNOWN, false, "database error");
    10071017        psFree(query);
     1018        if (!psDBRollback(config->dbh)) {
     1019            psError(PS_ERR_UNKNOWN, false, "database error");
     1020        }
    10081021        return false;
    10091022    }
     
    10141027        psErrorCode err = psErrorCodeLast();
    10151028        switch (err) {
    1016             case PS_ERR_DB_CLIENT:
    1017                 psError(PXTOOLS_ERR_SYS, false, "database error");
    1018             case PS_ERR_DB_SERVER:
    1019                 psError(PXTOOLS_ERR_PROG, false, "database error");
    1020             default:
    1021                 psError(PXTOOLS_ERR_PROG, false, "unknown error");
    1022         }
    1023 
     1029          case PS_ERR_DB_CLIENT:
     1030            psError(PXTOOLS_ERR_SYS, false, "database error");
     1031            break;
     1032          case PS_ERR_DB_SERVER:
     1033            psError(PXTOOLS_ERR_PROG, false, "database error");
     1034            break;
     1035          default:
     1036            psError(PXTOOLS_ERR_PROG, false, "unknown error");
     1037            break;
     1038        }
     1039        if (!psDBRollback(config->dbh)) {
     1040            psError(PS_ERR_UNKNOWN, false, "database error");
     1041        }
    10241042        return false;
    10251043    }
     
    10271045        psTrace("difftool", PS_LOG_INFO, "no rows found");
    10281046        psFree(output);
     1047        if (!psDBCommit(config->dbh)) {
     1048            psError(PS_ERR_UNKNOWN, false, "database error");
     1049            return false;
     1050        }
    10291051        return true;
    10301052    }
     
    10351057        psError(PS_ERR_UNKNOWN, false, "database error");
    10361058        psFree(query);
     1059        if (!psDBRollback(config->dbh)) {
     1060            psError(PS_ERR_UNKNOWN, false, "database error");
     1061        }
    10371062        return false;
    10381063    }
     
    10551080        if (!mdok) {
    10561081            psError(PXTOOLS_ERR_PROG, false, "exp_id not found");
     1082            if (!psDBRollback(config->dbh)) {
     1083                psError(PS_ERR_UNKNOWN, false, "database error");
     1084            }
    10571085            return false;
    10581086        }
     
    10681096            psFree(stackQuery);
    10691097            psFree(skycell_query);
     1098            if (!psDBRollback(config->dbh)) {
     1099                psError(PS_ERR_UNKNOWN, false, "database error");
     1100            }
    10701101            return false;
    10711102        }
     
    10761107            psFree(stackQuery);
    10771108            psFree(skycell_query);
     1109            if (!psDBRollback(config->dbh)) {
     1110                psError(PS_ERR_UNKNOWN, false, "database error");
     1111            }
    10781112            return false;
    10791113        }
     
    10841118            psFree(stackQuery);
    10851119            psFree(skycell_query);
     1120            if (!psDBRollback(config->dbh)) {
     1121                psError(PS_ERR_UNKNOWN, false, "database error");
     1122            }
    10861123            return false;
    10871124        }
     
    10921129            psFree(stackQuery);
    10931130            psFree(skycell_query);
     1131            if (!psDBRollback(config->dbh)) {
     1132                psError(PS_ERR_UNKNOWN, false, "database error");
     1133            }
    10941134            return false;
    10951135        }
     
    11001140            psFree(stackQuery);
    11011141            psFree(skycell_query);
     1142            if (!psDBRollback(config->dbh)) {
     1143                psError(PS_ERR_UNKNOWN, false, "database error");
     1144            }
    11021145            return false;
    11031146        }
     
    11071150            psFree(stackQuery);
    11081151            psFree(skycell_query);
     1152            if (!psDBRollback(config->dbh)) {
     1153                psError(PS_ERR_UNKNOWN, false, "database error");
     1154            }
    11091155            return false;
    11101156        }
     
    11321178                registered,
    11331179                tess_id,
    1134                 exp_id
     1180                exp_id,
     1181                false       // magicked
    11351182        );
    11361183
     
    11381185            psError(PS_ERR_UNKNOWN, false, "database error");
    11391186            psFree(run);
    1140             return true;
     1187            if (!psDBRollback(config->dbh)) {
     1188                psError(PS_ERR_UNKNOWN, false, "database error");
     1189            }
     1190            return false;
    11411191        }
    11421192        run->diff_id = psDBLastInsertID(config->dbh);
     
    11491199            psFree(skycell_query);
    11501200            psFree(query);
     1201        if (!psDBRollback(config->dbh)) {
     1202            psError(PS_ERR_UNKNOWN, false, "database error");
     1203        }
    11511204            return false;
    11521205        }
     
    11601213            psFree(skycell_query);
    11611214            psFree(query);
     1215            if (!psDBRollback(config->dbh)) {
     1216                psError(PS_ERR_UNKNOWN, false, "database error");
     1217            }
    11621218            return false;
    11631219        }
     
    11651221        query = NULL;
    11661222
    1167         if (!setdiffRunState(config, run->diff_id, "new")) {
     1223        if (!setdiffRunState(config, run->diff_id, "new", false)) {
    11681224            psError(PS_ERR_UNKNOWN, false, "failed to change diffRun.state for diff_id: %" PRId64,
    11691225                run->diff_id);
     
    11721228            psFree(skycell_query);
    11731229            psFree(query);
     1230            if (!psDBRollback(config->dbh)) {
     1231                psError(PS_ERR_UNKNOWN, false, "database error");
     1232            }
    11741233            return false;
    11751234        }
     
    11831242    psFree(skycell_query);
    11841243
     1244    if (!psDBCommit(config->dbh)) {
     1245        psError(PS_ERR_UNKNOWN, false, "database error");
     1246        psFree(list);
     1247        return false;
     1248    }
     1249
    11851250    if (!diffRunPrintObjects(stdout, list, !simple)) {
    11861251        psError(PS_ERR_UNKNOWN, false, "failed to print object");
     
    11921257    return true;
    11931258}
     1259
     1260static bool definewarpwarpMode(pxConfig *config)
     1261{
     1262    PS_ASSERT_PTR_NON_NULL(config, false);
     1263
     1264    psMetadata *selectWhere = psMetadataAlloc();
     1265    psMetadata *insertWhere = psMetadataAlloc();
     1266
     1267    // Restrictions for selecting warps
     1268    PXOPT_COPY_S64(config->args, selectWhere, "-warp_id", "inputWarpRun.warp_id", "==");
     1269    PXOPT_COPY_S64(config->args, selectWhere, "-exp_id", "inputRawExp.exp_id", "==");
     1270    PXOPT_COPY_STR(config->args, selectWhere, "-filter", "inputRawExp.filter", "==");
     1271    PXOPT_COPY_STR(config->args, selectWhere, "-input_label", "inputWarpRun.label", "==");
     1272    PXOPT_COPY_STR(config->args, selectWhere, "-template_label", "templateWarpRun.label", "==");
     1273    PXOPT_COPY_F32(config->args, selectWhere, "-timediff",
     1274                   "ABS(TIME_TO_SEC(TIMEDIFF(inputRawExp.dateobs, templateRawExp.dateobs)))", "<=");
     1275    PXOPT_COPY_F32(config->args, selectWhere, "-rotdiff", "ABS(inputRawExp.posang - templateRawExp.posang)", "<=");
     1276
     1277    // Restrictions for inserting skycells
     1278    PXOPT_COPY_F32(config->args, insertWhere, "-good_frac", "inputWarpSkyfile.good_frac", ">=");
     1279    PXOPT_COPY_F32(config->args, insertWhere, "-good_frac", "templateWarpSkyfile.good_frac", ">=");
     1280
     1281    // Additional controls
     1282    PXOPT_LOOKUP_BOOL(rerun, config->args, "-rerun", false);
     1283    PXOPT_LOOKUP_BOOL(available, config->args, "-available", false);
     1284
     1285    // Settings to apply to defined run
     1286    PXOPT_LOOKUP_STR(workdir, config->args, "-workdir", true, false); // required options
     1287    PXOPT_LOOKUP_STR(reduction, config->args, "-reduction", false, false); // option
     1288    PXOPT_LOOKUP_STR(label, config->args, "-label", false, false); // option
     1289    PXOPT_LOOKUP_TIME(registered, config->args, "-registered", false, false);
     1290    PXOPT_LOOKUP_BOOL(simple, config->args, "-simple", false);
     1291
     1292
     1293    psString select = pxDataGet("difftool_definewarpwarp_select.sql");
     1294    if (!select) {
     1295        psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
     1296        return false;
     1297    }
     1298
     1299    psString whereClause = NULL; // The WHERE part of the query
     1300
     1301    if (psListLength(selectWhere->list)) {
     1302        psString new = psDBGenerateWhereConditionSQL(selectWhere, NULL);
     1303        psStringAppend(&whereClause, "\n%s %s", whereClause ? "AND" : "WHERE", new);
     1304        psFree(new);
     1305    }
     1306    psFree(selectWhere);
     1307
     1308    if (!rerun) {
     1309        psStringAppend(&whereClause, "\n%s diffRun.diff_id IS NULL", whereClause ? "AND" : "WHERE");
     1310    }
     1311
     1312    if (!available) {
     1313        psStringAppend(&whereClause, "\n%s inputWarpRun.state = 'full'", whereClause ? "AND" : "WHERE");
     1314    }
     1315
     1316    if (!psDBTransaction(config->dbh)) {
     1317        psError(PS_ERR_UNKNOWN, false, "database error");
     1318        psFree(select);
     1319        psFree(whereClause);
     1320        psFree(insertWhere);
     1321        return false;
     1322    }
     1323
     1324    if (!p_psDBRunQueryF(config->dbh, select,
     1325                         !rerun ? "\n" : "", // Activate LEFT JOIN against diffRun?
     1326                         whereClause)) {
     1327        psError(PS_ERR_UNKNOWN, false, "Unable to run query: %s [WITH] %s", select, whereClause);
     1328        psFree(select);
     1329        psFree(whereClause);
     1330        psFree(insertWhere);
     1331        if (!psDBRollback(config->dbh)) {
     1332            psError(PS_ERR_UNKNOWN, false, "database error");
     1333        }
     1334        return false;
     1335    }
     1336    psFree(select);
     1337    psFree(whereClause);
     1338
     1339    psArray *results = p_psDBFetchResult(config->dbh); // Results of query
     1340    if (!results) {
     1341        psErrorCode err = psErrorCodeLast(); // Code for error
     1342        switch (err) {
     1343          case PS_ERR_DB_CLIENT:
     1344            psError(PXTOOLS_ERR_SYS, false, "database error");
     1345            break;
     1346          case PS_ERR_DB_SERVER:
     1347            psError(PXTOOLS_ERR_PROG, false, "database error");
     1348            break;
     1349          default:
     1350            psError(PXTOOLS_ERR_PROG, false, "unknown error");
     1351            break;
     1352        }
     1353        if (!psDBRollback(config->dbh)) {
     1354            psError(PS_ERR_UNKNOWN, false, "database error");
     1355        }
     1356        psFree(insertWhere);
     1357        return false;
     1358    }
     1359    if (!psArrayLength(results)) {
     1360        psTrace("difftool", 1, "no rows found");
     1361        psFree(results);
     1362        psFree(insertWhere);
     1363        if (!psDBCommit(config->dbh)) {
     1364            psError(PS_ERR_UNKNOWN, false, "database error");
     1365            return false;
     1366        }
     1367        return true;
     1368    }
     1369
     1370    psString insert = pxDataGet("difftool_definewarpwarp_insert.sql"); // Insertion for each new run
     1371
     1372    if (psListLength(insertWhere->list)) {
     1373        psString whereClause = psDBGenerateWhereConditionSQL(insertWhere, NULL);
     1374        psStringAppend(&insert, "\n%s", whereClause);
     1375        psFree(whereClause);
     1376    }
     1377    psFree(insertWhere);
     1378
     1379    psArray *list = psArrayAllocEmpty(16); // List of runs defined, to print
     1380    long numGood = 0;                   // Number of good rows added
     1381    for (long i = 0; i < results->n; i++) {
     1382        psMetadata *row = results->data[i]; // Result row from query
     1383
     1384        psS64 exp_id = psMetadataLookupS64(NULL, row, "input_exp_id");
     1385        psS64 input_id = psMetadataLookupS64(NULL, row, "input_warp_id");
     1386        psS64 template_id = psMetadataLookupS64(NULL, row, "template_warp_id");
     1387        const char *tess_id = psMetadataLookupStr(NULL, row, "tess_id");
     1388        if (!exp_id || !input_id || !template_id || !tess_id) {
     1389            psError(PXTOOLS_ERR_PROG, false, "Identifiers not found");
     1390            psFree(list);
     1391            psFree(insert);
     1392            psFree(results);
     1393            if (!psDBRollback(config->dbh)) {
     1394                psError(PS_ERR_UNKNOWN, false, "database error");
     1395            }
     1396            return false;
     1397        }
     1398
     1399        diffRunRow *run = diffRunRowAlloc(0, "reg", workdir, label, reduction, NULL, registered,
     1400                                          tess_id, exp_id, false); // Run to insert
     1401        if (!diffRunInsertObject(config->dbh, run)) {
     1402            psError(PS_ERR_UNKNOWN, false, "database error");
     1403            psFree(run);
     1404            psFree(list);
     1405            psFree(insert);
     1406            psFree(results);
     1407            if (!psDBRollback(config->dbh)) {
     1408                psError(PS_ERR_UNKNOWN, false, "database error");
     1409            }
     1410            return false;
     1411        }
     1412        run->diff_id = psDBLastInsertID(config->dbh); // Difference run identifier
     1413
     1414        // Convert identifiers to string, for insertion into query
     1415        psString diff = NULL, input = NULL, template = NULL; // String versions of identifiers
     1416        psStringAppend(&diff, "%" PRId64, run->diff_id);
     1417        psStringAppend(&input, "%" PRId64, input_id);
     1418        psStringAppend(&template, "%" PRId64, template_id);
     1419
     1420        if (!p_psDBRunQueryF(config->dbh, insert, diff, input, template, input, template)) {
     1421            psError(PS_ERR_UNKNOWN, false, "database error");
     1422            psFree(input);
     1423            psFree(template);
     1424            psFree(diff);
     1425            psFree(run);
     1426            psFree(list);
     1427            psFree(insert);
     1428            psFree(results);
     1429            if (!psDBRollback(config->dbh)) {
     1430                psError(PS_ERR_UNKNOWN, false, "database error");
     1431            }
     1432            return false;
     1433        }
     1434        psFree(input);
     1435        psFree(template);
     1436        psFree(diff);
     1437
     1438        if (!setdiffRunState(config, run->diff_id, "new", false)) {
     1439            psError(PS_ERR_UNKNOWN, false, "Failed to change diffRun.state for diff_id: %" PRId64,
     1440                    run->diff_id);
     1441            psFree(run);
     1442            psFree(list);
     1443            psFree(insert);
     1444            psFree(results);
     1445            if (!psDBRollback(config->dbh)) {
     1446                psError(PS_ERR_UNKNOWN, false, "database error");
     1447            }
     1448            return false;
     1449        }
     1450
     1451        psArrayAdd(list, list->n, run);
     1452        psFree(run);                    // Drop reference
     1453
     1454        numGood++;
     1455    }
     1456    psFree(insert);
     1457    psFree(results);
     1458
     1459    if (!psDBCommit(config->dbh)) {
     1460        psError(PS_ERR_UNKNOWN, false, "database error");
     1461        psFree(list);
     1462        return false;
     1463    }
     1464
     1465    if (!diffRunPrintObjects(stdout, list, !simple)) {
     1466        psError(PS_ERR_UNKNOWN, false, "failed to print object");
     1467        psFree(list);
     1468        return false;
     1469    }
     1470    psFree(list);
     1471
     1472    return true;
     1473}
     1474
    11941475
    11951476static bool pendingcleanuprunMode(pxConfig *config)
     
    14281709
    14291710        psS64 diff_id = psMetadataLookupS64(NULL, row, "diff_id");
     1711        bool magicked = psMetadataLookupBool(NULL, row, "magicked");
    14301712
    14311713        // set diffRun.state to 'stop'
    1432         if (!setdiffRunState(config, diff_id, "full")) {
     1714        if (!setdiffRunState(config, diff_id, "full", magicked)) {
    14331715            psError(PS_ERR_UNKNOWN, false, "failed to change diffRun.state for diff_id: %" PRId64,
    14341716                diff_id);
     
    14471729    char sqlFilename[80];
    14481730  } ExportTable;
    1449  
     1731
    14501732  int numExportFiles = 3;
    14511733
     
    15261808{
    15271809  unsigned int nFail;
    1528  
     1810
    15291811  int numImportTables = 2;
    1530  
     1812
    15311813  char tables[2] [80] = {"diffInputSkyfile", "diffSkyfile"};
    15321814
    15331815  PS_ASSERT_PTR_NON_NULL(config, NULL);
    1534  
     1816
    15351817  PXOPT_LOOKUP_STR(infile, config->args, "-infile", true,  false);
    15361818
     
    15571839    psAssert (item, "entry not in input?");
    15581840    psAssert (item->type == PS_DATA_METADATA_MULTI, "entry not multi?");
    1559  
     1841
    15601842    switch (i) {
    15611843      case 0:
     
    15711853        }
    15721854        break;
    1573        
     1855
    15741856      case 1:
    15751857        for (int i = 0; i < item->data.list->n; i++) {
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/difftool.h

    r23352 r23594  
    3535    DIFFTOOL_MODE_DEFINEPOPRUN,
    3636    DIFFTOOL_MODE_DEFINEBYQUERY,
     37    DIFFTOOL_MODE_DEFINEWARPWARP,
    3738    DIFFTOOL_MODE_PENDINGCLEANUPRUN,
    3839    DIFFTOOL_MODE_PENDINGCLEANUPSKYFILE,
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/difftoolConfig.c

    r23352 r23594  
    107107    psMetadataAddF32(adddiffskyfileArgs, PS_LIST_TAIL, "-kernel_xy",  0, "define kernel xy moment", NAN);
    108108    psMetadataAddF32(adddiffskyfileArgs, PS_LIST_TAIL, "-kernel_yy",  0, "define kernel yy moment", NAN);
    109     psMetadataAddS32(adddiffskyfileArgs, PS_LIST_TAIL, "-sources",  0,            "define number of sources", 0);
    110     psMetadataAddStr(adddiffskyfileArgs, PS_LIST_TAIL, "-hostname", 0,            "define hostname", 0);
    111     psMetadataAddF32(adddiffskyfileArgs, PS_LIST_TAIL, "-good_frac",  0,            "define %% of good pixels", NAN);
     109    psMetadataAddS32(adddiffskyfileArgs, PS_LIST_TAIL, "-sources",  0,   "define number of sources", 0);
     110    psMetadataAddStr(adddiffskyfileArgs, PS_LIST_TAIL, "-hostname", 0,   "define hostname", 0);
     111    psMetadataAddF32(adddiffskyfileArgs, PS_LIST_TAIL, "-good_frac",  0, "define %% of good pixels", NAN);
     112    psMetadataAddBool(adddiffskyfileArgs, PS_LIST_TAIL, "-magicked",  0, "define magicked state", false);
    112113
    113114    // -diffskyfile
     
    164165    psMetadataAddBool(definebyqueryArgs, PS_LIST_TAIL, "-simple", 0, "use the simple output format", false);
    165166
     167    // -definewarpwarp
     168    psMetadata *definewarpwarpArgs = psMetadataAlloc();
     169    psMetadataAddS64(definewarpwarpArgs, PS_LIST_TAIL, "-warp_id", 0, "search by warp ID", 0);
     170    psMetadataAddS64(definewarpwarpArgs, PS_LIST_TAIL, "-exp_id", 0, "search by exposure ID", 0);
     171    psMetadataAddStr(definewarpwarpArgs, PS_LIST_TAIL, "-filter", 0, "search by filter", NULL);
     172    psMetadataAddF32(definewarpwarpArgs, PS_LIST_TAIL, "-timediff", 0, "limit time difference between input and template", NAN);
     173    psMetadataAddF32(definewarpwarpArgs, PS_LIST_TAIL, "-rotdiff", 0, "limit rotator difference between input and template", NAN);
     174    psMetadataAddStr(definewarpwarpArgs, PS_LIST_TAIL, "-input_label", 0, "search by warp label for input", NULL);
     175    psMetadataAddStr(definewarpwarpArgs, PS_LIST_TAIL, "-template_label", 0, "search by warp label for template", NULL);
     176    psMetadataAddF32(definewarpwarpArgs, PS_LIST_TAIL, "-good_frac", 0, "minimum good fraction of skycell", NAN);
     177    psMetadataAddStr(definewarpwarpArgs, PS_LIST_TAIL, "-workdir", 0, "define workdir (required)", NULL);
     178    psMetadataAddStr(definewarpwarpArgs, PS_LIST_TAIL, "-label",  0, "define label", NULL);
     179    psMetadataAddStr(definewarpwarpArgs, PS_LIST_TAIL, "-reduction",  0, "define reduction class", NULL);
     180    psMetadataAddTime(definewarpwarpArgs, PS_LIST_TAIL, "-registered", 0, "time detrend run was registered", now);
     181    psMetadataAddBool(definewarpwarpArgs, PS_LIST_TAIL, "-rerun", 0, "define new run even if one exists", false);
     182    psMetadataAddBool(definewarpwarpArgs, PS_LIST_TAIL, "-available", 0, "define new run even if warpRun has some faults", false);
     183    psMetadataAddBool(definewarpwarpArgs, PS_LIST_TAIL, "-simple", 0, "use the simple output format", false);
     184
    166185    // -pendingcleanuprun
    167186    psMetadata *pendingcleanuprunArgs = psMetadataAlloc();
     
    214233    PXOPT_ADD_MODE("-definepoprun",     "", DIFFTOOL_MODE_DEFINEPOPRUN,      definepoprunArgs);
    215234    PXOPT_ADD_MODE("-definebyquery",    "", DIFFTOOL_MODE_DEFINEBYQUERY,     definebyqueryArgs);
     235    PXOPT_ADD_MODE("-definewarpwarp",   "", DIFFTOOL_MODE_DEFINEWARPWARP,    definewarpwarpArgs);
    216236    PXOPT_ADD_MODE("-pendingcleanuprun",     "show runs that need to be cleaned up", DIFFTOOL_MODE_PENDINGCLEANUPRUN,    pendingcleanuprunArgs);
    217237    PXOPT_ADD_MODE("-pendingcleanupskyfile", "show runs that need to be cleaned up", DIFFTOOL_MODE_PENDINGCLEANUPSKYFILE, pendingcleanupskyfileArgs);
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/disttool.c

    r23352 r23594  
    9898    PXOPT_LOOKUP_STR(set_label, config->args, "-set_label", false, false);
    9999
    100     bool require_chip_id = false;
    101     if (!strcmp(stage, "raw")) {
    102         // need to know the chip id for raw stage so that we can find the masks
    103         require_chip_id = true;
    104     }
    105     PXOPT_LOOKUP_S64(chip_id, config->args, "-chip_id",  require_chip_id, false);
    106 
    107100    // TODO: check that stage has an expected value
     101    // XXX: all of the following concerns will be managed properly by definebyquery
     102
    108103    // TODO: check that stage_id actually exists for stage
    109104    // in magicdstool we queue off of a magic_id so the stage_id, exp_id, and cam_id get looked up
     
    113108    // change between the time that it is queued.
    114109
    115     if (!distRunInsert(config->dbh, 0, stage, stage_id, chip_id, set_label, outroot, clean, "new", 0)) {
     110    if (!distRunInsert(config->dbh, 0, stage, stage_id, set_label, outroot, clean, "new", NULL, 0)) {
    116111        psError(PS_ERR_UNKNOWN, false, "database error");
    117112        return false;
     
    151146    }
    152147
    153     psString query = psStringCopy("UPDATE distRun");
     148    psString query = psStringCopy("UPDATE distRun SET time_stamp = UTC_TIMESTAMP()");
    154149
    155150    if (state) {
    156         psStringAppend(&query, " SET state = '%s'", state);
     151        psStringAppend(&query, " , state = '%s'", state);
    157152    }
    158153
    159154    if (label) {
    160         psStringAppend(&query, " SET label = '%s'", label);
     155        psStringAppend(&query, " , label = '%s'", label);
    161156    }
    162157
    163158    if (code) {
    164         psStringAppend(&query, " SET fault = %d", code);
     159        psStringAppend(&query, " , fault = %d", code);
    165160    }
    166161
     
    301296    PXOPT_LOOKUP_U64(limit, config->args, "-limit", false, false);
    302297    PXOPT_LOOKUP_BOOL(simple, config->args, "-simple", false);
     298    PXOPT_LOOKUP_BOOL(need_magic, config->args, "-need_magic", false);
    303299
    304300    // look for "inputs" that need to processed
     
    323319    }
    324320
    325     if (!p_psDBRunQuery(config->dbh, query)) {
     321    psString    chip_magic = "";
     322    psString    raw_where = "";
     323    psString    chip_where = "";
     324    psString    camera_where = "";
     325    psString    fake_where = "";
     326    psString    warp_where = "";
     327    psString    diff_where = "";
     328    psString    stack_where = "";
     329
     330    if (need_magic) {
     331        chip_magic = psStringCopy("\nAND chipRun.magicked");
     332        raw_where  = psStringCopy("\nAND rawExp.magicked");
     333        chip_where = psStringCopy("\nAND (distRun.clean OR chipRun.magicked)");
     334        // chipRun must be magicked to allow release camera level masks
     335        camera_where = psStringCopy("\nAND (distRun.clean OR chipRun.magicked)");
     336        warp_where = psStringCopy("\nAND (distRun.clean OR warpRun.magicked)");
     337        diff_where = psStringCopy("\nAND (distRun.clean OR diffRun.magicked)");
     338    }
     339
     340    if (!p_psDBRunQueryF(config->dbh,
     341            query,
     342            chip_magic,
     343            raw_where,
     344            chip_where,
     345            camera_where,
     346            fake_where,
     347            warp_where,
     348            diff_where,
     349            stack_where)) {
    326350        psError(PS_ERR_UNKNOWN, false, "database error");
    327351        psFree(query);
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/disttoolConfig.c

    r23352 r23594  
    4747    psMetadataAddStr(definerunArgs, PS_LIST_TAIL, "-stage",         0, "define stage for bundle (required)", NULL);
    4848    psMetadataAddS64(definerunArgs, PS_LIST_TAIL, "-stage_id", 0, "define stage_id (required)", 0);
    49     psMetadataAddS64(definerunArgs, PS_LIST_TAIL, "-chip_id", 0, "define chip_id (required for raw stage", 0);
    5049    psMetadataAddStr(definerunArgs, PS_LIST_TAIL, "-outroot",  0, "define output destination (required)", NULL);
    5150    psMetadataAddBool(definerunArgs, PS_LIST_TAIL, "-clean", 0,   "build clean distribution bundle", false);
     
    7675    psMetadataAddS64(pendingcomponentArgs, PS_LIST_TAIL, "-dist_id", 0, "define dist_id", 0);
    7776    psMetadataAddStr(pendingcomponentArgs, PS_LIST_TAIL, "-stage",    0, "limit results to runs for stage", NULL);
     77    psMetadataAddBool(pendingcomponentArgs, PS_LIST_TAIL, "-need_magic", 0, "magic is needed", false);
    7878    psMetadataAddStr(pendingcomponentArgs, PS_LIST_TAIL, "-label",    0, "limit results to label", NULL);
    7979    psMetadataAddU64(pendingcomponentArgs, PS_LIST_TAIL, "-limit",  0,  "limit result set to N items", 0);
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/magicdstool.c

    r21433 r23594  
    4040
    4141static bool setmagicDSRunState(pxConfig *config, psS64 magic_id, const char *state);
    42 static bool magicDSRunComplete(pxConfig *config);
     42static bool magicDSRunComplete(pxConfig *config, bool setmagicked);
    4343static bool magicDSGetIDs(pxConfig *config, psString stage, psS64 magic_id, psS64 *stage_id, psS64 *cam_id);
    4444
     
    242242
    243243        // create a new magicRun for this group
    244         magicRunRow *run = magicRunRowAlloc(0, exp_id, "run", workdir, "dirty", label, dvodb, registered, 0);
     244        magicRunRow *run = magicRunRowAlloc(0, exp_id, "new", workdir, "dirty", label, dvodb, registered, 0);
    245245        if (!run) {
    246246            psAbort("failed to alloc magicRun object");
     
    320320    PXOPT_LOOKUP_STR(stage, config->args, "-stage", true, false);
    321321    PXOPT_LOOKUP_STR(outroot, config->args, "-outroot", true, false);
     322
     323    // optional
    322324    PXOPT_LOOKUP_STR(recoveryroot, config->args, "-recoveryroot", false, false);
    323325    PXOPT_LOOKUP_BOOL(re_place, config->args, "-replace", false);
    324326    PXOPT_LOOKUP_BOOL(remove, config->args, "-remove", false);
    325 
    326     // optional
    327327    PXOPT_LOOKUP_BOOL(simple, config->args, "-simple", false);
     328    PXOPT_LOOKUP_STR(label, config->args, "-label", false, false);
    328329
    329330    psS64 stage_id = 0, cam_id = 0;
     
    337338            0,          // ID
    338339            magic_id,
    339             "run",      // state
     340            "new",      // state
    340341            stage,
    341342            stage_id,
    342343            cam_id,
     344            label,
    343345            outroot,
    344346            recoveryroot,
     
    396398    PXOPT_COPY_S64(config->args, where, "-magic_ds_id", "magic_ds_id", "==");
    397399    PXOPT_COPY_S64(config->args, where, "-magic_id", "magic_id", "==");
    398 //    PXOPT_COPY_S64(config->args, where, "-exp_id", "exp_id", "==");
     400    PXOPT_COPY_STR(config->args, where, "-label", "label", "==");
    399401
    400402    PXOPT_LOOKUP_U64(limit, config->args, "-limit", false, false);
     
    526528}
    527529
     530static bool
     531setRunMagicked(pxConfig *config, psS64 magic_ds_id)
     532{
     533    // first query the magicDSRun to find the stage and the stage_id
     534    psString query = "SELECT stage, stage_id from magicDSRun where magic_ds_id = %" PRId64;
     535
     536    if (!p_psDBRunQueryF(config->dbh, query, magic_ds_id)) {
     537        psError(PS_ERR_UNKNOWN, false, "database error");
     538        return false;
     539    }
     540
     541    psArray *output = p_psDBFetchResult(config->dbh);
     542    if (!output) {
     543        psError(PS_ERR_UNKNOWN, false, "database error");
     544        return false;
     545    }
     546    if (!psArrayLength(output)) {
     547        psError(PS_ERR_UNKNOWN, true, "magicDSRun not found for magic_ds_id %" PRId64, magic_ds_id);
     548        psFree(output);
     549        return false;
     550    }
     551    if (psArrayLength(output) > 1) {
     552        psError(PS_ERR_UNKNOWN, true, "unexpected number of rows found %ld for magic_ds_id %" PRId64,
     553            psArrayLength(output), magic_ds_id);
     554        psFree(output);
     555        return false;
     556    }
     557    psMetadata *row = output->data[0];
     558
     559    psString stage = psMetadataLookupStr(NULL, row, "stage");
     560    psS64 stage_id = psMetadataLookupS64(NULL, row, "stage_id");
     561
     562
     563    // chose the appropriate query based on the stage
     564    if (!strcmp(stage, "raw")) {
     565        query = "UPDATE rawExp SET magicked = 1 where exp_id = %" PRId64;
     566    } else if (!strcmp(stage, "chip")) {
     567        query = "UPDATE chipRun SET magicked = 1 where chip_id = %" PRId64;
     568    } else if (!strcmp(stage, "warp")) {
     569        query = "UPDATE warpRun SET magicked = 1 where warp_id = %" PRId64;
     570    } else if (!strcmp(stage, "diff")) {
     571        query = "UPDATE diffRun SET magicked = 1 where diff_id = %" PRId64;
     572    } else {
     573        psError(PS_ERR_UNKNOWN, true, "unexpected value for stage: %s found", stage);
     574        psFree(output);
     575        return false;
     576    }
     577    if (!p_psDBRunQueryF(config->dbh, query, stage_id)) {
     578        psError(PS_ERR_UNKNOWN, false, "database error");
     579        return false;
     580    }
     581    psFree(output);
     582
     583    psU64 affected = psDBAffectedRows(config->dbh);
     584    if (affected != 1) {
     585        psError(PS_ERR_UNKNOWN, false, "should have affected 1 row");
     586        return false;
     587    }
     588
     589    return true;
     590}
     591
    528592static bool adddestreakedfileMode(pxConfig *config)
    529593{
     
    551615
    552616    if (setmagicked) {
     617        // set the image file's magicked flag
    553618        if (!setMagicked(config, magic_ds_id, component)) {
    554619            psError(PS_ERR_UNKNOWN, false, "setMagicked failed");
     620            if (!psDBRollback(config->dbh)) {
     621                psError(PS_ERR_UNKNOWN, false, "database error");
     622            }
    555623            return false;
    556624        }
     
    566634    }
    567635
    568     if (!magicDSRunComplete(config)) {
     636    if (!magicDSRunComplete(config, setmagicked)) {
    569637            // rollback
    570638        if (!psDBRollback(config->dbh)) {
     
    591659
    592660    if (!strcmp(stage, "diff")) {
    593         // don't need these ids for diff stage
     661        // don't need these ids for diff stage because diff_id is in the magicRun
    594662        *stage_id = 0;
    595663        *cam_id = 0;
     
    652720}
    653721
    654 static bool magicDSRunComplete(pxConfig *config)
     722static bool magicDSRunComplete(pxConfig *config, bool setmagicked)
    655723{
    656724    PS_ASSERT_PTR_NON_NULL(config, false);
     
    685753        psS64 magic_ds_id = psMetadataLookupS64(NULL, row, "magic_ds_id");
    686754
    687         // set magicDSRun.state to 'stop'
    688         if (!setmagicDSRunState(config, magic_ds_id, "stop")) {
     755        // if requested, set stageRun.magicked
     756        if (setmagicked && !setRunMagicked(config, magic_ds_id)) {
     757            psError(PS_ERR_UNKNOWN, false, "failed to change stageRun.magicked for magic_ds_id: %" PRId64,
     758                magic_ds_id);
     759            return false;
     760        }
     761
     762        // set magicDSRun.state to 'full'
     763        if (!setmagicDSRunState(config, magic_ds_id, "full")) {
    689764            psError(PS_ERR_UNKNOWN, false, "failed to change magicDSRun.state for magic_ds_id: %" PRId64,
    690765                magic_ds_id);
     
    795870    // check that state is a valid string value
    796871    if (!(
    797             (strncmp(state, "run", 4) == 0)
    798             || (strncmp(state, "stop", 5) == 0)
     872            (strncmp(state, "new", 4) == 0)
     873            || (strncmp(state, "full", 5) == 0)
    799874        )
    800875    ) {
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/magicdstoolConfig.c

    r21433 r23594  
    7070    psMetadataAddBool(definerunArgs, PS_LIST_TAIL, "-replace", 0, "use the simple output format", false);
    7171    psMetadataAddBool(definerunArgs, PS_LIST_TAIL, "-remove", 0, "use the simple output format", false);
    72 //    psMetadataAddStr(definerunArgs, PS_LIST_TAIL, "-label", 0, "define label", NULL);
     72    psMetadataAddStr(definerunArgs, PS_LIST_TAIL, "-label", 0, "define label", NULL);
    7373    psMetadataAddBool(definerunArgs, PS_LIST_TAIL, "-simple", 0, "use the simple output format", false);
    7474
     
    8888    psMetadataAddS64(todestreakArgs, PS_LIST_TAIL, "-magic_ds_id", 0, "search by magic Destreak ID", 0);
    8989    psMetadataAddS64(todestreakArgs, PS_LIST_TAIL, "-magic_id", 0, "search by magic ID", 0);
    90 //    psMetadataAddS64(todestreakArgs, PS_LIST_TAIL, "-exp_id", 0, "search by exposure ID", 0);
     90    psMetadataAddStr(todestreakArgs, PS_LIST_TAIL, "-label", 0, "define label", NULL);
    9191    psMetadataAddU64(todestreakArgs, PS_LIST_TAIL, "-limit", 0, "limit result set to N items", 0);
    9292    psMetadataAddBool(todestreakArgs, PS_LIST_TAIL, "-simple", 0, "use the simple output format", false);
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/magictool.c

    r21402 r23594  
    217217
    218218        // create a new magicRun for this group
    219         magicRunRow *run = magicRunRowAlloc(0, exp_id, diff_id, "run", workdir, "dirty", label, dvodb, registered, 0);
     219        magicRunRow *run = magicRunRowAlloc(0, exp_id, diff_id, "new", workdir, "dirty", label, dvodb, registered, 0);
    220220        if (!run) {
    221221            psAbort("failed to alloc magicRun object");
     
    538538
    539539    if (code > 0) {
    540         char *query = "UPDATE magicRun SET fault = %d, state = 'stop' WHERE magic_id = %" PRId64;
     540        char *query = "UPDATE magicRun SET fault = %d, state = 'full' WHERE magic_id = %" PRId64;
    541541        if (!p_psDBRunQueryF(config->dbh, query, code, magic_id)) {
    542542            psError(PS_ERR_UNKNOWN, false,
     
    10881088    }
    10891089
    1090     // Set to "run"
     1090    // Set to "new"
    10911091    {
    10921092        psString query = psStringCopy("UPDATE magicRun JOIN magicMask USING(magic_id) "
    1093                                       "SET magicRun.state = 'run' WHERE magicMask.fault != 0");
     1093                                      "SET magicRun.state = 'new' WHERE magicMask.fault != 0");
    10941094
    10951095        if (psListLength(where->list)) {
     
    14811481    // check that state is a valid string value
    14821482    if (!(
    1483             (strncmp(state, "run", 4) == 0)
    1484             || (strncmp(state, "stop", 5) == 0)
     1483            (strncmp(state, "new", 4) == 0)
     1484            || (strncmp(state, "full", 5) == 0)
    14851485            || (strncmp(state, "reg", 4) == 0)
    14861486        )
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/pxcam.c

    r21402 r23594  
    4242    psMetadataAddStr(md,  PS_LIST_TAIL, "-comment",            0, "search by comment", NULL);
    4343    psMetadataAddStr(md,  PS_LIST_TAIL, "-filelevel",          0, "search by filelevel", NULL);
    44     psMetadataAddStr(md,  PS_LIST_TAIL, "-reduction",          0, "search by reduction class", NULL);
    4544    psMetadataAddStr(md,  PS_LIST_TAIL, "-filter",             0, "search for filter", NULL);
    4645    psMetadataAddF64(md,  PS_LIST_TAIL, "-airmass_min",        0, "define min airmass", NAN);
     
    7776bool pxcamGetSearchArgs (pxConfig *config, psMetadata *where) {
    7877
    79     PXOPT_COPY_S64(config->args, where, "-chip_id", "chip_id", "==");
    80     PXOPT_COPY_S64(config->args, where, "-exp_id", "rawExp.exp_id", "==");
    81     PXOPT_COPY_STR(config->args, where, "-exp_name", "exp_name", "==");
    82     PXOPT_COPY_STR(config->args, where, "-inst", "camera", "==");
    83     PXOPT_COPY_STR(config->args, where, "-telescope", "telescope", "==");
    84     PXOPT_COPY_TIME(config->args, where, "-dateobs_begin", "dateobs", ">=");
    85     PXOPT_COPY_TIME(config->args, where, "-dateobs_end", "dateobs", "<=");
    86     PXOPT_COPY_STR(config->args, where, "-exp_tag", "exp_tag", "==");
    87     PXOPT_COPY_STR(config->args, where, "-exp_type", "exp_type", "==");
    88     PXOPT_COPY_STR(config->args, where, "-comment", "rawExp.comment", "LIKE");
    89     PXOPT_COPY_STR(config->args, where, "-filelevel", "filelevel", "==");
    90     PXOPT_COPY_STR(config->args, where, "-reduction", "reduction", "==");
    91     PXOPT_COPY_STR(config->args, where, "-filter", "filter", "==");
    92     PXOPT_COPY_F64(config->args, where, "-airmass_min", "airmass", ">=");
    93     PXOPT_COPY_F64(config->args, where, "-airmass_max", "airmass", "<");
    94     PXOPT_COPY_F64(config->args, where, "-ra_min", "ra", ">=");
    95     PXOPT_COPY_F64(config->args, where, "-ra_max", "ra", "<");
    96     PXOPT_COPY_F64(config->args, where, "-decl_min", "decl", ">=");
    97     PXOPT_COPY_F64(config->args, where, "-decl_max", "decl", "<");
    98     PXOPT_COPY_F32(config->args, where, "-exp_time_min", "exp_time", ">=");
    99     PXOPT_COPY_F32(config->args, where, "-exp_time_max", "exp_time", "<");
    100     PXOPT_COPY_F32(config->args, where, "-sat_pixel_frac_min", "sat_pixel_frac", ">=");
    101     PXOPT_COPY_F32(config->args, where, "-sat_pixel_frac_max", "sat_pixel_frac", "<");
    102     PXOPT_COPY_F64(config->args, where, "-bg_min", "bt", ">=");
    103     PXOPT_COPY_F64(config->args, where, "-bg_max", "bt", "<");
    104     PXOPT_COPY_F64(config->args, where, "-bg_stdev_min", "bg_stdev", ">=");
    105     PXOPT_COPY_F64(config->args, where, "-bg_stdev_max", "bg_stdev", "<");
    106     PXOPT_COPY_F64(config->args, where, "-bg_mean_stdev_min", "bg_mean_stdev", ">=");
    107     PXOPT_COPY_F64(config->args, where, "-bg_mean_stdev_max", "bg_mean_stdev", "<");
    108     PXOPT_COPY_F64(config->args, where, "-alt_min", "alt", ">=");
    109     PXOPT_COPY_F64(config->args, where, "-alt_max", "alt", "<");
    110     PXOPT_COPY_F64(config->args, where, "-az_min", "az", ">=");
    111     PXOPT_COPY_F64(config->args, where, "-az_max", "az", "<");
    112     PXOPT_COPY_F32(config->args, where, "-ccd_temp_min", "ccd_temp", ">=");
    113     PXOPT_COPY_F32(config->args, where, "-ccd_temp_max", "ccd_temp", "<");
    114     PXOPT_COPY_F64(config->args, where, "-posang_min", "posang", ">=");
    115     PXOPT_COPY_F64(config->args, where, "-posang_max", "posang", "<");
    116     PXOPT_COPY_STR(config->args, where, "-object", "object", "==");
    117     PXOPT_COPY_F32(config->args, where, "-solang_min", "solang", ">=");
    118     PXOPT_COPY_F32(config->args, where, "-solang_max", "solang", "<");
     78    PXOPT_COPY_S64(config->args,  where, "-chip_id",            "chipRun.chip_id",       "==");
     79    PXOPT_COPY_S64(config->args,  where, "-exp_id",             "rawExp.exp_id",         "==");
     80    PXOPT_COPY_STR(config->args,  where, "-exp_name",           "rawExp.exp_name",       "==");
     81    PXOPT_COPY_STR(config->args,  where, "-inst",               "rawExp.camera",         "==");
     82    PXOPT_COPY_STR(config->args,  where, "-telescope",          "rawExp.telescope",      "==");
     83    PXOPT_COPY_TIME(config->args, where, "-dateobs_begin",      "rawExp.dateobs",        ">=");
     84    PXOPT_COPY_TIME(config->args, where, "-dateobs_end",        "rawExp.dateobs",        "<=");
     85    PXOPT_COPY_STR(config->args,  where, "-exp_tag",            "rawExp.exp_tag",        "==");
     86    PXOPT_COPY_STR(config->args,  where, "-exp_type",           "rawExp.exp_type",       "==");
     87    PXOPT_COPY_STR(config->args,  where, "-comment",            "rawExp.comment",        "LIKE");
     88    PXOPT_COPY_STR(config->args,  where, "-filelevel",          "rawExp.filelevel",      "==");
     89    PXOPT_COPY_STR(config->args,  where, "-filter",             "rawExp.filter",         "==");
     90    PXOPT_COPY_F64(config->args,  where, "-airmass_min",        "rawExp.airmass",        ">=");
     91    PXOPT_COPY_F64(config->args,  where, "-airmass_max",        "rawExp.airmass",        "<");
     92    PXOPT_COPY_F64(config->args,  where, "-ra_min",             "rawExp.ra",             ">=");
     93    PXOPT_COPY_F64(config->args,  where, "-ra_max",             "rawExp.ra",             "<");
     94    PXOPT_COPY_F64(config->args,  where, "-decl_min",           "rawExp.decl",           ">=");
     95    PXOPT_COPY_F64(config->args,  where, "-decl_max",           "rawExp.decl",           "<");
     96    PXOPT_COPY_F32(config->args,  where, "-exp_time_min",       "rawExp.exp_time",       ">=");
     97    PXOPT_COPY_F32(config->args,  where, "-exp_time_max",       "rawExp.exp_time",       "<");
     98    PXOPT_COPY_F32(config->args,  where, "-sat_pixel_frac_min", "rawExp.sat_pixel_frac", ">=");
     99    PXOPT_COPY_F32(config->args,  where, "-sat_pixel_frac_max", "rawExp.sat_pixel_frac", "<");
     100    PXOPT_COPY_F64(config->args,  where, "-bg_min",             "rawExp.bg",             ">=");
     101    PXOPT_COPY_F64(config->args,  where, "-bg_max",             "rawExp.bg",             "<");
     102    PXOPT_COPY_F64(config->args,  where, "-bg_stdev_min",       "rawExp.bg_stdev",       ">=");
     103    PXOPT_COPY_F64(config->args,  where, "-bg_stdev_max",       "rawExp.bg_stdev",       "<");
     104    PXOPT_COPY_F64(config->args,  where, "-bg_mean_stdev_min",  "rawExp.bg_mean_stdev",  ">=");
     105    PXOPT_COPY_F64(config->args,  where, "-bg_mean_stdev_max",  "rawExp.bg_mean_stdev",  "<");
     106    PXOPT_COPY_F64(config->args,  where, "-alt_min",            "rawExp.alt",            ">=");
     107    PXOPT_COPY_F64(config->args,  where, "-alt_max",            "rawExp.alt",            "<");
     108    PXOPT_COPY_F64(config->args,  where, "-az_min",             "rawExp.az",             ">=");
     109    PXOPT_COPY_F64(config->args,  where, "-az_max",             "rawExp.az",             "<");
     110    PXOPT_COPY_F32(config->args,  where, "-ccd_temp_min",       "rawExp.ccd_temp",       ">=");
     111    PXOPT_COPY_F32(config->args,  where, "-ccd_temp_max",       "rawExp.ccd_temp",       "<");
     112    PXOPT_COPY_F64(config->args,  where, "-posang_min",         "rawExp.posang",         ">=");
     113    PXOPT_COPY_F64(config->args,  where, "-posang_max",         "rawExp.posang",         "<");
     114    PXOPT_COPY_STR(config->args,  where, "-object",             "rawExp.object",         "==");
     115    PXOPT_COPY_F32(config->args,  where, "-solang_min",         "rawExp.solang",         ">=");
     116    PXOPT_COPY_F32(config->args,  where, "-solang_max",         "rawExp.solang",         "<");
    119117
    120118    return true;
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/pxchip.c

    r21402 r23594  
    3131bool pxchipSetSearchArgs (psMetadata *md) {
    3232
     33    // psMetadataAddStr(md,  PS_LIST_TAIL, "-class_id",           0, "search by class ID", NULL);
     34    // psMetadataAddStr(md,  PS_LIST_TAIL, "-reduction",          0, "search by reduction class", NULL);
     35
    3336    // XXX need to allow multiple exp_ids
    3437    psMetadataAddS64(md,  PS_LIST_TAIL, "-exp_id",             0, "search by exp_id", 0);
    3538    psMetadataAddStr(md,  PS_LIST_TAIL, "-exp_name",           0, "search by exp_name", NULL);
    36     // psMetadataAddStr(md,  PS_LIST_TAIL, "-class_id",           0, "search by class ID", NULL);
    3739    psMetadataAddStr(md,  PS_LIST_TAIL, "-inst",               0, "search for camera", NULL);
    3840    psMetadataAddStr(md,  PS_LIST_TAIL, "-telescope",          0, "search for telescope", NULL);
     
    4244    psMetadataAddStr(md,  PS_LIST_TAIL, "-exp_type",           0, "search by exp_type", NULL);
    4345    psMetadataAddStr(md,  PS_LIST_TAIL, "-filelevel",          0, "search by filelevel", NULL);
    44     // psMetadataAddStr(md,  PS_LIST_TAIL, "-reduction",          0, "search by reduction class", NULL);
    4546    psMetadataAddStr(md,  PS_LIST_TAIL, "-filter",             0, "search for filter", NULL);
    4647    psMetadataAddF32(md,  PS_LIST_TAIL, "-airmass_min",        0, "search by min airmass", NAN);
     
    128129}
    129130
    130 bool pxchipRunSetState(pxConfig *config, psS64 chip_id, const char *state)
     131bool pxchipRunSetState(pxConfig *config, psS64 chip_id, const char *state, const bool magicked)
    131132{
    132133    PS_ASSERT_PTR_NON_NULL(config, false);
     
    139140    }
    140141
    141     char *query = "UPDATE chipRun SET state = '%s' WHERE chip_id = %" PRId64;
    142     if (!p_psDBRunQueryF(config->dbh, query, state, chip_id)) {
     142    char *query = "UPDATE chipRun SET state = '%s', magicked = %d WHERE chip_id = %" PRId64;
     143    if (!p_psDBRunQueryF(config->dbh, query, state, magicked, chip_id)) {
    143144        psError(PS_ERR_UNKNOWN, false,
    144145                "failed to change state for chip_id %" PRId64, chip_id);
     
    158159    if (!pxIsValidState(state)) {
    159160        psError(PS_ERR_UNKNOWN, false, "invalid chipRun state: %s", state);
     161        return false;
     162    }
     163
     164    if (!strcmp(state, "full")) {
     165        // There are states that need to be met for a run to be set to full that we don't
     166        // check here.
     167        // for example all of the run's Imfiles must have chipProcessedImfile.data_state == "full"
     168        // chipRun.magicked = (SUM(!chipProcessedImfile.magicked) = 0)
     169        // so don't do allow setting the state to full
     170        psError(PS_ERR_UNKNOWN, true, "cannot use -updaterun so set chipRun state to full");
    160171        return false;
    161172    }
     
    253264            dvodb,
    254265            tess_id,
    255             end_stage)
     266            end_stage,
     267            0           // magicked
     268            )
    256269    ) {
    257270        if (!psDBRollback(config->dbh)) {
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/pxchip.h

    r19324 r23594  
    2525#include "pxtools.h"
    2626
    27 bool pxchipRunSetState(pxConfig *config, psS64 chip_id, const char *state);
     27bool pxchipRunSetState(pxConfig *config, psS64 chip_id, const char *state, const bool magicked);
    2828bool pxchipRunSetStateByQuery(pxConfig *config, psMetadata *where, const char *state);
    2929bool pxchipRunSetLabel(pxConfig *config, psS64 chip_id, const char *label);
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/pxerrors.c

    r17611 r23594  
    2424#include "pxtools.h"
    2525
    26 psExit pxerrorGetExitStatus () {
     26psExit pxerrorGetExitStatus(void) {
    2727
    2828    psErrorCode err = psErrorCodeLast ();
     
    3838      default:
    3939    return PS_EXIT_UNKNOWN_ERROR;
    40     }   
     40    }
    4141    return PS_EXIT_UNKNOWN_ERROR;
    4242}
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/pxtools.h

    r18561 r23594  
    5353bool pxSetFaultCode(psDB *dbh, const char *tableName, psMetadata *where, psS16 code);
    5454
    55 psExit pxerrorGetExitStatus ();
     55psExit pxerrorGetExitStatus(void);
    5656
    5757void pxUsage(FILE *stream, int argc, char **argv, const char *modeName, psMetadata *argSet);
     
    303303#define PXOPT_ADD_WHERE_BOOL(name) \
    304304{ \
    305     bool value = false;  \
     305    bool value = false;  \
    306306    bool status = false; \
    307307    if ((value = psMetadataLookupBool(&status, config->args, "-" #name))) { \
     
    370370}
    371371
    372 #define PXOPT_ADD_WHERE_BOOL_ALIAS(flag,name)   \
     372#define PXOPT_ADD_WHERE_BOOL_ALIAS(flag,name)   \
    373373{ \
    374374    bool value = 0; \
    375375    bool status = false; \
    376     if ((value = psMetadataLookupBool(&status, config->args, flag))) {  \
     376    if ((value = psMetadataLookupBool(&status, config->args, flag))) {  \
    377377        if (!psMetadataAddBOOL(config->where, PS_LIST_TAIL, name, 0, "==", value)) { \
    378378            psError(PS_ERR_UNKNOWN, false, "failed to add item %s", flag); \
     
    383383}
    384384
    385 #define PXOPT_ADD_WHERE_S16_ALIAS(flag,name)    \
     385#define PXOPT_ADD_WHERE_S16_ALIAS(flag,name)    \
    386386{ \
    387387    psS16 s16 = 0; \
    388388    bool status = false; \
    389     if ((s16= psMetadataLookupS16(&status, config->args, flag))) {      \
     389    if ((s16= psMetadataLookupS16(&status, config->args, flag))) {      \
    390390        if (!psMetadataAddS16(config->where, PS_LIST_TAIL, name, 0, "==", s16)) { \
    391391            psError(PS_ERR_UNKNOWN, false, "failed to add item %s", flag); \
     
    396396}
    397397
    398 #define PXOPT_ADD_WHERE_S32_ALIAS(flag,name)    \
     398#define PXOPT_ADD_WHERE_S32_ALIAS(flag,name)    \
    399399{ \
    400400    psS32 s32 = 0; \
    401401    bool status = false; \
    402     if ((s32= psMetadataLookupS32(&status, config->args, flag))) {      \
     402    if ((s32= psMetadataLookupS32(&status, config->args, flag))) {      \
    403403        if (!psMetadataAddS32(config->where, PS_LIST_TAIL, name, 0, "==", s32)) { \
    404404            psError(PS_ERR_UNKNOWN, false, "failed to add item %s", flag); \
     
    409409}
    410410
    411 #define PXOPT_ADD_WHERE_S64_ALIAS(flag,name)    \
     411#define PXOPT_ADD_WHERE_S64_ALIAS(flag,name)    \
    412412{ \
    413413    psS64 s64 = 0; \
    414414    bool status = false; \
    415     if ((s64= psMetadataLookupS64(&status, config->args, flag))) {      \
     415    if ((s64= psMetadataLookupS64(&status, config->args, flag))) {      \
    416416        if (!psMetadataAddS64(config->where, PS_LIST_TAIL, name, 0, "==", s64)) { \
    417417            psError(PS_ERR_UNKNOWN, false, "failed to add item %s", flag); \
     
    422422}
    423423
    424 #define PXOPT_ADD_WHERE_F32_ALIAS(flag,name)    \
     424#define PXOPT_ADD_WHERE_F32_ALIAS(flag,name)    \
    425425{ \
    426426    psF32 var = 0; \
    427427    bool status = false; \
    428     if ((var = psMetadataLookupF32(&status, config->args, flag))) {     \
     428    if ((var = psMetadataLookupF32(&status, config->args, flag))) {     \
    429429        if (!isnan(var))  { \
    430430            if (!psMetadataAddF32(config->where, PS_LIST_TAIL, name, 0, "==", var)) { \
     
    437437}
    438438
    439 #define PXOPT_ADD_WHERE_F64_ALIAS(flag,name)    \
     439#define PXOPT_ADD_WHERE_F64_ALIAS(flag,name)    \
    440440{ \
    441441    psF64 var = 0; \
    442442    bool status = false; \
    443     if ((var = psMetadataLookupF64(&status, config->args, flag))) {     \
     443    if ((var = psMetadataLookupF64(&status, config->args, flag))) {     \
    444444        if (!isnan(var))  { \
    445445            if (!psMetadataAddF64(config->where, PS_LIST_TAIL, name, 0, "==", var)) { \
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/pxwarp.c

    r23352 r23594  
    2828#include "pxtools.h"
    2929#include "pxwarp.h"
     30
     31bool pxwarpSetSearchArgs (psMetadata *md) {
     32    psMetadataAddS64(md, PS_LIST_TAIL, "-fake_id",            0, "search by fake_id", 0);
     33    psMetadataAddS64(md, PS_LIST_TAIL, "-cam_id",             0, "search by cam_id", 0);
     34    psMetadataAddS64(md, PS_LIST_TAIL, "-chip_id",            0, "search by chip_id", 0);
     35    psMetadataAddS64(md, PS_LIST_TAIL, "-exp_id",             0, "search by exp_id", 0);
     36    psMetadataAddStr(md, PS_LIST_TAIL, "-exp_name",           0, "search by exp_name", NULL);
     37    psMetadataAddStr(md, PS_LIST_TAIL, "-inst",               0, "search for camera", NULL);
     38    psMetadataAddStr(md, PS_LIST_TAIL, "-telescope",          0, "search for telescope", NULL);
     39    psMetadataAddTime(md, PS_LIST_TAIL, "-dateobs_begin",     0, "search for exposures by time (>=)", NULL);
     40    psMetadataAddTime(md, PS_LIST_TAIL, "-dateobs_end",       0, "search for exposures by time (<)", NULL);
     41    psMetadataAddStr(md, PS_LIST_TAIL, "-exp_tag",            0, "search by exp_tag", NULL);
     42    psMetadataAddStr(md, PS_LIST_TAIL, "-exp_type",           0, "search by exp_type", NULL);
     43    psMetadataAddStr(md, PS_LIST_TAIL, "-filelevel",          0, "search by filelevel", NULL);
     44    psMetadataAddStr(md, PS_LIST_TAIL, "-filter",             0, "search for filter", NULL);
     45    psMetadataAddF64(md, PS_LIST_TAIL, "-airmass_min",        0, "search by min airmass", NAN);
     46    psMetadataAddF64(md, PS_LIST_TAIL, "-airmass_max",        0, "search by max airmass", NAN);
     47    psMetadataAddF64(md, PS_LIST_TAIL, "-ra_min",             0, "search by min", NAN);
     48    psMetadataAddF64(md, PS_LIST_TAIL, "-ra_max",             0, "search by max", NAN);
     49    psMetadataAddF64(md, PS_LIST_TAIL, "-decl_min",           0, "search by min", NAN);
     50    psMetadataAddF64(md, PS_LIST_TAIL, "-decl_max",           0, "search by max", NAN);
     51    psMetadataAddF32(md, PS_LIST_TAIL, "-exp_time_min",       0, "search by min", NAN);
     52    psMetadataAddF32(md, PS_LIST_TAIL, "-exp_time_max",       0, "search by max", NAN);
     53    psMetadataAddF32(md, PS_LIST_TAIL, "-sat_pixel_frac_min", 0, "search by max fraction of saturated pixels", NAN);
     54    psMetadataAddF32(md, PS_LIST_TAIL, "-sat_pixel_frac_max", 0, "search by min fraction of saturated pixels", NAN);
     55    psMetadataAddF64(md, PS_LIST_TAIL, "-bg_min",             0, "search by max", NAN);
     56    psMetadataAddF64(md, PS_LIST_TAIL, "-bg_max",             0, "search by max", NAN);
     57    psMetadataAddF64(md, PS_LIST_TAIL, "-bg_stdev_min",       0, "search by max", NAN);
     58    psMetadataAddF64(md, PS_LIST_TAIL, "-bg_stdev_max",       0, "search by max", NAN);
     59    psMetadataAddF64(md, PS_LIST_TAIL, "-bg_mean_stdev_min",  0, "search by max", NAN);
     60    psMetadataAddF64(md, PS_LIST_TAIL, "-bg_mean_stdev_max",  0, "search by max", NAN);
     61    psMetadataAddF64(md, PS_LIST_TAIL, "-alt_min",            0, "search by min", NAN);
     62    psMetadataAddF64(md, PS_LIST_TAIL, "-alt_max",            0, "search by max", NAN);
     63    psMetadataAddF64(md, PS_LIST_TAIL, "-az_min",             0, "search by min", NAN);
     64    psMetadataAddF64(md, PS_LIST_TAIL, "-az_max",             0, "search by max", NAN);
     65    psMetadataAddF32(md, PS_LIST_TAIL, "-ccd_temp_min",       0, "search by min ccd tempature", NAN);
     66    psMetadataAddF32(md, PS_LIST_TAIL, "-ccd_temp_max",       0, "search by max ccd tempature", NAN);
     67    psMetadataAddF64(md, PS_LIST_TAIL, "-posang_min",         0, "search by min rotator position angle", NAN);
     68    psMetadataAddF64(md, PS_LIST_TAIL, "-posang_max",         0, "search by max rotator position angle", NAN);
     69    psMetadataAddStr(md, PS_LIST_TAIL, "-object",             0, "search by exposure object", NULL);
     70    psMetadataAddF32(md, PS_LIST_TAIL, "-solang_min",         0, "search by min solar angle", NAN);
     71    psMetadataAddF32(md, PS_LIST_TAIL, "-solang_max",         0, "search by max solar angle", NAN);
     72    return true;
     73}
     74
     75bool pxwarpGetSearchArgs (pxConfig *config, psMetadata *where) {
     76    PXOPT_COPY_S64(config->args, where, "-fake_id",            "fakeRun.fake_id",       "==");
     77    PXOPT_COPY_S64(config->args, where, "-cam_id",             "camRun.cam_id",         "==");
     78    PXOPT_COPY_S64(config->args, where, "-chip_id",            "chipRun.chip_id",       "==");
     79    PXOPT_COPY_S64(config->args, where, "-exp_id",             "newExp.exp_id",         "==");
     80    PXOPT_COPY_STR(config->args, where, "-exp_name",           "rawExp.exp_name",       "==");
     81    PXOPT_COPY_STR(config->args, where, "-inst",               "rawExp.camera",         "==");
     82    PXOPT_COPY_STR(config->args, where, "-telescope",          "rawExp.telescope",      "==");
     83    PXOPT_COPY_TIME(config->args, where, "-dateobs_begin",     "rawExp.dateobs",        ">=");
     84    PXOPT_COPY_TIME(config->args, where, "-dateobs_end",       "rawExp.dateobs",        "<=");
     85    PXOPT_COPY_STR(config->args, where, "-exp_tag",            "rawExp.exp_tag",        "==");
     86    PXOPT_COPY_STR(config->args, where, "-exp_type",           "rawExp.exp_type",       "==");
     87    PXOPT_COPY_STR(config->args, where, "-filelevel",          "rawExp.filelevel",      "==");
     88    PXOPT_COPY_STR(config->args, where, "-filter",             "rawExp.filter",         "==");
     89    PXOPT_COPY_F64(config->args, where, "-airmass_min",        "rawExp.airmass",        ">=");
     90    PXOPT_COPY_F64(config->args, where, "-airmass_max",        "rawExp.airmass",        "<");
     91    PXOPT_COPY_F64(config->args, where, "-ra_min",             "rawExp.ra",             ">=");
     92    PXOPT_COPY_F64(config->args, where, "-ra_max",             "rawExp.ra",             "<");
     93    PXOPT_COPY_F64(config->args, where, "-decl_min",           "rawExp.decl",           ">=");
     94    PXOPT_COPY_F64(config->args, where, "-decl_max",           "rawExp.decl",           "<");
     95    PXOPT_COPY_F32(config->args, where, "-exp_time_min",       "rawExp.exp_time",       ">=");
     96    PXOPT_COPY_F32(config->args, where, "-exp_time_max",       "rawExp.exp_time",       "<");
     97    PXOPT_COPY_F32(config->args, where, "-sat_pixel_frac_min", "rawExp.sat_pixel_frac", ">=");
     98    PXOPT_COPY_F32(config->args, where, "-sat_pixel_frac_max", "rawExp.sat_pixel_frac", "<");
     99    PXOPT_COPY_F64(config->args, where, "-bg_min",             "rawExp.bg",             ">=");
     100    PXOPT_COPY_F64(config->args, where, "-bg_max",             "rawExp.bg",             "<");
     101    PXOPT_COPY_F64(config->args, where, "-bg_stdev_min",       "rawExp.bg_stdev",       ">=");
     102    PXOPT_COPY_F64(config->args, where, "-bg_stdev_max",       "rawExp.bg_stdev",       "<");
     103    PXOPT_COPY_F64(config->args, where, "-bg_mean_stdev_min",  "rawExp.bg_mean_stdev",  ">=");
     104    PXOPT_COPY_F64(config->args, where, "-bg_mean_stdev_max",  "rawExp.bg_mean_stdev",  "<");
     105    PXOPT_COPY_F64(config->args, where, "-alt_min",            "rawExp.alt",            ">=");
     106    PXOPT_COPY_F64(config->args, where, "-alt_max",            "rawExp.alt",            "<");
     107    PXOPT_COPY_F64(config->args, where, "-az_min",             "rawExp.az",             ">=");
     108    PXOPT_COPY_F64(config->args, where, "-az_max",             "rawExp.az",             "<");
     109    PXOPT_COPY_F32(config->args, where, "-ccd_temp_min",       "rawExp.ccd_temp",       ">=");
     110    PXOPT_COPY_F32(config->args, where, "-ccd_temp_max",       "rawExp.ccd_temp",       "<");
     111    PXOPT_COPY_F64(config->args, where, "-posang_min",         "rawExp.posang",         ">=");
     112    PXOPT_COPY_F64(config->args, where, "-posang_max",         "rawExp.posang",         "<");
     113    PXOPT_COPY_STR(config->args, where, "-object",             "rawExp.object",         "==");
     114    PXOPT_COPY_F32(config->args, where, "-solang_min",         "rawExp.solang",         ">=");
     115    PXOPT_COPY_F32(config->args, where, "-solang_max",         "rawExp.solang",         "<");
     116    return true;
     117}
    30118
    31119bool pxwarpRunSetState(pxConfig *config, psS64 warp_id, const char *state)
     
    147235        tess_id,
    148236        end_stage,
    149         NULL       // registered
     237        NULL,      // registered
     238        0          // magicked zero when created will get updated when warpRun goes to 'full'
    150239    )) {
    151240        psError(PS_ERR_UNKNOWN, false, "database error");
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/pxwarp.h

    r18029 r23594  
    2525#include "pxtools.h"
    2626
     27bool pxwarpGetSearchArgs (pxConfig *config, psMetadata *where);
     28bool pxwarpSetSearchArgs (psMetadata *md);
     29
    2730bool pxwarpRunSetState(pxConfig *config, psS64 warp_id, const char *state);
    2831bool pxwarpRunSetStateByQuery(pxConfig *config, psMetadata *where, const char *state);
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/pztool.c

    r21479 r23594  
    4444
    4545static bool clearcommonfaultsMode(pxConfig *config);
     46static bool toadvanceMode(pxConfig *config);
    4647static bool advanceMode(pxConfig *config);
    4748
    48 static bool copydoneCompleteExp(pxConfig *config);
     49// static bool copydoneCompleteExp(pxConfig *config);
    4950static psArray *pzGetPendingCameras(pxConfig *config);
    5051static psArray *pzArrayZip(psArray *arraySet, psS64 limit);
     
    8081        MODECASE(PZTOOL_MODE_REVERTCOPIED, revertcopiedMode);
    8182        MODECASE(PZTOOL_MODE_CLEARCOMMONFAULTS, clearcommonfaultsMode);
     83        MODECASE(PZTOOL_MODE_TOADVANCE, toadvanceMode);
    8284        MODECASE(PZTOOL_MODE_ADVANCE, advanceMode);
    8385        default:
     
    403405    PXOPT_LOOKUP_S16(code, config->args, "-code", false, false);
    404406
    405     // NOTE : the rest of the command-line args are parsed in copydoneCompleteExp
    406 
    407407    // start a transaction early so it will contain any row level locks
    408408    if (!psDBTransaction(config->dbh)) {
     
    463463    }
    464464
    465 #ifdef notdef
    466     // we've changed to use -advance instead
    467     if (!copydoneCompleteExp(config)) {
    468         // rollback
    469         if (!psDBRollback(config->dbh)) {
    470             psError(PS_ERR_UNKNOWN, false, "database error");
    471         }
    472         psError(PS_ERR_UNKNOWN, false, "copydoneCompleteExp() failed");
    473         return false;
    474     }
    475 #endif
    476465    // point of no return
    477466    if (!psDBCommit(config->dbh)) {
     
    487476}
    488477
    489 static bool copydoneCompleteExp(pxConfig *config)
    490 {
    491     // THIS FUNCTION MUST BE INVOKED FROM INSIDE A TRANSACTION!!!
    492    
    493     PS_ASSERT_PTR_NON_NULL(config, false);
    494 
    495     // XXX this is an ugly hack!
    496     // we are passing exp level info to a imfile level mode (-copydone)
    497     // these options are thrown away unless we just -copydone'd the last imfile
    498     // in an exp. 
    499  
    500     // optional
    501     PXOPT_LOOKUP_STR(workdir, config->args, "-workdir", false, false);
    502     PXOPT_LOOKUP_STR(dvodb, config->args, "-dvodb", false, false);
    503     PXOPT_LOOKUP_STR(tess_id, config->args, "-tess_id", false, false);
    504     PXOPT_LOOKUP_STR(end_stage, config->args, "-end_stage", false, false);
    505     PXOPT_LOOKUP_STR(label, config->args, "-label", false, false);
     478static bool toadvanceMode(pxConfig *config)
     479{
     480    PS_ASSERT_PTR_NON_NULL(config, false);
     481
     482    // optional args
     483    PXOPT_LOOKUP_BOOL(simple, config->args, "-simple", false);
    506484    PXOPT_LOOKUP_U64(limit, config->args, "-limit", false, false);
    507485
     
    517495    PXOPT_COPY_STR(config->args, where,  "-exp_name", "exp_name", "==");
    518496    PXOPT_COPY_STR(config->args, where,  "-inst", "camera", "==");
    519     PXOPT_COPY_STR(config->args, where,  "-telescope", "telescope", "==");
     497    PXOPT_COPY_STR(config->args, where,  "-inst", "camera", "==");
     498    PXOPT_COPY_STR(config->args, where,  "-label", "label", "==");
    520499
    521500    if (psListLength(where->list)) {
     
    525504    }
    526505    psFree(where);
     506
    527507
    528508    // treat limit == 0 as "no limit"
     
    552532    }
    553533
    554    for (long i = 0; i < psArrayLength(output); i++) {
    555         psMetadata *row = output->data[i];
    556 
    557         pzDownloadExpRow *doneExp = pzDownloadExpObjectFromMetadata(row);
    558         if (!doneExp) {
    559             psError(PS_ERR_UNKNOWN, false, "pzDownloadExpObjectFromMetadata() failed");
    560             psFree(doneExp);
    561             psFree(output);
    562             return false;
    563         }
    564 
    565         if (!newExpInsert(config->dbh,
    566                     0x0,                // exp_id
    567                     doneExp->exp_name,  // tmp_exp_name
    568                     doneExp->camera,    // tmp_camera
    569                     doneExp->telescope, // tmp_telescope
    570                     "run",              // state
    571                     workdir,            // workdir
    572                     "dirty",            // workdir state
    573                     NULL,               // reduction class
    574                     dvodb,              // dvodb
    575                     tess_id,            // tess_id
    576                     end_stage,          // end_stage
    577                     label,
    578                     NULL                // epoch
    579                 )
     534    if (!ippdbPrintMetadatas(stdout, output, "toadvance", !simple)) {
     535        psError(PS_ERR_UNKNOWN, false, "failed to print array");
     536        psFree(output);
     537        return false;
     538    }
     539
     540    psFree(output);
     541
     542    return true;
     543}
     544
     545static bool advanceMode(pxConfig *config)
     546{
     547    PS_ASSERT_PTR_NON_NULL(config, false);
     548
     549    // required
     550    PXOPT_LOOKUP_STR(exp_name, config->args, "-exp_name", true, false);
     551    PXOPT_LOOKUP_STR(inst, config->args, "-inst", true, false);
     552    PXOPT_LOOKUP_STR(telescope, config->args, "-telescope", true, false);
     553    PXOPT_LOOKUP_STR(workdir, config->args, "-workdir", true, false);
     554
     555    // optional
     556    PXOPT_LOOKUP_STR(dvodb, config->args, "-dvodb", false, false);
     557    PXOPT_LOOKUP_STR(tess_id, config->args, "-tess_id", false, false);
     558    PXOPT_LOOKUP_STR(end_stage, config->args, "-end_stage", false, false);
     559    PXOPT_LOOKUP_STR(label, config->args, "-label", false, false);
     560
     561    // start a transaction so it's all rows or nothing
     562    if (!psDBTransaction(config->dbh)) {
     563        psError(PS_ERR_UNKNOWN, false, "database error");
     564        return false;
     565    }
     566
     567    if (!newExpInsert(config->dbh,
     568            0x0,        // exp_id
     569            exp_name,   // tmp_exp_name
     570            inst,       // tmp_camera
     571            telescope,  // tmp_telescope
     572            "run",      // state
     573            workdir,    // workdir
     574            "dirty",    // workdir state
     575            NULL,       // reduction class
     576            dvodb,      // dvodb
     577            tess_id,    // tess_id
     578            end_stage,  // end_stage
     579            label,      // label
     580            NULL        // epoch
     581            )
    580582        ) {
    581583            psError(PS_ERR_UNKNOWN, false, "database error");
    582             psFree(doneExp);
    583             psFree(output);
    584584            return false;
    585585        }
     
    592592                "INSERT INTO newImfile"
    593593                "   SElECT"
    594                 "       %" PRId64 "," // exp_id
     594                "       %" PRId64 ","               // exp_id
    595595                "       pzDownloadImfile.class_id," // tmp_class_id
    596                 "       pzDownloadImfile.uri," // uri
    597                 "       NULL" // epoch
     596                "       pzDownloadImfile.uri,"      // uri
     597                "       NULL"                       // epoch
    598598                "   FROM pzDownloadImfile"
    599599                "   WHERE"
     
    602602                "       AND pzDownloadImfile.telescope = '%s'";
    603603
    604             if (!p_psDBRunQueryF(config->dbh, query, exp_id, doneExp->exp_name, doneExp->camera, doneExp->telescope)) {
    605                 psError(PS_ERR_UNKNOWN, false, "database error");
    606                 psFree(doneExp);
    607                 psFree(output);
    608                 return false;
    609             }
    610 
    611             // sanity check: we should have inserted at least one row
    612             psU64 affected = psDBAffectedRows(config->dbh);
    613             if (psDBAffectedRows(config->dbh) < 1) {
    614                 psError(PS_ERR_UNKNOWN, false, "should have affected at least 1 row but %" PRIu64 " rows were modified", affected);
    615                 psFree(doneExp);
    616                 psFree(output);
    617                 return false;
    618             }
    619         }
    620 
    621         // set pzDownloadExp.state to 'stop'
    622         if (!pzDownloadExpSetState(config, doneExp->exp_name, doneExp->camera, doneExp->telescope, "stop")) {
    623             psError(PS_ERR_UNKNOWN, false, "failed to change pzDownloadExp.state for %s:%s:%s", doneExp->exp_name, doneExp->camera, doneExp->telescope);
    624             psFree(doneExp);
    625             psFree(output);
     604        if (!p_psDBRunQueryF(config->dbh, query, exp_id, exp_name, inst, telescope)) {
     605            psError(PS_ERR_UNKNOWN, false, "database error");
    626606            return false;
    627         }
    628 
    629         psFree(doneExp);
    630     }
    631 
    632     psFree(output);
     607        }
     608
     609        // sanity check: we should have inserted at least one row
     610        psU64 affected = psDBAffectedRows(config->dbh);
     611        if (psDBAffectedRows(config->dbh) < 1) {
     612            psError(PS_ERR_UNKNOWN, false, "should have affected at least 1 row but %" PRIu64 " rows were modified", affected);
     613            return false;
     614        }
     615    }
     616
     617    // set pzDownloadExp.state to 'stop'
     618    if (!pzDownloadExpSetState(config, exp_name, inst, telescope, "stop")) {
     619        psError(PS_ERR_UNKNOWN, false, "failed to change pzDownloadExp.state for %s:%s:%s", exp_name, inst, telescope);
     620        return false;
     621    }
     622
     623    // point of no return
     624    if (!psDBCommit(config->dbh)) {
     625        // rollback
     626        if (!psDBRollback(config->dbh)) {
     627            psError(PS_ERR_UNKNOWN, false, "database error");
     628        }
     629        psError(PS_ERR_UNKNOWN, false, "database error");
     630        return false;
     631    }
     632
    633633
    634634    return true;
     
    872872}
    873873
    874 static bool advanceMode(pxConfig *config)
    875 {
    876     PS_ASSERT_PTR_NON_NULL(config, false);
    877 
    878     // NOTE : the command-line args are parsed in copydoneCompleteExp
    879 
    880     // start a transaction so it's all rows or nothing
    881     if (!psDBTransaction(config->dbh)) {
    882         psError(PS_ERR_UNKNOWN, false, "database error");
    883         return false;
    884     }
    885 
    886     if (!copydoneCompleteExp(config)) {
    887         // rollback
    888         if (!psDBRollback(config->dbh)) {
    889             psError(PS_ERR_UNKNOWN, false, "database error");
    890         }
    891         psError(PS_ERR_UNKNOWN, false, "copydoneCompleteExp() failed");
    892         return false;
    893     }
    894 
    895     // point of no return
    896     if (!psDBCommit(config->dbh)) {
    897         // rollback
    898         if (!psDBRollback(config->dbh)) {
    899             psError(PS_ERR_UNKNOWN, false, "database error");
    900         }
    901         psError(PS_ERR_UNKNOWN, false, "database error");
    902         return false;
    903     }
    904 
    905 
    906     return true;
    907 }
    908 
    909874
    910875static bool pzDownloadExpSetState(pxConfig *config, const char *exp_name, const char *camera, const char *telescope, const char *state)
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/pztool.h

    r18314 r23594  
    3535    PZTOOL_MODE_REVERTCOPIED,
    3636    PZTOOL_MODE_CLEARCOMMONFAULTS,
     37    PZTOOL_MODE_TOADVANCE,
    3738    PZTOOL_MODE_ADVANCE
    3839} pztoolMode;
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/pztoolConfig.c

    r21479 r23594  
    9797    psMetadataAddS16(copydoneArgs, PS_LIST_TAIL, "-code",  0,            "set fault code", 0);
    9898    psMetadataAddBool(copydoneArgs, PS_LIST_TAIL, "-row_lock", 0,     "lock pzDownImfile rows while advancing an exposure", false);
     99    // XXX: remove this once advance is fixed
     100    psMetadataAddU64(copydoneArgs, PS_LIST_TAIL, "-limit",  0,            "limit result set to N items", 0);
    99101
    100102    // -copied
     
    129131    // -clearcommonfaults
    130132    psMetadata *clearcommonfaultsArgs = psMetadataAlloc();
     133    //
     134    // -toadvance
     135    psMetadata *toadvanceArgs = psMetadataAlloc();
     136    psMetadataAddStr(toadvanceArgs, PS_LIST_TAIL, "-exp_name", 0,      "define exposure ID", NULL);
     137    psMetadataAddStr(toadvanceArgs, PS_LIST_TAIL, "-inst", 0,          "define camera ID", NULL);
     138    psMetadataAddStr(toadvanceArgs, PS_LIST_TAIL, "-telescope", 0,     "define telescope ID", NULL);
     139    psMetadataAddStr(toadvanceArgs, PS_LIST_TAIL, "-label",  0,        "define the label for the chip stage", NULL);
     140    psMetadataAddBool(toadvanceArgs, PS_LIST_TAIL, "-simple",  0,      "use the simple output format", false);
     141    psMetadataAddU64(toadvanceArgs, PS_LIST_TAIL, "-limit",  0,        "limit result set to N items", 0);
    131142
    132143    // -advance
    133144    psMetadata *advanceArgs = psMetadataAlloc();
    134     psMetadataAddStr(advanceArgs, PS_LIST_TAIL, "-exp_name", 0,            "define exposure ID", NULL);
    135     psMetadataAddStr(advanceArgs, PS_LIST_TAIL, "-inst", 0,            "define camera ID", NULL);
    136     psMetadataAddStr(advanceArgs, PS_LIST_TAIL, "-telescope", 0,            "define telescope ID", NULL);
    137     psMetadataAddStr(advanceArgs, PS_LIST_TAIL, "-workdir",  0,        "define the \"default\" workdir for this exposure", NULL);
    138     psMetadataAddStr(advanceArgs, PS_LIST_TAIL, "-dvodb",  0,        "define the dvodb for the next processing step", NULL);
    139     psMetadataAddStr(advanceArgs, PS_LIST_TAIL, "-tess_id",  0,        "define the tess_id for the next processing step", NULL);
    140     psMetadataAddStr(advanceArgs, PS_LIST_TAIL, "-end_stage",  0,        "define the end goal processing step", NULL);
    141     psMetadataAddStr(advanceArgs, PS_LIST_TAIL, "-label",  0,        "define the label for the chip stage", NULL);
    142     psMetadataAddU64(advanceArgs, PS_LIST_TAIL, "-limit",  0,         "limit result set to N items", 0);
     145    psMetadataAddStr(advanceArgs, PS_LIST_TAIL, "-exp_name", 0,   "define exposure ID (required)", NULL);
     146    psMetadataAddStr(advanceArgs, PS_LIST_TAIL, "-inst", 0,       "define camera ID (required)", NULL);
     147    psMetadataAddStr(advanceArgs, PS_LIST_TAIL, "-telescope", 0,  "define telescope ID (required)", NULL);
     148    psMetadataAddStr(advanceArgs, PS_LIST_TAIL, "-workdir",  0,   "define the \"default\" workdir for this exposure (required)", NULL);
     149    psMetadataAddStr(advanceArgs, PS_LIST_TAIL, "-dvodb",  0,     "define the dvodb for the next processing step", NULL);
     150    psMetadataAddStr(advanceArgs, PS_LIST_TAIL, "-tess_id",  0,   "define the tess_id for the next processing step", NULL);
     151    psMetadataAddStr(advanceArgs, PS_LIST_TAIL, "-end_stage",  0, "define the end goal processing step", NULL);
     152    psMetadataAddStr(advanceArgs, PS_LIST_TAIL, "-label",  0,     "define the label for the chip stage", NULL);
    143153
    144154    psMetadata *argSets = psMetadataAlloc();
     
    155165    PXOPT_ADD_MODE("-revertcopied",    "", PZTOOL_MODE_REVERTCOPIED,revertcopiedArgs);
    156166    PXOPT_ADD_MODE("-clearcommonfaults","", PZTOOL_MODE_CLEARCOMMONFAULTS,clearcommonfaultsArgs);
     167    PXOPT_ADD_MODE("-toadvance",          "", PZTOOL_MODE_TOADVANCE,    toadvanceArgs);
    157168    PXOPT_ADD_MODE("-advance",          "", PZTOOL_MODE_ADVANCE,    advanceArgs);
    158169
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/regtool.c

    r23352 r23594  
    319319
    320320    psMetadata *where = psMetadataAlloc();
    321     PXOPT_COPY_S64(config->args, where,  "-exp_id", "exp_id", "==");
    322     PXOPT_COPY_STR(config->args, where,  "-exp_name", "exp_name", "==");
    323     PXOPT_COPY_STR(config->args, where,  "-class_id", "class_id", "==");
     321    PXOPT_COPY_S64(config->args, where,  "-exp_id",        "exp_id",   "==");
     322    PXOPT_COPY_STR(config->args, where,  "-exp_name",      "exp_name", "==");
     323    PXOPT_COPY_STR(config->args, where,  "-class_id",      "class_id", "==");
     324    PXOPT_COPY_TIME(config->args, where, "-dateobs_begin", "dateobs",  ">=");
     325    PXOPT_COPY_TIME(config->args, where, "-dateobs_end",   "dateobs",  "<=");
    324326
    325327    PXOPT_LOOKUP_U64(limit, config->args, "-limit", false, false);
     
    407409    PXOPT_COPY_STR(config->args, where,  "-class_id",     "class_id", "==");
    408410    PXOPT_COPY_S16(config->args, where,  "-code",         "fault", "==");
     411    PXOPT_COPY_S64(config->args, where,  "-exp_id_begin", "exp_id", ">=");
     412    PXOPT_COPY_S64(config->args, where,  "-exp_id_end", "exp_id", "<=");
    409413
    410414    psString query = pxDataGet("regtool_revertprocessedimfile.sql");
     
    419423        psStringAppend(&query, " AND %s", whereClause);
    420424        psFree(whereClause);
     425    } else {
     426        psFree(where);
     427        psError(PXTOOLS_ERR_DATA, false, "search parameters are required");
     428        return false;
    421429    }
    422430    psFree(where);
     
    429437    psFree(query);
    430438
    431     if (psDBAffectedRows(config->dbh) < 1) {
    432         psError(PS_ERR_UNKNOWN, false, "should have affected atleast 1 row");
    433         return false;
    434     }
     439    int numUpdated = psDBAffectedRows(config->dbh);
     440
     441    psLogMsg("regtool", PS_LOG_INFO, "Updated %d rawImfile", numUpdated);
    435442
    436443    return true;
     
    441448{
    442449    PS_ASSERT_PTR_NON_NULL(config, false);
     450
     451    PXOPT_LOOKUP_S64(exp_id, config->args, "-exp_id", true, false);
     452    PXOPT_LOOKUP_STR(class_id, config->args, "-class_id", true, false);
     453
     454    PXOPT_LOOKUP_S16(code, config->args, "-code", false, false);
     455    PXOPT_LOOKUP_F64(user_1, config->args, "-user_1", false, false);
     456
     457    if ((code == INT16_MAX) && !isfinite(user_1)) {
     458        psError(PS_ERR_UNKNOWN, false, "one of -code or -user_1 must be selected");
     459        return false;
     460    }
     461    if ((code != INT16_MAX) && isfinite(user_1)) {
     462        psError(PS_ERR_UNKNOWN, false, "only one of -code or -user_1 must be selected");
     463        return false;
     464    }
    443465
    444466    psMetadata *where = psMetadataAlloc();
     
    446468    PXOPT_COPY_STR(config->args, where,  "-class_id",     "class_id", "==");
    447469
    448     PXOPT_LOOKUP_S16(code, config->args, "-code", true, false);
    449 
    450     if (!pxSetFaultCode(config->dbh, "rawImfile", where, code)) {
    451         psError(PS_ERR_UNKNOWN, false, "failed to set set fault flag");
    452         psFree (where);
    453         return false;
     470    if (code != INT16_MAX) {
     471        // this is fairly dangerous : can set all if the where is not set...
     472        if (!pxSetFaultCode(config->dbh, "rawImfile", where, code)) {
     473            psError(PS_ERR_UNKNOWN, false, "failed to set set fault flag");
     474            psFree (where);
     475            return false;
     476        }
     477    }
     478
     479    if (isfinite(user_1)) {
     480        psString query = pxDataGet("regtool_updateprocessedimfile.sql");
     481        if (!query) {
     482            psError(PXTOOLS_ERR_DATA, false, "failed to retreive SQL statement");
     483            return false;
     484        }
     485
     486        if (!p_psDBRunQueryF(config->dbh, query, user_1, exp_id, class_id)) {
     487            psError(PS_ERR_UNKNOWN, false, "database error");
     488            psFree(query);
     489            return false;
     490        }
     491        psFree(query);
    454492    }
    455493    psFree (where);
     
    764802        hostname,
    765803        code,
    766         NULL
     804        NULL,
     805        0
    767806    )) {
    768807        // rollback
     
    806845                exp_id,
    807846                workdir,
    808             label,
     847                label,
    809848                reduction,
    810849                NULL, // expgroup
     
    957996    PXOPT_COPY_S64(config->args, where,  "-exp_id",       "exp_id", "==");
    958997    PXOPT_COPY_S16(config->args, where,  "-code",         "fault", "==");
     998    PXOPT_COPY_S64(config->args, where,  "-exp_id_begin", "exp_id", ">=");
     999    PXOPT_COPY_S64(config->args, where,  "-exp_id_end", "exp_id", "<=");
    9591000
    9601001    psString query = pxDataGet("regtool_revertprocessedexp.sql");
     
    9681009        psString whereClause = psDBGenerateWhereConditionSQL(where, "rawExp");
    9691010        psStringAppend(&query, " AND %s", whereClause);
     1011        psFree(whereClause);
     1012    } else {
    9701013        psFree(where);
    971         psFree(whereClause);
     1014        psError(PXTOOLS_ERR_DATA, false, "search parameters are required");
     1015        return false;
    9721016    }
    9731017    psFree(where);
     
    9801024    psFree(query);
    9811025
    982     if (psDBAffectedRows(config->dbh) < 1) {
    983         psError(PS_ERR_UNKNOWN, false, "should have affected atleast 1 row");
    984         return false;
    985     }
     1026    int numUpdated = psDBAffectedRows(config->dbh);
     1027
     1028    psLogMsg("regtool", PS_LOG_INFO, "Updated %d rawExp", numUpdated);
    9861029
    9871030    return true;
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/regtoolConfig.c

    r23352 r23594  
    129129    ADD_OPT(Str,  processedimfileArgs, "-exp_name",  "search by exposure name",               NULL);
    130130    ADD_OPT(Str,  processedimfileArgs, "-class_id",  "search by class ID",                    NULL);
     131    ADD_OPT(Time, processedimfileArgs, "-dateobs_begin", "search for exposures by time (>=)", NULL);
     132    ADD_OPT(Time, processedimfileArgs, "-dateobs_end", "search for exposures by time (<)", NULL);
    131133    ADD_OPT(U64,  processedimfileArgs, "-limit",     "limit result set to N items",           0);
    132134    ADD_OPT(Bool, processedimfileArgs, "-faulted",   "only return imfiles with a fault status set", false);
     
    135137    // -revertprocessedimfile
    136138    psMetadata *revertprocessedimfileArgs = psMetadataAlloc();
    137     ADD_OPT(S64, revertprocessedimfileArgs, "-exp_id",        "search by exposure ID (required)", 0);
     139    ADD_OPT(S64, revertprocessedimfileArgs, "-exp_id",        "search by exposure ID", 0);
    138140    ADD_OPT(Str, revertprocessedimfileArgs, "-tmp_class_id",  "searcy by temp. class ID", NULL);
    139141    ADD_OPT(Str, revertprocessedimfileArgs, "-class_id",      "search by class ID", NULL);
    140142    ADD_OPT(S16, revertprocessedimfileArgs, "-code",          "search by fault code", 0);
     143    ADD_OPT(S64, revertprocessedimfileArgs, "-exp_id_begin",  "search by exposure ID", 0);
     144    ADD_OPT(S64, revertprocessedimfileArgs, "-exp_id_end",    "search by exposure ID", 0);
    141145
    142146    // -updateprocessedimfile
     
    144148    ADD_OPT(S64, updateprocessedimfileArgs, "-exp_id",        "search by exposure ID", 0);
    145149    ADD_OPT(Str, updateprocessedimfileArgs, "-class_id",      "search by class ID", NULL);
    146     ADD_OPT(S16, updateprocessedimfileArgs, "-code",          "set fault code (required)", INT16_MAX);
     150    ADD_OPT(F64, updateprocessedimfileArgs, "-user_1",        "set user stat (1)", NAN);
     151    ADD_OPT(S16, updateprocessedimfileArgs, "-code",          "set fault code", INT16_MAX);
    147152
    148153    // -pendingexp
     
    270275    // -revertprocessedexp
    271276    psMetadata *revertprocessedexpArgs = psMetadataAlloc();
    272     psMetadataAddS64(revertprocessedexpArgs, PS_LIST_TAIL, "-exp_id",   0,            "search by exposure ID (required)", 0);
     277    psMetadataAddS64(revertprocessedexpArgs, PS_LIST_TAIL, "-exp_id",   0,            "search by exposure ID", 0);
    273278    psMetadataAddS16(revertprocessedexpArgs, PS_LIST_TAIL, "-code",     0,            "search by fault code", 0);
     279    psMetadataAddS64(revertprocessedexpArgs, PS_LIST_TAIL, "-exp_id_begin",   0,      "search by exposure ID", 0);
     280    psMetadataAddS64(revertprocessedexpArgs, PS_LIST_TAIL, "-exp_id_end",   0,      "search by exposure ID", 0);
    274281
    275282    // -updatedprocessedexp
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/warptool.c

    r23352 r23594  
    157157            tess_id,
    158158            end_stage,
    159             registered
     159            registered,
     160            false       // magicked
    160161    );
    161162    if (!warpRun) {
     
    190191
    191192    psMetadata *where = psMetadataAlloc();
    192     PXOPT_COPY_S64(config->args, where, "-fake_id", "fakeRun.fake_id", "==");
    193     PXOPT_COPY_S64(config->args, where, "-cam_id", "camRun.cam_id", "==");
    194     PXOPT_COPY_S64(config->args, where, "-chip_id", "chipRun.chip_id", "==");
    195     PXOPT_COPY_S64(config->args, where, "-exp_id", "newExp.exp_id", "==");
    196     PXOPT_COPY_STR(config->args, where, "-exp_name", "exp_name", "==");
    197     PXOPT_COPY_STR(config->args, where, "-inst", "camera", "==");
    198     PXOPT_COPY_STR(config->args, where, "-telescope", "telescope", "==");
    199     PXOPT_COPY_TIME(config->args, where, "-dateobs_begin", "dateobs", ">=");
    200     PXOPT_COPY_TIME(config->args, where, "-dateobs_end", "dateobs", "<=");
    201     PXOPT_COPY_STR(config->args, where, "-exp_tag", "exp_tag", "==");
    202     PXOPT_COPY_STR(config->args, where, "-exp_type", "exp_type", "==");
    203     PXOPT_COPY_STR(config->args, where, "-filelevel", "filelevel", "==");
    204     PXOPT_COPY_STR(config->args, where, "-reduction", "reduction", "==");
    205     PXOPT_COPY_STR(config->args, where, "-filter", "filter", "==");
    206     PXOPT_COPY_F64(config->args, where, "-airmass_min", "airmass", ">=");
    207     PXOPT_COPY_F64(config->args, where, "-airmass_max", "airmass", "<");
    208     PXOPT_COPY_F64(config->args, where, "-ra_min", "ra", ">=");
    209     PXOPT_COPY_F64(config->args, where, "-ra_max", "ra", "<");
    210     PXOPT_COPY_F64(config->args, where, "-decl_min", "decl", ">=");
    211     PXOPT_COPY_F64(config->args, where, "-decl_max", "decl", "<");
    212     PXOPT_COPY_F32(config->args, where, "-exp_time_min", "exp_time", ">=");
    213     PXOPT_COPY_F32(config->args, where, "-exp_time_max", "exp_time", "<");
    214     PXOPT_COPY_F32(config->args, where, "-sat_pixel_frac_min", "sat_pixel_frac", ">=");
    215     PXOPT_COPY_F32(config->args, where, "-sat_pixel_frac_max", "sat_pixel_frac", "<");
    216     PXOPT_COPY_F64(config->args, where, "-bg_min", "bt", ">=");
    217     PXOPT_COPY_F64(config->args, where, "-bg_max", "bt", "<");
    218     PXOPT_COPY_F64(config->args, where, "-bg_stdev_min", "bg_stdev", ">=");
    219     PXOPT_COPY_F64(config->args, where, "-bg_stdev_max", "bg_stdev", "<");
    220     PXOPT_COPY_F64(config->args, where, "-bg_mean_stdev_min", "bg_mean_stdev", ">=");
    221     PXOPT_COPY_F64(config->args, where, "-bg_mean_stdev_max", "bg_mean_stdev", "<");
    222     PXOPT_COPY_F64(config->args, where, "-alt_min", "alt", ">=");
    223     PXOPT_COPY_F64(config->args, where, "-alt_max", "alt", "<");
    224     PXOPT_COPY_F64(config->args, where, "-az_min", "az", ">=");
    225     PXOPT_COPY_F64(config->args, where, "-az_max", "az", "<");
    226     PXOPT_COPY_F32(config->args, where, "-ccd_temp_min", "ccd_temp", ">=");
    227     PXOPT_COPY_F32(config->args, where, "-ccd_temp_max", "ccd_temp", "<");
    228     PXOPT_COPY_F64(config->args, where, "-posang_min", "posang", ">=");
    229     PXOPT_COPY_F64(config->args, where, "-posang_max", "posang", "<");
    230     PXOPT_COPY_STR(config->args, where, "-object", "object", "==");
    231     PXOPT_COPY_F32(config->args, where, "-solang_min", "solang", ">=");
    232     PXOPT_COPY_F32(config->args, where, "-solang_max", "solang", "<");
    233     PXOPT_COPY_STR(config->args, where, "-label", "label", "==");
     193    pxwarpGetSearchArgs (config, where);
     194    PXOPT_COPY_STR(config->args, where, "-reduction", "fakeRun.reduction", "==");
     195    PXOPT_COPY_STR(config->args, where, "-label",     "fakeRun.label",     "==");
    234196
    235197    if (!psListLength(where->list) &&
     
    337299
    338300    psMetadata *where = psMetadataAlloc();
    339     PXOPT_COPY_S64(config->args, where, "-warp_id", "warp_id", "==");
    340     PXOPT_COPY_S64(config->args, where, "-fake_id", "fake_id", "==");
    341     PXOPT_COPY_S64(config->args, where, "-chip_id", "chip_id", "==");
    342     PXOPT_COPY_S64(config->args, where, "-exp_id", "exp_id", "==");
    343     PXOPT_COPY_STR(config->args, where, "-exp_name", "exp_name", "==");
    344     PXOPT_COPY_STR(config->args, where, "-inst", "camera", "==");
    345     PXOPT_COPY_STR(config->args, where, "-telescope", "telescope", "==");
    346     PXOPT_COPY_TIME(config->args, where, "-dateobs_begin", "dateobs", ">=");
    347     PXOPT_COPY_TIME(config->args, where, "-dateobs_end", "dateobs", "<=");
    348     PXOPT_COPY_STR(config->args, where, "-exp_tag", "exp_tag", "==");
    349     PXOPT_COPY_STR(config->args, where, "-exp_type", "exp_type", "==");
    350     PXOPT_COPY_STR(config->args, where, "-filelevel", "filelevel", "==");
    351     PXOPT_COPY_STR(config->args, where, "-reduction", "reduction", "==");
    352     PXOPT_COPY_STR(config->args, where, "-filter", "filter", "==");
    353     PXOPT_COPY_F32(config->args, where, "-airmass_min", "airmass", ">=");
    354     PXOPT_COPY_F32(config->args, where, "-airmass_max", "airmass", "<");
    355     PXOPT_COPY_F64(config->args, where, "-ra_min", "ra", ">=");
    356     PXOPT_COPY_F64(config->args, where, "-ra_max", "ra", "<");
    357     PXOPT_COPY_F64(config->args, where, "-decl_min", "decl", ">=");
    358     PXOPT_COPY_F64(config->args, where, "-decl_max", "decl", "<");
    359     PXOPT_COPY_F32(config->args, where, "-exp_time_min", "exp_time", ">=");
    360     PXOPT_COPY_F32(config->args, where, "-exp_time_max", "exp_time", "<");
    361     PXOPT_COPY_F32(config->args, where, "-sat_pixel_frac_min", "sat_pixel_frac", ">=");
    362     PXOPT_COPY_F32(config->args, where, "-sat_pixel_frac_max", "sat_pixel_frac", "<");
    363     PXOPT_COPY_F64(config->args, where, "-bg_min", "bt", ">=");
    364     PXOPT_COPY_F64(config->args, where, "-bg_max", "bt", "<");
    365     PXOPT_COPY_F64(config->args, where, "-bg_stdev_min", "bg_stdev", ">=");
    366     PXOPT_COPY_F64(config->args, where, "-bg_stdev_max", "bg_stdev", "<");
    367     PXOPT_COPY_F64(config->args, where, "-bg_mean_stdev_min", "bg_mean_stdev", ">=");
    368     PXOPT_COPY_F64(config->args, where, "-bg_mean_stdev_max", "bg_mean_stdev", "<");
    369     PXOPT_COPY_F64(config->args, where, "-alt_min", "alt", ">=");
    370     PXOPT_COPY_F64(config->args, where, "-alt_max", "alt", "<");
    371     PXOPT_COPY_F64(config->args, where, "-az_min", "az", ">=");
    372     PXOPT_COPY_F64(config->args, where, "-az_max", "az", "<");
    373     PXOPT_COPY_F64(config->args, where, "-ccd_temp_min", "ccd_temp", ">=");
    374     PXOPT_COPY_F64(config->args, where, "-ccd_temp_max", "ccd_temp", "<");
    375     PXOPT_COPY_F64(config->args, where, "-posang_min", "posang", ">=");
    376     PXOPT_COPY_F64(config->args, where, "-posang_max", "posang", "<");
    377     PXOPT_COPY_STR(config->args, where, "-object", "object", "==");
    378     PXOPT_COPY_F32(config->args, where, "-solang_min", "solang", ">=");
    379     PXOPT_COPY_F32(config->args, where, "-solang_max", "solang", "<");
     301    pxwarpGetSearchArgs (config, where);
     302    PXOPT_COPY_S64(config->args, where, "-warp_id",   "warpRun.warp_id",   "==");
     303    PXOPT_COPY_STR(config->args, where, "-reduction", "warpRun.reduction", "==");
     304    PXOPT_COPY_STR(config->args, where, "-label",     "warpRun.label",     "==");
     305    PXOPT_COPY_STR(config->args, where, "-state",     "warpRun.state",     "==");
    380306
    381307    if (!psListLength(where->list)
     
    387313    }
    388314
    389     PXOPT_LOOKUP_STR(state, config->args, "-state", false, false);
    390     PXOPT_LOOKUP_STR(label, config->args, "-label", false, false);
     315    PXOPT_LOOKUP_STR(state, config->args, "-set_state", false, false);
     316    PXOPT_LOOKUP_STR(label, config->args, "-set_label", false, false);
    391317
    392318    if ((!state) && (!label)) {
     
    934860    PXOPT_LOOKUP_F32(good_frac, config->args, "-good_frac", false, false);
    935861    PXOPT_LOOKUP_BOOL(accept, config->args, "-accept", false);
     862    PXOPT_LOOKUP_BOOL(magicked, config->args, "-magicked", false);
    936863
    937864    // default values
     
    965892                           !accept,
    966893                           code,
    967                            0            // magic_ds_id
     894                           magicked
    968895        )) {
    969896        if (!psDBRollback(config->dbh)) {
     
    995922    PS_ASSERT_PTR_NON_NULL(config, false);
    996923
    997     // XXX this SQL has not been broken out to into seperate files as the MYSQL
    998     // < 5 & MYSQL 5 versions need to be kept in sync
    999 
    1000 #undef MYSQL5
    1001 #if MYSQL5
    1002     // XXX at MySQL 4.1.21 (probably all of 4.1.x) chokes and dies on this
    1003     // statement as it thinks it is trying to select from the table being
    1004     // updated. The 4.1 manual says that nested sub-queries are explicited
    1005     // allowed to do this with update statements as a temporary table is
    1006     // created so that you are not actually selecting from the table you are
    1007     // modifying.
    1008     char *query =
    1009         "UPDATE warpRun\n"
    1010         "   SET warpRun.state = 'stop'\n"
    1011         " WHERE\n"
    1012         "   warpRun.warp_id =\n"
    1013         "   (SELECT DISTINCT\n"
    1014         "       warp_id\n"
    1015         "   FROM\n"
    1016         "       (SELECT DISTINCT\n"
    1017         "           warpRun.warp_id,\n"
    1018         "           warpSkyCellMap.warp_id as foo,\n"
    1019         "           warpSkyfile.warp_id as bar\n"
    1020         "       FROM warpRun\n"
    1021         "       JOIN warpSkyCellMap\n"
    1022         "           USING(warp_id)\n"
    1023         "       LEFT JOIN warpSkyfile\n"
    1024         "           USING(warp_id, skycell_id, tess_id)\n"
    1025         "       WHERE\n"
    1026         "           warpRun.state = 'new'\n"
    1027         "       GROUP BY\n"
    1028         "           warpRun.warp_id\n"
    1029         "       HAVING\n"
    1030         "       COUNT(warpSkyCellMap.warp_id) = COUNT(warpSkyfile.warp_id)\n"
    1031         "       ) as Foo\n"
    1032         "   )\n";
     924    psString query = pxDataGet("warptool_finished_run_select.sql");
     925    if (!query) {
     926        psError(PXTOOLS_ERR_DATA, false, "failed to retrieve SQL statement");
     927        return false;
     928    }
    1033929
    1034930    if (!p_psDBRunQuery(config->dbh, query)) {
    1035931        psError(PS_ERR_UNKNOWN, false, "database error");
    1036         return false;
    1037     }
    1038 #else // if MYSQL5
    1039 {
    1040     char *query =
    1041         "CREATE TEMPORARY TABLE finished\n"
    1042         " (warp_id INT, PRIMARY KEY(warp_id)) ENGINE=MEMORY\n";
    1043 
    1044     if (!p_psDBRunQuery(config->dbh, query)) {
    1045         psError(PS_ERR_UNKNOWN, false, "database error");
    1046         return false;
    1047     }
    1048 }
    1049 
    1050 {
    1051     char *query =
    1052         "INSERT INTO finished\n"
    1053         " SELECT\n"
    1054         "   warp_id\n"
    1055         " FROM\n"
    1056         "   (SELECT DISTINCT\n"
    1057         "       warpRun.warp_id,\n"
    1058         "       warpSkyCellMap.warp_id as foo,\n"
    1059         "       warpSkyfile.warp_id as bar\n"
    1060         "   FROM warpRun\n"
    1061         "   JOIN warpSkyCellMap\n"
    1062         "       USING(warp_id)\n"
    1063         "   LEFT JOIN warpSkyfile\n"
    1064         "       USING(warp_id, skycell_id)\n"
    1065         "   WHERE\n"
    1066         "       warpRun.state = 'new'\n"
    1067         "   GROUP BY\n"
    1068         "       warpRun.warp_id\n"
    1069         "   HAVING\n"
    1070         "       COUNT(warpSkyCellMap.warp_id) = COUNT(warpSkyfile.warp_id)\n"
    1071         " ) as Foo \n";
    1072 
    1073     if (!p_psDBRunQuery(config->dbh, query)) {
    1074         psError(PS_ERR_UNKNOWN, false, "database error");
    1075         return false;
    1076     }
    1077 }
    1078 
    1079 {
    1080     char *query =
    1081         "UPDATE warpRun\n"
    1082         "   SET warpRun.state = 'full'\n"
    1083         " WHERE\n"
    1084         "   warpRun.warp_id =\n"
    1085         "   (SELECT DISTINCT\n"
    1086         "       warp_id\n"
    1087         "   FROM finished\n"
    1088         "   )\n";
    1089 
    1090     if (!p_psDBRunQuery(config->dbh, query)) {
    1091         psError(PS_ERR_UNKNOWN, false, "database error");
    1092         return false;
    1093     }
    1094 }
    1095 #endif // if MYSQL5
     932        psFree(query);
     933        return false;
     934    }
     935    psFree(query);
     936
     937    psArray *output = p_psDBFetchResult(config->dbh);
     938    if (!output) {
     939        psError(PS_ERR_UNKNOWN, false, "database error");
     940        return false;
     941    }
     942    if (!psArrayLength(output)) {
     943        psTrace("warptool", PS_LOG_INFO, "no rows found");
     944        psFree(output);
     945        return true;
     946    }
     947
     948    query = pxDataGet("warptool_finish_run.sql");
     949    for (long i = 0; i < psArrayLength(output); i++) {
     950        psMetadata *row = output->data[i];
     951
     952        bool status;
     953        psS64 warp_id = psMetadataLookupS64(&status, row, "warp_id");
     954        if (!status) {
     955            psError(PS_ERR_UNKNOWN, false, "failed to look up value for warp_id");
     956            psFree(output);
     957            psFree(query);
     958            return false;
     959        }
     960        psS32 magicked = psMetadataLookupS64(&status, row, "magicked");
     961        if (!status) {
     962            psError(PS_ERR_UNKNOWN, false, "failed to look up value for magicked");
     963            psFree(output);
     964            psFree(query);
     965            return false;
     966        }
     967        if (!p_psDBRunQueryF(config->dbh, query, magicked, warp_id)) {
     968            psError(PS_ERR_UNKNOWN, false, "database error");
     969            psFree(output);
     970            psFree(query);
     971            return false;
     972        }
     973
     974        psS64 numUpdated = psDBAffectedRows(config->dbh);
     975
     976        if (numUpdated != 1) {
     977            psError(PS_ERR_UNKNOWN, false, "should have affected 1 row");
     978            psFree(query);
     979            psFree(output);
     980            return false;
     981        }
     982    }
     983    psFree(output);
     984    psFree(query);
    1096985
    1097986    return true;
     
    11811070
    11821071    psMetadata *where = psMetadataAlloc();
    1183     PXOPT_COPY_S64(config->args, where, "-warp_id", "warpSkyfile.warp_id", "==");
     1072    pxwarpGetSearchArgs (config, where);
     1073    PXOPT_COPY_S64(config->args, where, "-warp_id",    "warpSkyfile.warp_id", "==");
    11841074    PXOPT_COPY_STR(config->args, where, "-skycell_id", "warpSkyfile.skycell_id", "==");
    1185     PXOPT_COPY_STR(config->args, where, "-tess_id", "warpSkyfile.tess_id", "==");
    1186     PXOPT_COPY_S64(config->args, where, "-fake_id", "fakeRun.fake_id", "==");
    1187     PXOPT_COPY_S64(config->args, where, "-chip_id", "chipRun.chip_id", "==");
    1188     PXOPT_COPY_S64(config->args, where, "-exp_id", "rawExp.exp_id", "==");
    1189 
    1190     PXOPT_COPY_STR(config->args, where, "-exp_name", "rawExp.exp_name", "==");
    1191     PXOPT_COPY_STR(config->args, where, "-label", "warpRun.label", "==");
    1192     PXOPT_COPY_STR(config->args, where, "-inst", "rawExp.camera", "==");
    1193     PXOPT_COPY_STR(config->args, where, "-telescope", "rawExp.telescope", "==");
    1194     PXOPT_COPY_TIME(config->args, where, "-dateobs_begin", "rawExp.dateobs", ">=");
    1195     PXOPT_COPY_TIME(config->args, where, "-dateobs_end", "rawExp.dateobs", "<=");
    1196     PXOPT_COPY_STR(config->args, where, "-exp_tag", "rawExp.exp_tag", "==");
    1197     PXOPT_COPY_STR(config->args, where, "-exp_type", "rawExp.exp_type", "==");
    1198     PXOPT_COPY_STR(config->args, where, "-filelevel", "rawExp.filelevel", "==");
    1199     PXOPT_COPY_STR(config->args, where, "-reduction", "rawExp.reduction", "==");
    1200     PXOPT_COPY_STR(config->args, where, "-filter", "rawExp.filter", "==");
    1201 
    1202     PXOPT_COPY_F32(config->args, where, "-airmass_min", "rawExp.airmass", ">=");
    1203     PXOPT_COPY_F32(config->args, where, "-airmass_max", "rawExp.airmass", "<");
    1204     PXOPT_COPY_F64(config->args, where, "-ra_min", "rawExp.ra", ">=");
    1205     PXOPT_COPY_F64(config->args, where, "-ra_max", "rawExp.ra", "<");
    1206     PXOPT_COPY_F64(config->args, where, "-decl_min", "rawExp.decl", ">=");
    1207     PXOPT_COPY_F64(config->args, where, "-decl_max", "rawExp.decl", "<");
    1208     PXOPT_COPY_F32(config->args, where, "-exp_time_min", "rawExp.exp_time", ">=");
    1209     PXOPT_COPY_F32(config->args, where, "-exp_time_max", "rawExp.exp_time", "<");
    1210     PXOPT_COPY_F32(config->args, where, "-sat_pixel_frac_min", "rawExp.sat_pixel_frac", ">=");
    1211     PXOPT_COPY_F32(config->args, where, "-sat_pixel_frac_max", "rawExp.sat_pixel_frac", "<");
    1212     PXOPT_COPY_F64(config->args, where, "-bg_min", "rawExp.bg", ">=");
    1213     PXOPT_COPY_F64(config->args, where, "-bg_max", "rawExp.bg", "<");
    1214     PXOPT_COPY_F64(config->args, where, "-bg_stdev_min", "rawExp.bg_stdev", ">=");
    1215     PXOPT_COPY_F64(config->args, where, "-bg_stdev_max", "rawExp.bg_stdev", "<");
    1216     PXOPT_COPY_F64(config->args, where, "-bg_mean_stdev_min", "rawExp.bg_mean_stdev", ">=");
    1217     PXOPT_COPY_F64(config->args, where, "-bg_mean_stdev_max", "rawExp.bg_mean_stdev", "<");
    1218     PXOPT_COPY_F64(config->args, where, "-alt_min", "rawExp.alt", ">=");
    1219     PXOPT_COPY_F64(config->args, where, "-alt_max", "rawExp.alt", "<");
    1220     PXOPT_COPY_F64(config->args, where, "-az_min", "rawExp.az", ">=");
    1221     PXOPT_COPY_F64(config->args, where, "-az_max", "rawExp.az", "<");
    1222     PXOPT_COPY_F64(config->args, where, "-ccd_temp_min", "rawExp.ccd_temp", ">=");
    1223     PXOPT_COPY_F64(config->args, where, "-ccd_temp_max", "rawExp.ccd_temp", "<");
    1224     PXOPT_COPY_F64(config->args, where, "-posang_min", "rawExp.posang", ">=");
    1225     PXOPT_COPY_F64(config->args, where, "-posang_max", "rawExp.posang", "<");
    1226     PXOPT_COPY_STR(config->args, where, "-object", "rawExp.object", "==");
    1227     PXOPT_COPY_F32(config->args, where, "-solang_min", "rawExp.solang", ">=");
    1228     PXOPT_COPY_F32(config->args, where, "-solang_max", "rawExp.solang", "<");
    1229     PXOPT_COPY_S16(config->args, where, "-code", "warpSkyfile.fault", "==");
     1075    PXOPT_COPY_STR(config->args, where, "-tess_id",    "warpSkyfile.tess_id", "==");
     1076    PXOPT_COPY_STR(config->args, where, "-reduction",  "rawExp.reduction", "==");
     1077    PXOPT_COPY_STR(config->args, where, "-label",      "warpRun.label", "==");
     1078    PXOPT_COPY_S16(config->args, where, "-code",       "warpSkyfile.fault", "==");
    12301079
    12311080    if (!psListLength(where->list)
     
    12461095    int numUpdated;                     // Number updated
    12471096    {
     1097        // This query is no longer necessary because we do not set warpRun's to full statte
     1098        // if they have faulted skyfiles.
     1099        // We do have runs in the DB that follow the old convention so we leave this in for
     1100        // now
    12481101        psString query = pxDataGet("warptool_revertwarped_update.sql");
    12491102        if (!query) {
     
    12731126        numUpdated = psDBAffectedRows(config->dbh);
    12741127
     1128#ifdef notdef
     1129        // new warpRuns won't get changed (they're already new) so don't require an update
    12751130        if (numUpdated < 1) {
    1276             psError(PS_ERR_UNKNOWN, false, "should have affected atleast 1 row");
     1131            psError(PS_ERR_UNKNOWN, false, "should have affected at least 1 row");
    12771132            if (!psDBRollback(config->dbh)) {
    12781133                psError(PS_ERR_UNKNOWN, false, "database error");
     
    12801135            return false;
    12811136        }
     1137#endif
    12821138    }
    12831139
     
    14621318    PS_ASSERT_PTR_NON_NULL(config, NULL);
    14631319
    1464     PXOPT_LOOKUP_S64(warp_id, config->args, "-warp_id", false, false);
     1320    PXOPT_LOOKUP_S64(warp_id, config->args, "-warp_id", true, false);
    14651321    PXOPT_LOOKUP_U64(limit, config->args, "-limit", false, false);
    14661322    PXOPT_LOOKUP_BOOL(simple, config->args, "-simple", false);
    14671323
    14681324    psMetadata *where = psMetadataAlloc();
    1469     if (warp_id) {
    1470         PXOPT_COPY_S64(config->args, where, "-warp_id", "warp_id", "==");
    1471     }
     1325    PXOPT_COPY_S64(config->args, where, "-warp_id", "warp_id", "==");
    14721326    PXOPT_COPY_STR(config->args, where, "-label", "label", "==");
    14731327
     
    16241478
    16251479    // note only updates if warpRun.state = run_state
    1626     if (!p_psDBRunQueryF(config->dbh, query, data_state, warp_id, skycell_id, run_state)) {
     1480    // XXX note that we have removed this constraint for now
     1481    if (!p_psDBRunQueryF(config->dbh, query, data_state, warp_id, skycell_id)) {
    16271482        psError(PS_ERR_UNKNOWN, false, "database error");
    16281483        // rollback
  • branches/cnb_branches/cnb_branch_20090301/ippTools/src/warptoolConfig.c

    r23352 r23594  
    5151    // XXX need to allow multiple exp_ids
    5252    psMetadata *definebyqueryArgs = psMetadataAlloc();
    53     psMetadataAddS64(definebyqueryArgs, PS_LIST_TAIL, "-fake_id",            0, "search by fake_id", 0);
    54     psMetadataAddS64(definebyqueryArgs, PS_LIST_TAIL, "-cam_id",             0, "search by cam_id", 0);
    55     psMetadataAddS64(definebyqueryArgs, PS_LIST_TAIL, "-chip_id",            0, "search by chip_id", 0);
    56     psMetadataAddS64(definebyqueryArgs, PS_LIST_TAIL, "-exp_id",             0, "search by exp_id", 0);
    57     psMetadataAddStr(definebyqueryArgs, PS_LIST_TAIL, "-exp_name",           0, "search by exp_name", NULL);
    58     psMetadataAddStr(definebyqueryArgs, PS_LIST_TAIL, "-inst",               0, "search for camera", NULL);
    59     psMetadataAddStr(definebyqueryArgs, PS_LIST_TAIL, "-telescope",          0, "search for telescope", NULL);
    60     psMetadataAddTime(definebyqueryArgs, PS_LIST_TAIL, "-dateobs_begin",     0, "search for exposures by time (>=)", NULL);
    61     psMetadataAddTime(definebyqueryArgs, PS_LIST_TAIL, "-dateobs_end",       0, "search for exposures by time (<)", NULL);
    62     psMetadataAddStr(definebyqueryArgs, PS_LIST_TAIL, "-exp_tag",            0, "search by exp_tag", NULL);
    63     psMetadataAddStr(definebyqueryArgs, PS_LIST_TAIL, "-exp_type",           0, "search by exp_type", NULL);
    64     psMetadataAddStr(definebyqueryArgs, PS_LIST_TAIL, "-filelevel",          0, "search by filelevel", NULL);
    65     psMetadataAddStr(definebyqueryArgs, PS_LIST_TAIL, "-reduction",          0, "search by reduction class", NULL);
    66     psMetadataAddStr(definebyqueryArgs, PS_LIST_TAIL, "-filter",             0, "search for filter", NULL);
    67     psMetadataAddF64(definebyqueryArgs, PS_LIST_TAIL, "-airmass_min",        0, "define min airmass", NAN);
    68     psMetadataAddF64(definebyqueryArgs, PS_LIST_TAIL, "-airmass_max",        0, "define max airmass", NAN);
    69     psMetadataAddF64(definebyqueryArgs, PS_LIST_TAIL, "-ra_min",             0, "define min", NAN);
    70     psMetadataAddF64(definebyqueryArgs, PS_LIST_TAIL, "-ra_max",             0, "define max", NAN);
    71     psMetadataAddF64(definebyqueryArgs, PS_LIST_TAIL, "-decl_min",           0, "define min", NAN);
    72     psMetadataAddF64(definebyqueryArgs, PS_LIST_TAIL, "-decl_max",           0, "define max", NAN);
    73     psMetadataAddF32(definebyqueryArgs, PS_LIST_TAIL, "-exp_time_min",       0, "define min", NAN);
    74     psMetadataAddF32(definebyqueryArgs, PS_LIST_TAIL, "-exp_time_max",       0, "define max", NAN);
    75     psMetadataAddF32(definebyqueryArgs, PS_LIST_TAIL, "-sat_pixel_frac_min", 0, "define max fraction of saturated pixels", NAN);
    76     psMetadataAddF32(definebyqueryArgs, PS_LIST_TAIL, "-sat_pixel_frac_max", 0, "define min fraction of saturated pixels", NAN);
    77     psMetadataAddF64(definebyqueryArgs, PS_LIST_TAIL, "-bg_min",             0, "define max", NAN);
    78     psMetadataAddF64(definebyqueryArgs, PS_LIST_TAIL, "-bg_max",             0, "define max", NAN);
    79     psMetadataAddF64(definebyqueryArgs, PS_LIST_TAIL, "-bg_stdev_min",       0, "define max", NAN);
    80     psMetadataAddF64(definebyqueryArgs, PS_LIST_TAIL, "-bg_stdev_max",       0, "define max", NAN);
    81     psMetadataAddF64(definebyqueryArgs, PS_LIST_TAIL, "-bg_mean_stdev_min",  0, "define max", NAN);
    82     psMetadataAddF64(definebyqueryArgs, PS_LIST_TAIL, "-bg_mean_stdev_max",  0, "define max", NAN);
    83     psMetadataAddF64(definebyqueryArgs, PS_LIST_TAIL, "-alt_min",            0, "define min", NAN);
    84     psMetadataAddF64(definebyqueryArgs, PS_LIST_TAIL, "-alt_max",            0, "define max", NAN);
    85     psMetadataAddF64(definebyqueryArgs, PS_LIST_TAIL, "-az_min",             0, "define min", NAN);
    86     psMetadataAddF64(definebyqueryArgs, PS_LIST_TAIL, "-az_max",             0, "define max", NAN);
    87     psMetadataAddF32(definebyqueryArgs, PS_LIST_TAIL, "-ccd_temp_min",       0, "define min ccd tempature", NAN);
    88     psMetadataAddF32(definebyqueryArgs, PS_LIST_TAIL, "-ccd_temp_max",       0, "define max ccd tempature", NAN);
    89     psMetadataAddF64(definebyqueryArgs, PS_LIST_TAIL, "-posang_min",         0, "define min rotator position angle", NAN);
    90     psMetadataAddF64(definebyqueryArgs, PS_LIST_TAIL, "-posang_max",         0, "define max rotator position angle", NAN);
    91     psMetadataAddStr(definebyqueryArgs, PS_LIST_TAIL, "-object",             0, "search by exposure object", NULL);
    92     psMetadataAddF32(definebyqueryArgs, PS_LIST_TAIL, "-solang_min",         0, "define min solar angle", NAN);
    93     psMetadataAddF32(definebyqueryArgs, PS_LIST_TAIL, "-solang_max",         0, "define max solar angle", NAN);
    94     psMetadataAddStr(definebyqueryArgs, PS_LIST_TAIL, "-label", 0, "search on fakeRun label", NULL);
    95 
     53    pxwarpSetSearchArgs (definebyqueryArgs);
     54    psMetadataAddStr(definebyqueryArgs, PS_LIST_TAIL, "-reduction",          0, "search by fakeRun reduction class", NULL);
     55    psMetadataAddStr(definebyqueryArgs, PS_LIST_TAIL, "-label",              0, "search on fakeRun label", NULL);
    9656    psMetadataAddStr(definebyqueryArgs, PS_LIST_TAIL, "-set_mode",           0, "define mode (warp, diff, stack, magic)", NULL);
    9757    psMetadataAddStr(definebyqueryArgs, PS_LIST_TAIL, "-set_workdir",        0, "define workdir", NULL);
     
    12383    // XXX need to allow multiple exp_ids
    12484    psMetadata *updaterunArgs = psMetadataAlloc();
    125     psMetadataAddS64(updaterunArgs, PS_LIST_TAIL, "-warp_id", 0,            "search by warptool ID", 0);
    126     psMetadataAddS64(updaterunArgs, PS_LIST_TAIL, "-fake_id",  0,            "search by fake_id", 0);
    127     psMetadataAddS64(updaterunArgs, PS_LIST_TAIL, "-chip_id",  0,            "search by chip_id", 0);
    128     psMetadataAddS64(updaterunArgs, PS_LIST_TAIL, "-exp_id",  0,            "search by exp_id", 0);
    129     psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-exp_name",  0,            "search by exp_name", NULL);
    130     psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-inst",  0,            "search for camera", NULL);
    131     psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-telescope",  0,            "search for telescope", NULL);
    132     psMetadataAddTime(updaterunArgs, PS_LIST_TAIL, "-dateobs_begin", 0,            "search for exposures by time (>=)", NULL);
    133     psMetadataAddTime(updaterunArgs, PS_LIST_TAIL, "-dateobs_end", 0,            "search for exposures by time (<)", NULL);
    134     psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-exp_tag",  0,            "search by exp_tag", NULL);
    135     psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-exp_type",  0,            "search by exp_type", NULL);
    136     psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-filelevel",  0,            "search by filelevel", NULL);
    137     psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-reduction",  0,            "search by reduction class", NULL);
    138     psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-filter",  0,            "search for filter", NULL);
    139     psMetadataAddF32(updaterunArgs, PS_LIST_TAIL, "-airmass_min",  0,            "define min airmass", NAN);
    140     psMetadataAddF32(updaterunArgs, PS_LIST_TAIL, "-airmass_max",  0,            "define max airmass", NAN);
    141     psMetadataAddF64(updaterunArgs, PS_LIST_TAIL, "-ra_min",  0,            "define min", NAN);
    142     psMetadataAddF64(updaterunArgs, PS_LIST_TAIL, "-ra_max",  0,            "define max", NAN);
    143     psMetadataAddF64(updaterunArgs, PS_LIST_TAIL, "-decl_min",  0,            "define min", NAN);
    144     psMetadataAddF64(updaterunArgs, PS_LIST_TAIL, "-decl_max",  0,            "define max", NAN);
    145     psMetadataAddF32(updaterunArgs, PS_LIST_TAIL, "-exp_time_min",  0,            "define min", NAN);
    146     psMetadataAddF32(updaterunArgs, PS_LIST_TAIL, "-exp_time_max",  0,            "define max", NAN);
    147     psMetadataAddF32(updaterunArgs, PS_LIST_TAIL, "-sat_pixel_frac_min",  0,            "define max fraction of saturated pixels", NAN);
    148     psMetadataAddF32(updaterunArgs, PS_LIST_TAIL, "-sat_pixel_frac_max",  0,            "define min fraction of saturated pixels", NAN);
    149     psMetadataAddF64(updaterunArgs, PS_LIST_TAIL, "-bg_min",  0,            "define max", NAN);
    150     psMetadataAddF64(updaterunArgs, PS_LIST_TAIL, "-bg_max",  0,            "define max", NAN);
    151     psMetadataAddF64(updaterunArgs, PS_LIST_TAIL, "-bg_stdev_min",  0,            "define max", NAN);
    152     psMetadataAddF64(updaterunArgs, PS_LIST_TAIL, "-bg_stdev_max",  0,            "define max", NAN);
    153     psMetadataAddF64(updaterunArgs, PS_LIST_TAIL, "-bg_mean_stdev_min",  0,            "define max", NAN);
    154     psMetadataAddF64(updaterunArgs, PS_LIST_TAIL, "-bg_mean_stdev_max",  0,            "define max", NAN);
    155     psMetadataAddF64(updaterunArgs, PS_LIST_TAIL, "-alt_min",  0,            "define min", NAN);
    156     psMetadataAddF64(updaterunArgs, PS_LIST_TAIL, "-alt_max",  0,            "define max", NAN);
    157     psMetadataAddF64(updaterunArgs, PS_LIST_TAIL, "-az_min",  0,            "define min", NAN);
    158     psMetadataAddF64(updaterunArgs, PS_LIST_TAIL, "-az_max",  0,            "define max", NAN);
    159     psMetadataAddF64(updaterunArgs, PS_LIST_TAIL, "-ccd_temp_min",  0,            "define min ccd tempature", NAN);
    160     psMetadataAddF64(updaterunArgs, PS_LIST_TAIL, "-ccd_temp_max",  0,            "define max ccd tempature", NAN);
    161     psMetadataAddF64(updaterunArgs, PS_LIST_TAIL, "-posang_min",  0,            "define min rotator position angle", NAN);
    162     psMetadataAddF64(updaterunArgs, PS_LIST_TAIL, "-posang_max",  0,            "define max rotator position angle", NAN);
    163     psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-object",  0,            "search by exposure object", NULL);
    164     psMetadataAddF32(updaterunArgs, PS_LIST_TAIL, "-solang_min",  0,            "define min solar angle", NAN);
    165     psMetadataAddF32(updaterunArgs, PS_LIST_TAIL, "-solang_max",  0,            "define max solar angle", NAN);
    166 
    167     psMetadataAddBool(updaterunArgs, PS_LIST_TAIL, "-all",  0,            "allow everything to be queued without search terms", false);
    168     psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-state", 0,            "set state", NULL);
    169     psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-label", 0,            "set label", NULL);
    170 
    171 #if 0
    172     psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-workdir", 0,            "define workdir (required)", NULL);
    173     psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-registered",  0,            "time detrend run was registered", now);
    174 #endif
     85    pxwarpSetSearchArgs (updaterunArgs);
     86    psMetadataAddS64(updaterunArgs, PS_LIST_TAIL, "-warp_id", 0,    "search by warptool ID", 0);
     87    psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-reduction", 0,  "search by warpRun reduction class", NULL);
     88    psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-state", 0,      "search by warpRun state", NULL);
     89    psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-label", 0,      "search by warpRun label", NULL);
     90    psMetadataAddBool(updaterunArgs, PS_LIST_TAIL, "-all",  0,      "allow everything to be queued without search terms", false);
     91    psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-set_state", 0,  "set state", NULL);
     92    psMetadataAddStr(updaterunArgs, PS_LIST_TAIL, "-set_label", 0,  "set label", NULL);
    17593
    17694    // -exp
     
    235153    psMetadataAddF32(addwarpedArgs, PS_LIST_TAIL, "-good_frac",  0,            "define %% of good pixels", NAN);
    236154    psMetadataAddBool(addwarpedArgs, PS_LIST_TAIL, "-accept",  0, "define if this skycell should be accepted", false);
     155    psMetadataAddBool(addwarpedArgs, PS_LIST_TAIL, "-magicked",  0, "define if this skycell has been magicked", false);
    237156    psMetadataAddS16(addwarpedArgs, PS_LIST_TAIL, "-code",  0,            "set fault code", 0);
    238157
     
    254173    // XXX need to allow multiple exp_ids
    255174    psMetadata *revertwarpedArgs = psMetadataAlloc();
     175    pxwarpSetSearchArgs(revertwarpedArgs); // XXX does this work here?
    256176    psMetadataAddS64(revertwarpedArgs, PS_LIST_TAIL, "-warp_id", 0,            "search by warptool ID", 0);
    257177    psMetadataAddStr(revertwarpedArgs, PS_LIST_TAIL, "-skycell_id",  0,            "search by skycell ID", NULL);
    258     psMetadataAddStr(revertwarpedArgs, PS_LIST_TAIL, "-tess_id",  0,            "searcy by tessellation ID", NULL);
    259     psMetadataAddS64(revertwarpedArgs, PS_LIST_TAIL, "-fake_id",  0,            "search by fake_id", 0);
    260     psMetadataAddS64(revertwarpedArgs, PS_LIST_TAIL, "-chip_id",  0,            "search by chip_id", 0);
    261     psMetadataAddS64(revertwarpedArgs, PS_LIST_TAIL, "-exp_id",  0,            "search by exp_id", 0);
    262     psMetadataAddStr(revertwarpedArgs, PS_LIST_TAIL, "-exp_name",  0,            "search by exp_name", NULL);
    263     psMetadataAddStr(revertwarpedArgs, PS_LIST_TAIL, "-label",  0,            "search by label", NULL);
    264     psMetadataAddStr(revertwarpedArgs, PS_LIST_TAIL, "-inst",  0,            "search for camera", NULL);
    265     psMetadataAddStr(revertwarpedArgs, PS_LIST_TAIL, "-telescope",  0,            "search for telescope", NULL);
    266     psMetadataAddTime(revertwarpedArgs, PS_LIST_TAIL, "-dateobs_begin", 0,            "search for exposures by time (>=)", NULL);
    267     psMetadataAddTime(revertwarpedArgs, PS_LIST_TAIL, "-dateobs_end", 0,            "search for exposures by time (<)", NULL);
    268     psMetadataAddStr(revertwarpedArgs, PS_LIST_TAIL, "-exp_tag",  0,            "search by exp_tag", NULL);
    269     psMetadataAddStr(revertwarpedArgs, PS_LIST_TAIL, "-exp_type",  0,            "search by exp_type", NULL);
    270     psMetadataAddStr(revertwarpedArgs, PS_LIST_TAIL, "-filelevel",  0,            "search by filelevel", NULL);
    271     psMetadataAddStr(revertwarpedArgs, PS_LIST_TAIL, "-reduction",  0,            "search by reduction class", NULL);
    272     psMetadataAddStr(revertwarpedArgs, PS_LIST_TAIL, "-filter",  0,            "search for filter", NULL);
    273     psMetadataAddF32(revertwarpedArgs, PS_LIST_TAIL, "-airmass_min",  0,            "define min airmass", NAN);
    274     psMetadataAddF32(revertwarpedArgs, PS_LIST_TAIL, "-airmass_max",  0,            "define max airmass", NAN);
    275     psMetadataAddF64(revertwarpedArgs, PS_LIST_TAIL, "-ra_min",  0,            "define min", NAN);
    276     psMetadataAddF64(revertwarpedArgs, PS_LIST_TAIL, "-ra_max",  0,            "define max", NAN);
    277     psMetadataAddF64(revertwarpedArgs, PS_LIST_TAIL, "-decl_min",  0,            "define min", NAN);
    278     psMetadataAddF64(revertwarpedArgs, PS_LIST_TAIL, "-decl_max",  0,            "define max", NAN);
    279     psMetadataAddF32(revertwarpedArgs, PS_LIST_TAIL, "-exp_time_min",  0,            "define min", NAN);
    280     psMetadataAddF32(revertwarpedArgs, PS_LIST_TAIL, "-exp_time_max",  0,            "define max", NAN);
    281     psMetadataAddF32(revertwarpedArgs, PS_LIST_TAIL, "-sat_pixel_frac_min",  0,            "define max fraction of saturated pixels", NAN);
    282     psMetadataAddF32(revertwarpedArgs, PS_LIST_TAIL, "-sat_pixel_frac_max",  0,            "define min fraction of saturated pixels", NAN);
    283     psMetadataAddF64(revertwarpedArgs, PS_LIST_TAIL, "-bg_min",  0,            "define max", NAN);
    284     psMetadataAddF64(revertwarpedArgs, PS_LIST_TAIL, "-bg_max",  0,            "define max", NAN);
    285     psMetadataAddF64(revertwarpedArgs, PS_LIST_TAIL, "-bg_stdev_min",  0,            "define max", NAN);
    286     psMetadataAddF64(revertwarpedArgs, PS_LIST_TAIL, "-bg_stdev_max",  0,            "define max", NAN);
    287     psMetadataAddF64(revertwarpedArgs, PS_LIST_TAIL, "-bg_mean_stdev_min",  0,            "define max", NAN);
    288     psMetadataAddF64(revertwarpedArgs, PS_LIST_TAIL, "-bg_mean_stdev_max",  0,            "define max", NAN);
    289     psMetadataAddF64(revertwarpedArgs, PS_LIST_TAIL, "-alt_min",  0,            "define min", NAN);
    290     psMetadataAddF64(revertwarpedArgs, PS_LIST_TAIL, "-alt_max",  0,            "define max", NAN);
    291     psMetadataAddF64(revertwarpedArgs, PS_LIST_TAIL, "-az_min",  0,            "define min", NAN);
    292     psMetadataAddF64(revertwarpedArgs, PS_LIST_TAIL, "-az_max",  0,            "define max", NAN);
    293     psMetadataAddF64(revertwarpedArgs, PS_LIST_TAIL, "-ccd_temp_min",  0,            "define min ccd tempature", NAN);
    294     psMetadataAddF64(revertwarpedArgs, PS_LIST_TAIL, "-ccd_temp_max",  0,            "define max ccd tempature", NAN);
    295     psMetadataAddF64(revertwarpedArgs, PS_LIST_TAIL, "-posang_min",  0,            "define min rotator position angle", NAN);
    296     psMetadataAddF64(revertwarpedArgs, PS_LIST_TAIL, "-posang_max",  0,            "define max rotator position angle", NAN);
    297     psMetadataAddStr(revertwarpedArgs, PS_LIST_TAIL, "-object",  0,            "search by exposure object", NULL);
    298     psMetadataAddF32(revertwarpedArgs, PS_LIST_TAIL, "-solang_min",  0,            "define min solar angle", NAN);
    299     psMetadataAddF32(revertwarpedArgs, PS_LIST_TAIL, "-solang_max",  0,            "define max solar angle", NAN);
    300 
     178    psMetadataAddStr(revertwarpedArgs, PS_LIST_TAIL, "-tess_id",  0,            "search by tessellation ID", NULL);
     179    psMetadataAddStr(revertwarpedArgs, PS_LIST_TAIL, "-reduction",  0,            "search by warpRun reduction class", NULL);
     180    psMetadataAddStr(revertwarpedArgs, PS_LIST_TAIL, "-label",  0,            "search by warpRun label", NULL);
    301181    psMetadataAddS16(revertwarpedArgs, PS_LIST_TAIL, "-code",  0,            "search by fault code", 0);
    302182    psMetadataAddBool(revertwarpedArgs, PS_LIST_TAIL, "-all",  0,            "allow everything to be queued without search terms", false);
     
    323203    psMetadata *pendingcleanupskyfileArgs = psMetadataAlloc();
    324204    psMetadataAddStr(pendingcleanupskyfileArgs, PS_LIST_TAIL, "-label",  0,            "list blocks for specified label", NULL);
    325     psMetadataAddS64(pendingcleanupskyfileArgs, PS_LIST_TAIL, "-warp_id", 0,          "search by warp ID", 0);
     205    psMetadataAddS64(pendingcleanupskyfileArgs, PS_LIST_TAIL, "-warp_id", 0,          "search by warp ID (required)", 0);
    326206    psMetadataAddBool(pendingcleanupskyfileArgs, PS_LIST_TAIL, "-simple",  0,            "use the simple output format", false);
    327207    psMetadataAddU64(pendingcleanupskyfileArgs, PS_LIST_TAIL, "-limit",  0,            "limit result set to N items", 0);
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/gpc1/ppImage.config

    r23352 r23594  
    1414
    1515OLDDARK                 BOOL    FALSE
     16
     17# use the deburned image instead of the raw, if it exists
     18USE.DEBURNED.IMAGE      BOOL    TRUE           # use burntool-repaired image?
    1619
    1720## XXX use these local variations until we are building real detrend images
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/recipes/Makefile.am

    r20196 r23594  
    99        addstar.config \
    1010        masks.config \
     11        masks.16bit.config \
    1112        reductionClasses.mdc \
    1213        rejections.config \
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/recipes/filerules-mef.mdc

    r23352 r23594  
    11### File rules for PHU=FPA, EXT=CHIP (eg, Megacam)
    22### this file specifies compression types for various output files
     3### The image types are defined in fitstypes.mdc
     4### The default type of NONE means no compression
    35
    46### Redirections (MEF)
     
    8486PSASTRO.INPUT.CMP       INPUT    @FILES        CHIP       CMP
    8587PSASTRO.INPUT.CMF       INPUT    @FILES        CHIP       CMF
     88PSASTRO.INPUT.MASK      INPUT    @FILES        CHIP       MASK
     89PSASTRO.REFMASK         INPUT    @DETDB        CHIP       MASK
    8690PSASTRO.WCS             INPUT    @FILES        CHIP       CMF
    8791PSASTRO.MODEL           INPUT    @DETDB        FPA        ASTROM
     92
     93PSASTRO.EXTRACT.ASTROM  INPUT    @FILES        CHIP       CMF
     94PSASTRO.EXTRACT.INPUT   INPUT    @FILES        CHIP       IMAGE
    8895
    8996## files used by pswarp
     
    229236PPSTACK.OUTPUT.VARIANCE OUTPUT {OUTPUT}.wt.fits                  VARIANCE  COMP_WT    FPA        TRUE      NONE
    230237PPSTACK.TARGET.PSF      OUTPUT {OUTPUT}.target.psf               PSF       NONE       CHIP       TRUE      NONE
     238PPSTACK.CONV.KERNEL     OUTPUT {OUTPUT}.{FILE.INDEX}.kernel      SUBKERNEL NONE       FPA        TRUE      NONE
    231239PPSTACK.OUTPUT.JPEG1    OUTPUT {OUTPUT}.b1.jpg                   JPEG      NONE       FPA        TRUE      NONE
    232240PPSTACK.OUTPUT.JPEG2    OUTPUT {OUTPUT}.b2.jpg                   JPEG      NONE       FPA        TRUE      NONE
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/recipes/filerules-simple.mdc

    r23352 r23594  
    11### File rules for PHU=FPA, EXT=NONE
     2### The default type of NONE means no compression
     3
    24
    35PSASTRO.INPUT      STR PSASTRO.INPUT.CMF
     
    1820PPIMAGE.INPUT.PSF       INPUT    @FILES        READOUT    PSF       
    1921PPIMAGE.INPUT.SRC       INPUT    @FILES        READOUT    CMF       
    20 PPIMAGE.MASK            INPUT    @DETDB        CHIP       IMAGE     
     22PPIMAGE.MASK            INPUT    @DETDB        CHIP       MASK
    2123PPIMAGE.BIAS            INPUT    @DETDB        CHIP       IMAGE     
    2224PPIMAGE.DARK            INPUT    @DETDB        CHIP       DARK     
     
    4749PSASTRO.INPUT.CMP       INPUT    @FILES        CHIP       CMP       
    4850PSASTRO.INPUT.CMF       INPUT    @FILES        CHIP       CMF       
     51PSASTRO.INPUT.MASK      INPUT    @FILES        CHIP       MASK
     52PSASTRO.REFMASK         INPUT    @DETDB        CHIP       MASK
    4953PSASTRO.WCS             INPUT    @FILES        CHIP       CMF
    5054PSASTRO.MODEL           INPUT    @DETDB        FPA        ASTROM
     55
     56PSASTRO.EXTRACT.ASTROM  INPUT    @FILES        CHIP       CMF
     57PSASTRO.EXTRACT.INPUT   INPUT    @FILES        CHIP       IMAGE
    5158
    5259## files used by pswarp
     
    181188PPSTACK.OUTPUT.VARIANCE OUTPUT {OUTPUT}.weight.fits  VARIANCE  NONE       FPA        TRUE      NONE
    182189PPSTACK.TARGET.PSF      OUTPUT {OUTPUT}.target.psf   PSF       NONE       CHIP       TRUE      NONE
     190PPSTACK.CONV.KERNEL     OUTPUT {OUTPUT}.{FILE.INDEX}.kernel SUBKERNEL NONE FPA       TRUE      NONE
    183191PPSTACK.OUTPUT.JPEG1    OUTPUT {OUTPUT}.b1.jpg       JPEG      NONE       FPA        TRUE      NONE
    184192PPSTACK.OUTPUT.JPEG2    OUTPUT {OUTPUT}.b2.jpg       JPEG      NONE       FPA        TRUE      NONE
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/recipes/filerules-split.mdc

    r23352 r23594  
    11### File rules for PHU=CHIP, EXT=CELL (eg, GPC1)
    22### this file specifies compression types for various output files
     3### The default type of NONE means no compression
    34
    45# for basic chip analysis, psphot should produce SPLIT output
     
    6162PSASTRO.WCS             INPUT    @FILES        CHIP       WCS
    6263PSASTRO.MODEL           INPUT    @DETDB        FPA        ASTROM
     64
     65PSASTRO.EXTRACT.ASTROM  INPUT    @FILES        CHIP       CMF
     66PSASTRO.EXTRACT.INPUT   INPUT    @FILES        CHIP       IMAGE
    6367
    6468## files used by pswarp
     
    119123PPIMAGE.JPEG1           OUTPUT {OUTPUT}.b1.jpg                   JPEG      NONE       FPA        TRUE      NONE
    120124PPIMAGE.JPEG2           OUTPUT {OUTPUT}.b2.jpg                   JPEG      NONE       FPA        TRUE      NONE
    121                                                                                                        
     125
    122126PPIMAGE.STATS           OUTPUT {OUTPUT}.{CHIP.NAME}.stats        STATS     NONE       CHIP       TRUE      NONE
    123127
     
    197201PPSTACK.OUTPUT.VARIANCE OUTPUT {OUTPUT}.wt.fits                  VARIANCE  COMP_WT    FPA        TRUE      NONE
    198202PPSTACK.TARGET.PSF      OUTPUT {OUTPUT}.target.psf               PSF       NONE       CHIP       TRUE      NONE
     203PPSTACK.CONV.KERNEL     OUTPUT {OUTPUT}.{FILE.INDEX}.kernel      SUBKERNEL NONE       FPA        TRUE      NONE
    199204PPSTACK.OUTPUT.JPEG1    OUTPUT {OUTPUT}.b1.jpg                   JPEG      NONE       FPA        TRUE      NONE
    200205PPSTACK.OUTPUT.JPEG2    OUTPUT {OUTPUT}.b2.jpg                   JPEG      NONE       FPA        TRUE      NONE
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/recipes/jpeg.mdc

    r23352 r23594  
    182182        END
    183183END
     184
     185CTEMAP  METADATA
     186        PPIMAGE.JPEG1            METADATA
     187                COLORMAP        STR     rainbow
     188                SCALE.MODE      STR     VALUE
     189                SCALE.MIN       F32     0.0
     190                SCALE.MAX       F32     5.0
     191        END
     192
     193        PPIMAGE.JPEG2            METADATA
     194                COLORMAP        STR     rainbow
     195                SCALE.MODE      STR     VALUE
     196                SCALE.MIN       F32     0.0
     197                SCALE.MAX       F32     5.0
     198        END
     199END
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/recipes/masks.16bit.config

    r21185 r23594  
    88
    99# Mask values which represent features of the detector
    10 DETECTOR        U8      0x0001          # Something is wrong with the detector
    11 FLAT            U8      0x0002          # Pixel doesn't flat-field properly
    12 DARK            U8      0x0004          # Pixel doesn't dark-subtract properly
    13 BLANK           U8      0x0008          # Pixel doesn't contain valid data
     10DETECTOR        U16     0x0001          # Something is wrong with the detector
     11FLAT            U16     0x0002          # Pixel doesn't flat-field properly
     12DARK            U16     0x0004          # Pixel doesn't dark-subtract properly
     13BLANK           U16     0x0008          # Pixel doesn't contain valid data
     14CTE             U16     0x0010          # Pixel has poor Charge Transfer Efficiency
    1415
    1516# Mask values which represent invalid signal ranges
    16 RANGE           U8      0x0010          # Pixel is out-of-range of linearity
    17 SAT             U8      0x0020          # Pixel is saturated
    18 BAD             U8      0x0040          # Pixel is low (can we rename this 'LOW'?)
     17SAT             U16     0x0020          # Pixel is saturated or non-linear
     18LOW             U16     0x0040          # Pixel is low
     19SUSPECT         U16     0x0080          # Pixel is suspected of being bad
    1920
    2021# Mask values which represent non-astronomical structures
    21 GHOST           U8      0x0100          # Pixel contains an optical ghost
    22 CR              U8      0x0200          # Pixel contains a cosmic ray
    23 STREAK          U8      0x0400          # Pixel contains a streak
     22CR              U16     0x0100          # Pixel contains a cosmic ray
     23SPIKE           U16     0x0200          # Pixel contains a diffraction spike
     24GHOST           U16     0x0400          # Pixel contains an optical ghost
     25STREAK          U16     0x0800          # Pixel contains a streak
     26STARCORE        U16     0x1000          # Pixel contains a bright star core
    2427
    2528# Mask values which identify pixels badly affected by convolutions and interpolations
    26 BAD.WARP        U8      0x1000          # Pixel is bad after convolution with a bad pixel
    27 POOR.WARP       U8      0x2000          # Pixel is poor after convolution with a bad pixel
     29CONV.BAD        U16     0x2000          # Pixel is bad after convolution with a bad pixel
     30CONV.POOR       U16     0x4000          # Pixel is poor after convolution with a bad pixel
    2831
     32# Spare value for temporary marking
     33# MARK          U16     0x8000          # Pixel is temporarily marked
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/recipes/masks.config

    r20631 r23594  
    1414FLAT            U8      0x04            # Pixel doesn't flat-field properly =4
    1515DARK            U8      0x40            # Pixel doesn't dark-subtract properly =64
     16CTE             U8      0x40            # Pixel has poor cte
     17
    1618# Filling in the rest with whatever makes some sense
    1719BLANK           U8      0x01            # Pixel doesn't contain valid data
     
    2426GHOST           U8      0x20            # Pixel contains an optical ghost
    2527STREAK          U8      0x20            # Pixel contains a streak
     28
     29SPIKE           U8      0x20            # Pixel contains a diffraction spike
     30STARCORE        U8      0x20            # Pixel contains a streak
    2631
    2732###### The following values are what I'm aiming to have in the long term (PAP, 2008-09-09)
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/recipes/ppImage.config

    r23352 r23594  
    1919ASTROM.MOSAIC      BOOL    FALSE           # Astrometry for mosaic?
    2020BACKGROUND         BOOL    FALSE           # Subtract model background?
     21CHECK.CTE          BOOL    FALSE           # measure CTE errors?
     22USE.DEBURNED.IMAGE BOOL    FALSE           # use burntool-repaired image?
    2123
    2224# output data formats to save
     
    7779BIN2.XBIN               S32     16
    7880BIN2.YBIN               S32     16
     81
     82CTE.XBIN                S32     20
     83CTE.YBIN                S32     20
    7984
    8085PPIMAGE.JPEG1  METADATA
     
    470475  BASE.FITS        BOOL    TRUE            # Save base detrended image?
    471476  BASE.MASK.FITS   BOOL    TRUE            # Save base detrended image?
    472   BASE.VARIANCE.FITS BOOL    TRUE            # Save base detrended image?
    473   CHIP.FITS        BOOL    FALSE           # Save chip-mosaic-ed image?
    474   CHIP.MASK.FITS   BOOL    FALSE           # Save chip-mosaic-ed image?
    475   CHIP.VARIANCE.FITS BOOL    FALSE           # Save chip-mosaic-ed image?
     477  BASE.VARIANCE.FITS BOOL  TRUE            # Save base detrended image?
     478  CHIP.FITS        BOOL    FALSE           # Save chip-mosaic-ed image?
     479  CHIP.MASK.FITS   BOOL    FALSE           # Save chip-mosaic-ed image?
     480  CHIP.VARIANCE.FITS BOOL  FALSE           # Save chip-mosaic-ed image?
    476481  OVERSCAN         BOOL    TRUE            # Overscan subtraction
    477482  BIAS             BOOL    TRUE            # Bias subtraction
     
    14171422END
    14181423
     1424# generate CTE map image
     1425PPIMAGE_CTEMAP     METADATA
     1426  BASE.FITS        BOOL    TRUE            # Save base image?
     1427  BASE.MASK.FITS   BOOL    TRUE            # Save base detrended image?
     1428  BASE.VARIANCE.FITS BOOL  TRUE            # Save base detrended image?
     1429  CHIP.FITS        BOOL    FALSE           # Save chip-mosaic-ed image?
     1430  CHIP.MASK.FITS   BOOL    FALSE           # Save chip-mosaic-ed image?
     1431  CHIP.VARIANCE.FITS BOOL  FALSE           # Save chip-mosaic-ed image?
     1432  OVERSCAN         BOOL    FALSE           # Overscan subtraction
     1433  OVERSCAN         BOOL    TRUE            # Overscan subtraction
     1434  BIAS             BOOL    TRUE            # Bias subtraction
     1435  DARK             BOOL    TRUE            # Dark subtraction
     1436  SHUTTER          BOOL    FALSE           # Shutter correction
     1437  FLAT             BOOL    TRUE            # Flat-field normalisation
     1438  MASK             BOOL    FALSE           # Mask bad pixels
     1439  FRINGE           BOOL    FALSE           # Fringe subtraction
     1440  PHOTOM           BOOL    FALSE           # Source identification and photometry
     1441  ASTROM.CHIP      BOOL    FALSE           # Astrometry per chip?
     1442  ASTROM.MOSAIC    BOOL    FALSE           # Astrometry for mosaic?
     1443  BIN1.FITS        BOOL    TRUE            # Save 1st binned chip image?
     1444  BIN2.FITS        BOOL    TRUE            # Save 2nd binned chip image?
     1445  CHECK.CTE        BOOL    TRUE            # measure CTE errors?
     1446END
     1447
    14191448# For SDSS cameras
    14201449PPIMAGE_OA_SOFT   METADATA
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/recipes/ppMerge.config

    r21370 r23594  
    1414FRINGE.XSMOOTH  S32     5               # Number of smoothing regions in x
    1515FRINGE.YSMOOTH  S32     11              # Number of smoothing regions in y
     16CTE.MIN         F32     0.2             # regions lower than this in the CTE image are masked
    1617SHUTTER.SIZE    S32     128             # Size for shutter measurement regions
    1718MASK.SUSPECT    F32     5.0             # Threshold for suspect pixels (sigma)
     
    9495END
    9596
     97# CTEMASK generation combines the images like a flat or bias (mean after outlier rejection),
     98# but it then sets a mask based on the resulting data values (using CTE.MIN)
     99PPMERGE_CTEMASK METADATA
     100        REJ             F32     3.0             # Rejection threshold (sigma)
     101        ITER            S32     2               # Number of rejection iterations
     102        FRACHIGH        F32     0.0             # Fraction of high pixels to reject immediately
     103        FRACLOW         F32     0.0             # Fraction of low pixels to reject immediately
     104        VARIANCES       BOOL    FALSE           # Use image variances?
     105        COMBINE         STR     CLIPPED         # Statistic to use for combination:
     106        CTE.MIN         F32     0.2             # regions lower than this in the CTE image are masked
     107        MASK.SET.VALUE  STR     CTE             # set this bit in the output mask
     108END
     109
    96110# Shutter generation --- already included in default, above
    97111PPMERGE_SHUTTER METADATA
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/recipes/ppSim.config

    r20911 r23594  
    6666
    6767GALAXY.MODEL     STR    PS_MODEL_GAUSS
     68
     69BADCTE          BOOL    FALSE           # create a region of 'bad CTE'?
     70BADCTE.REGION   STR     [0:200,0:200]   # region of 'bad CTE'
     71BADCTE.SIGMA    F32     2.0             # 'bad CTE' smoothing scale
     72BADCTE.NSIGMA   S32     2               # 'bad CTE' smoothing scale
    6873
    6974BADPIX.SEED     U64     123456789       # Seed for RNG in creating deterministic bad pixels
     
    185190    BADPIX.MODE STR     NAN             # Mode for bad pixels: RANDOM|NAN
    186191END
     192
     193# recipe for a CTE test
     194BADCTE.TEST     METADATA
     195  BADCTE BOOL TRUE
     196END
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/recipes/ppStack.config

    r23352 r23594  
    11# Recipe configuration for ppStack (image combination)
    22
     3CONVOLVE        BOOL    TRUE            # Convolve images when stacking?
    34ITER            S32     1               # Number of rejection iterations
    45COMBINE.REJ     F32     3.0             # Rejection threshold in combination (sigma)
    56COMBINE.SYS     F32     0.08            # Relative systematic error in combination
    67COMBINE.DISCARD F32     0.2             # Discard fraction for Olympic weighted mean
    7 MASK.VAL        STR     MASK.VALUE,BAD.WARP     # Mask value of input bad pixels
     8MASK.VAL        STR     MASK.VALUE,CONV.BAD     # Mask value of input bad pixels
    89MASK.BAD        STR     BLANK           # Mask value to give bad pixels
    9 MASK.POOR       STR     POOR.WARP       # Mask value to give poor pixels
     10MASK.POOR       STR     CONV.POOR       # Mask value to give poor pixels
    1011POOR.FRACTION   F32     0.01            # Maximum fraction of bad variance for poor pixels
    1112THRESHOLD.MASK  F32     0.5             # Threshold for mask deconvolution (0..1)
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/recipes/ppSub.config

    r23352 r23594  
    1515
    1616# EAM : we now ignore these: BAD.WARP is always bad, POOR.WARP is always defined
    17 MASK.IN         STR     MASK.VALUE,BAD.WARP     # Mask value for input
    18 MASK.BAD        STR     BLANK           # Mask value to give bad pixels
    19 MASK.POOR       STR     POOR.WARP       # Mask value to give poor pixels
     17MASK.IN         STR     MASK.VALUE,CONV.BAD     # Mask value for input
     18MASK.BAD        STR     CONV.BAD        # Mask value to give bad pixels
     19MASK.POOR       STR     CONV.POOR       # Mask value to give poor pixels
    2020
    2121POOR.FRACTION   F32     0.10            # Maximum fraction of bad weight for poor pixels
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/recipes/psastro.config

    r20797 r23594  
    124124REFSTAR_MASK_BLEED_MAG_SLOPE    F32   5.0
    125125
     126EXTRACT_MAX_MAG                 F32 -15.0
     127
    126128# 2MASS default configuration (use 2MASS_J as ref magnitude)
    127129PSASTRO.CATDIR                STR      2MASS
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/recipes/reductionClasses.mdc

    r23352 r23594  
    111111        FLATMASK_JPEG_RESID     STR     FLAT_RESID
    112112
     113        CTEMASK_PROCESS         STR     PPIMAGE_CTEMAP
     114        CTEMASK_RESID           STR     PPIMAGE_M
     115        CTEMASK_VERIFY          STR     PPIMAGE_M
     116        CTEMASK_STACK           STR     PPMERGE_CTEMASK
     117        CTEMASK_JPEG_IMAGE      STR     CTEMAP
     118        CTEMASK_JPEG_RESID      STR     CTEMAP
     119
    113120        FRINGE_PROCESS          STR     PPIMAGE_OBDSF
    114121        FRINGE_RESID            STR     PPIMAGE_R
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/recipes/rejections.config

    r19379 r23594  
    361361
    362362FLATMASK METADATA
     363  FILTER             STR  *
     364  EXPECTED           F32  0.0
     365  IMFILE.MEAN        F32  0.0
     366  IMFILE.STDEV       F32  0.0
     367  IMFILE.MEANSTDEV   F32  0.0
     368  IMFILE.SKEWNESS    F32  0.0
     369  IMFILE.KURTOSIS    F32  0.0
     370  IMFILE.SNR         F32  0.0
     371  IMFILE.BIN.STDEV   F32  0.0
     372  IMFILE.BIN.SNR     F32  0.0
     373  IMFILE.FLUX        F32  0.0
     374  EXP.MEAN           F32  0.0
     375  EXP.STDEV          F32  0.0
     376  EXP.MEANSTDEV      F32  0.0
     377  EXP.SNR            F32  0.0
     378  EXP.BIN.STDEV      F32  0.0
     379  EXP.BIN.SNR        F32  0.0
     380  EXP.FLUX           F32  0.0
     381  ENSEMBLE.MEAN      F32  0.0
     382  ENSEMBLE.STDEV     F32  0.0
     383  ENSEMBLE.MEANSTDEV F32  0.0
     384END
     385
     386CTEMASK METADATA
    363387  FILTER             STR  *
    364388  EXPECTED           F32  0.0
  • branches/cnb_branches/cnb_branch_20090301/ippconfig/system.config

    r20387 r23594  
    3636
    3737RECIPES         METADATA                # Site-level recipes
    38         MASKS           STR             recipes/masks.config    # Mask values
     38        MASKS           STR             recipes/masks.16bit.config      # Mask values
    3939        REJECTIONS      STR             recipes/rejections.config # Rejection for detrend creation
    4040        PPIMAGE         STR             recipes/ppImage.config  # Image reduction
  • branches/cnb_branches/cnb_branch_20090301/operations/registration/input

    r22426 r23594  
    6666    controller host add ipp007 -threads $1
    6767# ipp008 is flaky
    68     controller host add ipp009 -threads $1
     68# ipp009 is registration server
    6969    controller host add ipp010 -threads $1
    7070    controller host add ipp011 -threads $1
     
    104104    controller host add ipp007
    105105# ipp008 is flaky
    106     controller host add ipp009
     106# ipp009 is registration server
    107107    controller host add ipp010
    108108    controller host add ipp011
  • branches/cnb_branches/cnb_branch_20090301/operations/registration/ptolemy.rc

    r22425 r23594  
    22PANTASKS_SERVER_STDOUT  pantasks.stdout.log
    33PANTASKS_SERVER_STDERR  pantasks.stderr.log
    4 PANTASKS_SERVER         ipp008
     4PANTASKS_SERVER         ipp009
    55PASSWORD                foobar
    66
  • branches/cnb_branches/cnb_branch_20090301/ppImage

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

    r23352 r23594  
    2121        ppMergeFileGroup.c      \
    2222        ppMergeReadChunk.c      \
    23         ppMergeLoop_Threaded.c  \
     23        ppMergeLoop.c           \
    2424        ppMergeSetThreads.c     \
    2525        ppMergeMask.c           \
  • branches/cnb_branches/cnb_branch_20090301/ppMerge/src/ppMerge.c

    r23352 r23594  
    5555      case PPMERGE_TYPE_FLAT:
    5656      case PPMERGE_TYPE_FRINGE:
     57      case PPMERGE_TYPE_CTEMASK:
    5758        if (!ppMergeScaleZero(config)) {
    5859            psErrorStackPrint(stderr, "Error getting scale and zero-points.");
  • branches/cnb_branches/cnb_branch_20090301/ppMerge/src/ppMerge.h

    r23352 r23594  
    4040    PPMERGE_TYPE_DARK,                  ///< (Multi-)Dark frame
    4141    PPMERGE_TYPE_MASK,                  ///< Mask frame
     42    PPMERGE_TYPE_CTEMASK,               ///< CTE Mask based on flat variance
    4243    PPMERGE_TYPE_SHUTTER,               ///< Shutter frame
    4344    PPMERGE_TYPE_FLAT,                  ///< Flat-field frame (dome or sky)
  • branches/cnb_branches/cnb_branch_20090301/ppMerge/src/ppMergeArguments.c

    r21365 r23594  
    170170    psMetadataAddS32(arguments, PS_LIST_TAIL, "-fringe-ysmooth", 0, "Number of smoothing regions in y", 0);
    171171
     172    /** CTEMASK construction parameters */
     173    psMetadataAddF32(arguments, PS_LIST_TAIL, "-cte-min", 0, "min allowed value for good CTE", NAN);
     174
    172175    /** Shutter construction parameters */
    173176    psMetadataAddS32(arguments, PS_LIST_TAIL, "-shutter-size", 0, "Size for shutter measurement regions", 0);
     
    268271      goto VALID;
    269272    }
     273    if (strcasecmp(typeStr, "CTEMASK") == 0) {
     274      type = PPMERGE_TYPE_CTEMASK;
     275      goto VALID;
     276    }
    270277    if (strcasecmp(typeStr, "MASK") == 0 ||
    271278        strcasecmp(typeStr, "DARKMASK") == 0 ||
     
    314321    VALUE_ARG_RECIPE_INT("-fringe-xsmooth", "FRINGE.XSMOOTH", S32, 0);
    315322    VALUE_ARG_RECIPE_INT("-fringe-ysmooth", "FRINGE.YSMOOTH", S32, 0);
     323
     324    /** CTEMASK construction parameters */
     325    VALUE_ARG_RECIPE_FLOAT("-cte-min",      "CTE.MIN",        F32);
    316326
    317327    /** Shutter construction parameters */
  • branches/cnb_branches/cnb_branch_20090301/ppMerge/src/ppMergeCamera.c

    r21365 r23594  
    326326        fileType = PM_FPA_FILE_MASK;
    327327        break;
     328      case PPMERGE_TYPE_CTEMASK:
     329        fileType = PM_FPA_FILE_MASK;
     330        break;
    328331      case PPMERGE_TYPE_SHUTTER:
    329332        fileType = PM_FPA_FILE_IMAGE;
  • branches/cnb_branches/cnb_branch_20090301/ppMerge/src/ppMergeFiles.c

    r21365 r23594  
    209209        outSuffix = "MASK";
    210210        break;
     211      case PPMERGE_TYPE_CTEMASK:
     212        outSuffix = "MASK";
     213        break;
    211214      case PPMERGE_TYPE_SHUTTER:
    212215        outSuffix = "SHUTTER";
  • branches/cnb_branches/cnb_branch_20090301/ppMerge/src/ppMergeScaleZero.c

    r23352 r23594  
    3535      case PPMERGE_TYPE_BIAS:
    3636      case PPMERGE_TYPE_DARK:
     37      case PPMERGE_TYPE_CTEMASK:
    3738        // Nothing to measure
    3839        return true;
  • branches/cnb_branches/cnb_branch_20090301/ppSim/src/Makefile.am

    r23352 r23594  
    4545        ppSimRandomGaussian.c     \
    4646        ppSimBadPixels.c          \
     47        ppSimBadCTE.c             \
    4748        ppSimVersion.c
    4849
  • branches/cnb_branches/cnb_branch_20090301/ppSim/src/ppSim.h

    r23352 r23594  
    6767} ppSimGalaxy;
    6868
    69 ppSimStar *ppSimStarAlloc ();
    70 ppSimGalaxy *ppSimGalaxyAlloc ();
     69ppSimStar *ppSimStarAlloc(void);
     70ppSimGalaxy *ppSimGalaxyAlloc(void);
    7171
    7272/// Parse command-line arguments
     
    135135
    136136
     137// add a bad CTE region
     138bool ppSimBadCTE(psImage *image,        // Signal image, modified and returned
     139                 const pmConfig *config // configuration
     140  );
     141
    137142/// Add bad pixels to an image
    138143bool ppSimBadPixels(pmReadout *readout, ///< Readout for which to generate bad pixels
     
    184189double ppSimRandomGaussian (const psRandom *rnd, double mean, double sigma);
    185190double ppSimRandomGaussianNorm (const psRandom *rnd);
    186 void ppSimRandomGaussianFree();
     191void ppSimRandomGaussianFree(void);
    187192
    188193bool ppSimPhotomFiles (pmConfig *config, pmFPAfile *fakeFile, pmFPAfile *forceFile);
  • branches/cnb_branches/cnb_branch_20090301/ppSim/src/ppSimLoadSpots.c

    r18047 r23594  
    5757
    5858    // load refstars from the catalog
    59     psArray *spots = psastroLoadRefstars(config);
     59    psArray *spots = psastroLoadRefstars(config, "PSASTRO.INPUT");
    6060    if (!spots || spots->n == 0) {
    6161        psError(PS_ERR_UNKNOWN, false, "Unable to find reference stars.");
  • branches/cnb_branches/cnb_branch_20090301/ppSim/src/ppSimLoadStars.c

    r20040 r23594  
    4141    psMetadataAdd(astroRecipe, PS_LIST_TAIL, "DEC_MIN", PS_DATA_F32 | PS_META_REPLACE, "", dec0 - radius);
    4242    psMetadataAdd(astroRecipe, PS_LIST_TAIL, "DEC_MAX", PS_DATA_F32 | PS_META_REPLACE, "", dec0 + radius);
    43     psArray *refStars = psastroLoadRefstars(config);
     43    psArray *refStars = psastroLoadRefstars(config, "PSASTRO.INPUT");
    4444    if (!refStars) {
    4545        psError(PS_ERR_UNKNOWN, false, "Unable to find reference stars.");
  • branches/cnb_branches/cnb_branch_20090301/ppSim/src/ppSimLoop.c

    r23352 r23594  
    154154            done:
    155155                if (!ppSimAddNoise(readout->image, readout->variance, cell, config, rng)) ESCAPE (PS_ERR_UNKNOWN, "problem adding noise");
     156
     157                if (!ppSimBadCTE(readout->image, config)) ESCAPE (PS_ERR_UNKNOWN, "problem inducing bad cte");
     158
    156159                if (!ppSimSaturate(readout, config)) ESCAPE (PS_ERR_UNKNOWN, "problem setting saturation levels");
    157160
  • branches/cnb_branches/cnb_branch_20090301/ppSim/src/ppSimRandomGaussian.c

    r18011 r23594  
    2929
    3030/* integrate a gaussian from -5 sigma to +5 sigma */
    31 void p_ppSimRandomGaussianInit () {
    32  
     31void p_ppSimRandomGaussianInit (void) {
     32
    3333  int i;
    3434  long A, B;
    3535  double val, x, dx, dx1, dx2, dx3, df;
    3636  double mean, sigma;
    37  
     37
    3838  /* no need to generate this if it already exists */
    3939  if (gaussint) return;
     
    4242  for (B = 0; A == time(NULL); B++);
    4343  srand48(B);
    44  
     44
    4545  Ngaussint = 0x1000;
    4646  ppSimRandomGaussianAlloc (Ngaussint + 1);
     
    5353  mean = 0.0;
    5454  sigma = 1.0;
    55  
     55
    5656  for (i = 0, x = -7.0; (i < Ngaussint) && (x < 7.0); x += dx)  {
    57     df = (3.0*p_ppSimGaussian(x    , mean, sigma) + 
     57    df = (3.0*p_ppSimGaussian(x    , mean, sigma) +
    5858          9.0*p_ppSimGaussian(x+dx1, mean, sigma) +
    59           9.0*p_ppSimGaussian(x+dx2, mean, sigma) + 
     59          9.0*p_ppSimGaussian(x+dx2, mean, sigma) +
    6060          3.0*p_ppSimGaussian(x+dx3, mean, sigma)) * (dx1/8.0);
    6161    val += df;
     
    6767}
    6868
    69 // XXX we are using drand48() rather than the random var supplied by rnd 
     69// XXX we are using drand48() rather than the random var supplied by rnd
    7070double ppSimRandomGaussian (const psRandom *rnd, double mean, double sigma) {
    71  
     71
    7272  int i;
    7373  double y;
    74  
     74
    7575  if (gaussint == NULL) {
    7676      p_ppSimRandomGaussianInit ();
     
    8080  i = Ngaussint*y;
    8181  y = gaussint[i]*sigma + mean;
    82  
     82
    8383  return (y);
    84  
     84
    8585}
    86  
    87 // XXX we are using drand48() rather than the random var supplied by rnd 
     86
     87// XXX we are using drand48() rather than the random var supplied by rnd
    8888double ppSimRandomGaussianNorm (const psRandom *rnd) {
    89  
     89
    9090  int i;
    9191  double y;
    92  
     92
    9393  if (gaussint == NULL) {
    9494      p_ppSimRandomGaussianInit ();
     
    9898  i = Ngaussint*y;
    9999  y = gaussint[i];
    100  
     100
    101101  return (y);
    102102}
  • branches/cnb_branches/cnb_branch_20090301/ppSim/src/ppSimStars.c

    r17557 r23594  
    66}
    77
    8 ppSimStar *ppSimStarAlloc () {
     8ppSimStar *ppSimStarAlloc(void) {
    99
    1010    ppSimStar *star = (ppSimStar *) psAlloc(sizeof(ppSimStar));
     
    1919}
    2020
    21 ppSimGalaxy *ppSimGalaxyAlloc () {
     21ppSimGalaxy *ppSimGalaxyAlloc(void) {
    2222
    2323    ppSimGalaxy *galaxy = (ppSimGalaxy *) psAlloc(sizeof(ppSimGalaxy));
  • branches/cnb_branches/cnb_branch_20090301/ppStack

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

    r23352 r23594  
    2929        ppStackPrepare.c        \
    3030        ppStackConvolve.c       \
     31        ppStackCombinePrepare.c \
    3132        ppStackCombineInitial.c \
    3233        ppStackReject.c         \
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStack.h

    r23352 r23594  
    77#include <pslib.h>
    88#include <psmodules.h>
     9
     10#include "ppStackOptions.h"
    911
    1012// Mask values for inputs
     
    106108/// Convolve image to match specified seeing
    107109bool ppStackMatch(pmReadout *readout,   // Readout to be convolved; replaced with output
    108                   psArray **regions,    // Array of regions used in each PSF matching, returned
    109                   psArray **kernels,    // Array of kernels used in each PSF matching, returned
    110                   float *chi2,          // Chi^2 from the stamps
    111                   float *weighting,     // Stack weighting (1/noise^2)
    112                   psArray *sources,     // Array of sources
    113                   const pmPSF *psf,     // Target PSF
    114                   psRandom *rng,        // Random number generator
     110                  ppStackOptions *options, // Options for stacking
     111                  int index,            // Index of image to match
    115112                  const pmConfig *config // Configuration
    116113    );
     
    120117///
    121118/// Corrects the source PSF photometry to a common system.  Return the sum of the exposure times.
    122 float ppStackSourcesTransparency(const psArray *sourceLists, // Sources for each input
    123                                  psVector *inputMask, // Indicates bad input
    124                                  const pmFPAview *view, // View to readout
    125                                  const pmConfig *config // Configuration
     119bool ppStackSourcesTransparency(ppStackOptions *options, // Stacking options
     120                                const pmFPAview *view, // View to readout
     121                                const pmConfig *config // Configuration
    126122    );
    127123
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackArguments.c

    r23352 r23594  
    2020    fprintf(stderr, "\nPan-STARRS Image combination\n\n");
    2121    fprintf(stderr,
    22             "Usage: %s INPUTS.mdc OUTPUT_ROOT [-sources STAMPS.cmf | -stamps STAMPS.dat]\n"
     22            "Usage: %s -input INPUTS.mdc OUTPUT_ROOT [-sources STAMPS.cmf | -stamps STAMPS.dat]\n"
    2323            "where INPUTS.mdc contains various METADATAs, each with:\n"
    2424            "\tIMAGE(STR):     Image filename\n"
     
    2626            "\tVARIANCE(STR):  Variance map filename\n"
    2727            "\tPSF(STR):       PSF filename\n"
    28             "\tSOURCES(STR):   Sources filename\n"
    29             "\tWEIGHTING(F32): Relative weighting to be applied\n",
     28            "\tSOURCES(STR):   Sources filename\n",
    3029            program);
    3130    fprintf(stderr, "\n");
     
    137136        psArgumentRemove(argNum, &argc, argv);
    138137    }
    139 
    140138
    141139    psMetadata *arguments = config->arguments; // Command-line arguments
     
    187185    psMetadataAddBool(arguments, PS_LIST_TAIL, "-visual", 0, "visualisation", false);
    188186
    189     if (argc == 1 || !psArgumentParse(arguments, &argc, argv) || argc != 3) {
     187    if (argc == 1) {
    190188        usage(argv[0], arguments, config);
    191189    }
     190
     191    if ((argNum = psArgumentGet(argc, argv, "-input"))) {
     192        psArgumentRemove(argNum, &argc, argv);
     193        if (argNum >= argc) {
     194            usage(argv[0], arguments, config);
     195        }
     196
     197        unsigned int numBad = 0;                     // Number of bad lines
     198        psMetadata *inputs = psMetadataConfigRead(NULL, &numBad, argv[argNum], false); // Input file info
     199        if (!inputs || numBad > 0) {
     200            psError(PS_ERR_BAD_PARAMETER_VALUE, false, "Unable to cleanly read MDC file with inputs.");
     201            return false;
     202        }
     203        psMetadataAddMetadata(arguments, PS_LIST_TAIL, "INPUTS", 0, "Metadata with input details", inputs);
     204        psFree(inputs);
     205
     206        psArgumentRemove(argNum, &argc, argv);
     207    }
     208
     209    if (!psArgumentParse(arguments, &argc, argv) || argc != 2) {
     210        usage(argv[0], arguments, config);
     211    }
     212
     213    psMetadataAddStr(arguments, PS_LIST_TAIL, "OUTPUT", 0, "Root name of the output image list", argv[1]);
    192214
    193215    const char *stampsName = psMetadataLookupStr(NULL, arguments, "-stamps"); // Name of stamps file
    194216    psMetadataAddStr(arguments, PS_LIST_TAIL, "STAMPS", 0, "Stamps file", stampsName);
    195 
    196     unsigned int numBad = 0;                     // Number of bad lines
    197     psMetadata *inputs = psMetadataConfigRead(NULL, &numBad, argv[1], false); // Information about inputs
    198     if (!inputs || numBad > 0) {
    199         psError(PS_ERR_BAD_PARAMETER_VALUE, false, "Unable to cleanly read MDC file with inputs.");
    200         return false;
    201     }
    202     psMetadataAddMetadata(arguments, PS_LIST_TAIL, "INPUTS", 0, "Metadata with input details", inputs);
    203     psFree(inputs);
    204     psMetadataAddStr(arguments, PS_LIST_TAIL, "OUTPUT", 0, "Root name of the output image list", argv[2]);
    205217
    206218    valueArgStr(arguments, "-stats", "STATS", arguments);
     
    295307    psTrace("ppStack", 1, "Done parsing arguments\n");
    296308
    297     // Dump configuration, now that's it's settled
    298     bool status;
    299     psString dump_file =  psMetadataLookupStr(&status, config->arguments, "DUMP_CONFIG");
    300     if (dump_file) {
    301         pmConfigCamerasCull(config, NULL);
    302         pmConfigRecipesCull(config, "PPSTACK,PPSUB,PPSTATS,PSPHOT,MASKS,JPEG");
    303 
    304         pmFPAfile *input = psMetadataLookupPtr(NULL, config->files, "PPSTACK.INPUT"); // Input file
    305         pmConfigDump(config, input->fpa, dump_file);
    306     }
     309    pmConfigCamerasCull(config, NULL);
     310    pmConfigRecipesCull(config, "PPSTACK,PPSUB,PPSTATS,PSPHOT,MASKS,JPEG");
    307311
    308312    return true;
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackCamera.c

    r21366 r23594  
    1111#include "ppStack.h"
    1212
    13 
    14 #if 0
    15 // Define an output convolved image file
    16 static pmFPAfile *defineOutputConvolved(const char *name, // FPA file name
    17                                         pmFPA *fpa, // FPA to bind
    18                                         const pmConfig *config, // Configuration
    19                                         pmFPAfileType type // Expected type
    20     )
     13// Define a file
     14static pmFPAfile *defineFile(pmConfig *config, // Configuration
     15                             pmFPAfile *bind, // File to which to bind
     16                             const char *name, // Name of file rule
     17                             const char *filename, // Name of file
     18                             pmFPAfileType type // Type of file
     19                             )
    2120{
    22     pmFPAfile *file = pmFPAfileDefineOutput(config, fpa, name);
    23     if (!file) {
    24         psError(PS_ERR_UNKNOWN, false, "Unable to define output convolved file %s", name);
     21
     22    psArray *dummy = psArrayAlloc(1);   // Dummy array of filenames for this FPA
     23    dummy->data[0] = psStringCopy(filename);
     24    psMetadataAddArray(config->arguments, PS_LIST_TAIL, "FILENAMES", PS_META_REPLACE,
     25                       "Filenames for file rule definition", dummy);
     26    psFree(dummy);
     27
     28    bool found = false;             // Found the file?
     29    pmFPAfile *file = bind ? pmFPAfileBindFromArgs(&found, bind, config, name, "FILENAMES") :
     30        pmFPAfileDefineFromArgs(&found, config, name, "FILENAMES");
     31    if (!file || !found) {
     32        psError(PS_ERR_UNKNOWN, false, "Unable to define file %s from %s", name, filename);
    2533        return NULL;
    2634    }
    27     if (file->type != PM_FPA_FILE_IMAGE) {
    28         psError(PS_ERR_IO, true, "PPSTACK.OUTCONV is not of type %s", pmFPAfileStringFromType(type));
     35    if (file->type != type) {
     36        psError(PS_ERR_IO, true, "%s is not of type %s", name, pmFPAfileStringFromType(type));
    2937        return NULL;
    3038    }
     
    3341}
    3442
    35 // Define an input convolved image file, using the output as a basis
    36 static pmFPAfile *defineInputConvolved(const char *inputName, // Input FPA file name
    37                                        pmFPAfile *outFile, // Corresponding output FPA file
    38                                        pmConfig *config, // Configuration
    39                                        pmFPAfileType type // Expected type
    40     )
    41 {
    42     pmFPAview *view = pmFPAviewAlloc(0); // View into sky cells
    43     view->chip = view->cell = view->readout = 0;
    44 
    45     psString imageName = pmFPANameFromRule(outFile->filerule, outFile->fpa, view);
    46     psArray *imageNames = psArrayAlloc(1);
    47     imageNames->data[0] = imageName;
    48     psMetadataAddArray(config->arguments, PS_LIST_TAIL, "INCONV.FILENAMES", PS_META_REPLACE,
    49                        "Filenames of input convolved image files", imageNames);
    50     psFree(imageNames);
    51     bool found = false;                 // Found the file?
    52     pmFPAfile *imageFile = pmFPAfileDefineFromArgs(&found, config, "PPSTACK.INCONV",
    53                                                    "INCONV.FILENAMES");
    54     psMetadataRemoveKey(config->arguments, "INCONV.FILENAMES");
    55     if (!imageFile || !found) {
    56         psError(PS_ERR_UNKNOWN, false, "Unable to define %s file", inputName);
    57         return NULL;
    58     }
    59     if (imageFile->type != type) {
    60         psError(PS_ERR_IO, true, "PPSTACK.INCONV is not of type %s",
    61                 pmFPAfileStringFromType(type));
    62         return NULL;
    63     }
    64 
    65     return imageFile;
    66 }
    67 #endif
    68 
    6943
    7044
    7145bool ppStackCamera(pmConfig *config)
    7246{
    73     bool haveVariances = false;           // Do we have variance maps?
     47    int num = 0;                        // Number of inputs
     48    bool haveVariances = false;         // Do we have variance maps?
    7449    bool havePSFs = false;              // Do we have PSFs?
    7550
    76     psMetadata *inputs = psMetadataLookupMetadata(NULL, config->arguments, "INPUTS"); // The inputs info
    77     psMetadataIterator *iter = psMetadataIteratorAlloc(inputs, PS_LIST_HEAD, NULL); // Iterator
    78     psMetadataItem *item;               // Item from iteration
    79     int i = 0;                          // Counter
    80     while ((item = psMetadataGetAndIncrement(iter))) {
    81         if (item->type != PS_DATA_METADATA) {
    82             psError(PS_ERR_BAD_PARAMETER_TYPE, true,
    83                     "Component %s of the input metadata is not of type METADATA", item->name);
    84             psFree(iter);
    85             return false;
    86         }
    87 
    88         psMetadata *input = item->data.md; // The input metadata of interest
    89 
    90         psString image = psMetadataLookupStr(NULL, input, "IMAGE"); // Name of image
    91         if (!image || strlen(image) == 0) {
    92             psError(PS_ERR_BAD_PARAMETER_VALUE, true, "Component %s lacks IMAGE of type STR", item->name);
    93             psFree(iter);
    94             return false;
    95         }
    96 
    97         bool mdok;
    98         psString mask = psMetadataLookupStr(&mdok, input, "MASK"); // Name of mask
    99         psString variance = psMetadataLookupStr(&mdok, input, "VARIANCE"); // Name of variance map
    100         psString psf = psMetadataLookupStr(&mdok, input, "PSF"); // Name of PSF
    101         psString sources = psMetadataLookupStr(&mdok, input, "SOURCES"); // Name of sources
    102 
    103         // Add the image file
    104         psArray *imageFiles = psArrayAlloc(1); // Array of filenames for this FPA
    105         imageFiles->data[0] = psMemIncrRefCounter(image);
    106         psMetadataAddArray(config->arguments, PS_LIST_TAIL, "IMAGE.FILENAMES", PS_META_REPLACE,
    107                            "Filenames of image files", imageFiles);
    108         psFree(imageFiles);
    109 
    110         bool found = false;             // Found the file?
    111         pmFPAfile *imageFile = pmFPAfileDefineFromArgs(&found, config, "PPSTACK.INPUT", "IMAGE.FILENAMES");
    112         if (!imageFile || !found) {
    113             psError(PS_ERR_UNKNOWN, false, "Unable to define file from image %d (%s)", i, image);
    114             return false;
    115         }
    116         if (imageFile->type != PM_FPA_FILE_IMAGE) {
    117             psError(PS_ERR_IO, true, "PPSTACK.INPUT is not of type IMAGE");
    118             return false;
    119         }
    120 
    121         // Optionally add the mask file
    122         if (mask && strlen(mask) > 0) {
    123             psArray *maskFiles = psArrayAlloc(1); // Array of filenames for this FPA
    124             maskFiles->data[0] = psMemIncrRefCounter(mask);
    125             psMetadataAddArray(config->arguments, PS_LIST_TAIL, "MASK.FILENAMES", PS_META_REPLACE,
    126                                "Filenames of mask files", maskFiles);
    127             psFree(maskFiles);
    128 
    129             bool status;
    130             pmFPAfile *maskFile = pmFPAfileBindFromArgs(&status, imageFile, config, "PPSTACK.INPUT.MASK",
    131                                                         "MASK.FILENAMES");
     51    bool status = false;                // Status of file definition
     52
     53    psMetadata *recipe = psMetadataLookupMetadata(NULL, config->recipes, PPSTACK_RECIPE); // Recipe for ppSim
     54    if (!recipe) {
     55        psError(PS_ERR_UNEXPECTED_NULL, false, "Unable to find recipe %s", PPSTACK_RECIPE);
     56        return false;
     57    }
     58    bool convolve = psMetadataLookupBool(NULL, recipe, "CONVOLVE"); // Convolve images before stack?
     59
     60    psArray *runImages = pmFPAfileDefineMultipleFromRun(&status, NULL, config,
     61                                                        "PPSTACK.INPUT"); // Input images from previous run
     62    if (runImages) {
     63        // Defining files from the RUN metadata
     64        num = runImages->n;
     65
     66        psArray *runMasks = pmFPAfileDefineMultipleFromRun(&status, runImages, config,
     67                                                           "PPSTACK.INPUT.MASK"); // Input masks
     68        if (!status) {
     69            psError(PS_ERR_UNKNOWN, false, "Unable to define input masks from RUN metadata.");
     70            psFree(runImages);
     71            return false;
     72        }
     73        psFree(runMasks);
     74
     75        psArray *runVars = pmFPAfileDefineMultipleFromRun(&status, runImages, config,
     76                                                          "PPSTACK.INPUT.VARIANCE"); // Input variances
     77        if (!status) {
     78            psError(PS_ERR_UNKNOWN, false, "Unable to define input variances from RUN metadata.");
     79            psFree(runImages);
     80            return false;
     81        }
     82        if (runVars) {
     83            haveVariances = true;
     84        }
     85        psFree(runVars);
     86
     87        psArray *runPSF = pmFPAfileDefineMultipleFromRun(&status, runImages, config,
     88                                                         "PPSTACK.INPUT.PSF"); // Input PSFs
     89        if (!status) {
     90            psError(PS_ERR_UNKNOWN, false, "Unable to define input PSFs from RUN metadata.");
     91            psFree(runImages);
     92            return false;
     93        }
     94        if (runPSF) {
     95            havePSFs = true;
     96        }
     97        psFree(runPSF);
     98
     99        psArray *runSrc = pmFPAfileDefineMultipleFromRun(&status, runImages, config,
     100                                                         "PPSTACK.INPUT.SOURCES"); // Input sources
     101        if (!status) {
     102            psError(PS_ERR_UNKNOWN, false, "Unable to define input sources from RUN metadata.");
     103            psFree(runImages);
     104            return false;
     105        }
     106        if (!runSrc) {
     107            psError(PS_ERR_UNEXPECTED_NULL, true, "Unable to define input sources from RUN metadata.");
     108            psFree(runImages);
     109            return false;
     110        }
     111        psFree(runSrc);
     112
     113        if (convolve) {
     114            psArray *runKernel = pmFPAfileDefineMultipleFromRun(&status, runImages, config,
     115                                                                "PPSTACK.CONV.KERNEL"); // Convolution kernels
    132116            if (!status) {
     117                psError(PS_ERR_UNKNOWN, false, "Unable to define convolution kernels from RUN metadata.");
     118                psFree(runImages);
     119                return false;
     120            }
     121            if (!runKernel) {
     122                psError(PS_ERR_UNEXPECTED_NULL, true,
     123                        "Unable to define convolution kernels from RUN metadata.");
     124                psFree(runImages);
     125                return false;
     126            }
     127            psFree(runKernel);
     128        }
     129
     130        psFree(runImages);
     131    } else {
     132        // Defining files from the input metadata
     133        psMetadata *inputs = psMetadataLookupMetadata(NULL, config->arguments, "INPUTS"); // The inputs info
     134        if (!inputs) {
     135            psError(PS_ERR_UNEXPECTED_NULL, false, "Unable to find inputs.");
     136            return false;
     137        }
     138        psMetadataIterator *iter = psMetadataIteratorAlloc(inputs, PS_LIST_HEAD, NULL); // Iterator
     139        psMetadataItem *item;               // Item from iteration
     140        int i = 0;                          // Counter
     141        while ((item = psMetadataGetAndIncrement(iter))) {
     142            if (item->type != PS_DATA_METADATA) {
     143                psError(PS_ERR_BAD_PARAMETER_TYPE, true,
     144                        "Component %s of the input metadata is not of type METADATA", item->name);
     145                psFree(iter);
     146                return false;
     147            }
     148
     149            psMetadata *input = item->data.md; // The input metadata of interest
     150
     151            psString image = psMetadataLookupStr(NULL, input, "IMAGE"); // Name of image
     152            if (!image || strlen(image) == 0) {
     153                psError(PS_ERR_BAD_PARAMETER_VALUE, true, "Component %s lacks IMAGE of type STR", item->name);
     154                psFree(iter);
     155                return false;
     156            }
     157
     158            bool mdok;
     159            psString mask = psMetadataLookupStr(&mdok, input, "MASK"); // Name of mask
     160            psString variance = psMetadataLookupStr(&mdok, input, "VARIANCE"); // Name of variance map
     161            psString psf = psMetadataLookupStr(&mdok, input, "PSF"); // Name of PSF
     162            psString sources = psMetadataLookupStr(&mdok, input, "SOURCES"); // Name of sources
     163
     164            pmFPAfile *imageFile = defineFile(config, NULL, "PPSTACK.INPUT",
     165                                              image, PM_FPA_FILE_IMAGE); // File for image
     166            if (!imageFile) {
     167                psError(PS_ERR_UNKNOWN, false, "Unable to define file from image %d (%s)", i, image);
     168                return false;
     169            }
     170
     171            if (mask && strlen(mask) > 0 &&
     172                !defineFile(config, imageFile, "PPSTACK.INPUT.MASK", mask, PM_FPA_FILE_MASK)) {
    133173                psError(PS_ERR_UNKNOWN, false, "Unable to define file from mask %d (%s)", i, mask);
    134174                return false;
    135175            }
    136             if (maskFile->type != PM_FPA_FILE_MASK) {
    137                 psError(PS_ERR_IO, true, "PPSTACK.INPUT.MASK is not of type MASK");
    138                 return false;
    139             }
    140         }
    141 
    142         // Optionally add the variance file
    143         if (variance && strlen(variance) > 0) {
    144             haveVariances = true;
    145             psArray *varianceFiles = psArrayAlloc(1); // Array of filenames for this FPA
    146             varianceFiles->data[0] = psMemIncrRefCounter(variance);
    147             psMetadataAddArray(config->arguments, PS_LIST_TAIL, "VARIANCE.FILENAMES", PS_META_REPLACE,
    148                                "Filenames of variance files", varianceFiles);
    149             psFree(varianceFiles);
    150 
    151             bool status;
    152             pmFPAfile *varianceFile = pmFPAfileBindFromArgs(&status, imageFile, config,
    153                                                             "PPSTACK.INPUT.VARIANCE", "VARIANCE.FILENAMES");
    154             if (!status) {
    155                 psError(PS_ERR_UNKNOWN, false, "Unable to define file from variance %d (%s)", i, variance);
    156                 return false;
    157             }
    158             if (varianceFile->type != PM_FPA_FILE_VARIANCE) {
    159                 psError(PS_ERR_IO, true, "PPSTACK.INPUT.VARIANCE is not of type VARIANCE");
    160                 return false;
    161             }
    162         }
    163 
    164         // Add the psf file
    165         if (!psf || strlen(psf) == 0) {
    166             if (havePSFs) {
    167                 psError(PS_ERR_UNEXPECTED_NULL, true, "Unable to find PSF %d", i);
    168                 return false;
    169             }
    170         } else {
    171             if (!havePSFs && i != 0) {
    172                 psWarning("PSF not provided for all inputs --- ignoring.");
    173             } else {
    174                 psArray *psfFiles = psArrayAlloc(1); // Array of filenames for this FPA
    175                 psfFiles->data[0] = psMemIncrRefCounter(psf);
    176                 psMetadataAddArray(config->arguments, PS_LIST_TAIL, "PSF.FILENAMES", PS_META_REPLACE,
    177                                    "Filenames of PSF files", psfFiles);
    178                 psFree(psfFiles);
    179 
    180                 bool status;
    181                 pmFPAfile *psfFile = pmFPAfileBindFromArgs(&status, imageFile, config, "PPSTACK.INPUT.PSF",
    182                                                            "PSF.FILENAMES");
    183                 if (!status) {
    184                     psError(PS_ERR_UNKNOWN, false, "Unable to define file from psf %d (%s)", i, psf);
     176
     177            if (variance && strlen(variance) > 0) {
     178                haveVariances = true;
     179                if (!defineFile(config, imageFile, "PPSTACK.INPUT.VARIANCE", variance,
     180                                PM_FPA_FILE_VARIANCE)) {
     181                    psError(PS_ERR_UNKNOWN, false,
     182                            "Unable to define file from variance %d (%s)", i, variance);
    185183                    return false;
    186184                }
    187                 if (psfFile->type != PM_FPA_FILE_PSF) {
    188                     psError(PS_ERR_IO, true, "PPSTACK.INPUT.PSF is not of type PSF");
     185            }
     186
     187            if (psf && strlen(psf) > 0) {
     188                if (i != 0 && !havePSFs) {
     189                    psWarning("PSF not provided for all inputs --- ignoring.");
     190                } else {
     191                    havePSFs = true;
     192                    if (!defineFile(config, imageFile, "PPSTACK.INPUT.PSF", psf, PM_FPA_FILE_PSF)) {
     193                        psError(PS_ERR_UNKNOWN, false, "Unable to define file from psf %d (%s)", i, psf);
     194                        return false;
     195                    }
     196                }
     197            } else if (havePSFs) {
     198                psError(PS_ERR_UNEXPECTED_NULL, true, "Unable to find PSF %d", i);
     199                return false;
     200            }
     201
     202            if (!sources || strlen(sources) == 0) {
     203                psError(PS_ERR_UNEXPECTED_NULL, true, "SOURCES not provided for file %d", i);
     204                return false;
     205            }
     206            if (!defineFile(config, imageFile, "PPSTACK.INPUT.SOURCES", sources, PM_FPA_FILE_CMF)) {
     207                psError(PS_ERR_UNKNOWN, false, "Unable to define file from sources %d (%s)",
     208                        i, sources);
     209                return false;
     210            }
     211
     212            if (convolve) {
     213                pmFPAfile *kernel = pmFPAfileDefineOutput(config, imageFile->fpa, "PPSTACK.CONV.KERNEL");
     214                if (!kernel) {
     215                    psError(PS_ERR_IO, false, _("Unable to generate output file from PPSTACK.CONV.KERNEL"));
    189216                    return false;
    190217                }
    191                 havePSFs = true;
    192             }
    193         }
    194 
    195         // Add the sources file
    196         {
    197             psArray *sourcesFiles = psArrayAlloc(1); // Array of filenames for this FPA
    198             sourcesFiles->data[0] = psMemIncrRefCounter(sources);
    199             psMetadataAddArray(config->arguments, PS_LIST_TAIL, "SOURCES.FILENAMES", PS_META_REPLACE,
    200                                "Filenames of SOURCES files", sourcesFiles);
    201             psFree(sourcesFiles);
    202 
    203             bool status;
    204             pmFPAfile *sourcesFile = pmFPAfileBindFromArgs(&status, imageFile, config,
    205                                                            "PPSTACK.INPUT.SOURCES", "SOURCES.FILENAMES");
    206             if (!status) {
    207                 psError(PS_ERR_UNKNOWN, false, "Unable to define file from sources %d (%s)",
    208                         i, sources);
    209                 return false;
    210             }
    211             if (sourcesFile->type != PM_FPA_FILE_CMF) {
    212                 psError(PS_ERR_IO, true, "PPSTACK.INPUT.SOURCES is not of type CMF");
    213                 return false;
    214             }
    215         }
    216 
    217 #if 0
    218         // Output convolved files
    219         pmFPAfile *outconvImage    = defineOutputConvolved("PPSTACK.OUTCONV", imageFile->fpa, config,
    220                                                            PM_FPA_FILE_IMAGE);
    221         pmFPAfile *outconvMask     = defineOutputConvolved("PPSTACK.OUTCONV.MASK", imageFile->fpa, config,
    222                                                            PM_FPA_FILE_MASK);
    223         pmFPAfile *outconvVariance = defineOutputConvolved("PPSTACK.OUTCONV.VARIANCE", imageFile->fpa, config,
    224                                                            PM_FPA_FILE_VARIANCE);
    225         if (!outconvImage || !outconvMask || !outconvVariance) {
    226             return false;
    227         }
    228 
    229         // Input convolved files
    230         pmFPAfile *inconvImage    = defineInputConvolved("PPSTACK.INCONV", outconvImage, config,
    231                                                          PM_FPA_FILE_IMAGE);
    232         pmFPAfile *inconvMask     = defineInputConvolved("PPSTACK.INCONV.MASK", outconvMask, config,
    233                                                          PM_FPA_FILE_MASK);
    234         pmFPAfile *inconvVariance = defineInputConvolved("PPSTACK.INCONV.VARIANCE", outconvVariance, config,
    235                                                          PM_FPA_FILE_VARIANCE);
    236         if (!inconvImage || !inconvMask || !inconvVariance) {
    237             return false;
    238         }
    239 #endif
    240 
    241         i++;
    242     }
    243     psFree(iter);
    244     psMetadataRemoveKey(config->arguments, "IMAGE.FILENAMES");
    245     if (psMetadataLookup(config->arguments, "MASK.FILENAMES")) {
    246         psMetadataRemoveKey(config->arguments, "MASK.FILENAMES");
    247     }
    248     if (psMetadataLookup(config->arguments, "VARIANCE.FILENAMES")) {
    249         psMetadataRemoveKey(config->arguments, "VARIANCE.FILENAMES");
    250     }
    251     if (psMetadataLookup(config->arguments, "PSF.FILENAMES")) {
    252         psMetadataRemoveKey(config->arguments, "PSF.FILENAMES");
    253     }
    254     if (psMetadataLookup(config->arguments, "SOURCES.FILENAMES")) {
    255         psMetadataRemoveKey(config->arguments, "SOURCES.FILENAMES");
    256     }
    257 
    258     psMetadataAddS32(config->arguments, PS_LIST_TAIL, "INPUTS.NUM", 0, "Number of input files", i);
     218                kernel->save = true;
     219            }
     220
     221            i++;
     222        }
     223        psFree(iter);
     224        psMetadataRemoveKey(config->arguments, "FILENAMES");
     225        num = i;
     226    }
     227    psMetadataAddS32(config->arguments, PS_LIST_TAIL, "INPUTS.NUM", 0, "Number of input files", num);
    259228    psMetadataAddBool(config->arguments, PS_LIST_TAIL, "HAVE.PSF", 0, "Have PSFs available?", havePSFs);
    260229
     
    343312    }
    344313    jpeg2->save = true;
    345 
    346 
    347     psMetadata *recipe = psMetadataLookupMetadata(NULL, config->recipes, PPSTACK_RECIPE); // Recipe for ppSim
    348     if (!recipe) {
    349         psError(PS_ERR_UNEXPECTED_NULL, false, "Unable to find recipe %s", PPSTACK_RECIPE);
    350         return false;
    351     }
    352314
    353315    // For photometry, we operate on the chip-mosaicked image
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackCombineInitial.c

    r23352 r23594  
    1616    psAssert(config, "Require configuration");
    1717
    18     psTimerStart("PPSTACK_FINAL");
     18    if (!options->convolve) {
     19        // No need to do initial combination when we haven't convolved
     20        return true;
     21    }
    1922
    20     psMetadata *recipe = psMetadataLookupMetadata(NULL, config->recipes, PPSTACK_RECIPE); // ppStack recipe
    21     psAssert(recipe, "We've thrown an error on this before.");
     23    psTimerStart("PPSTACK_INITIAL");
    2224
    2325    psMetadata *ppsub = psMetadataLookupMetadata(NULL, config->recipes, "PPSUB"); // PPSUB recipe
     
    2527                                          "KERNEL.SIZE"); // Overlap by kernel size between consecutive scans
    2628
    27     pmFPAview *view = NULL;             // View to readout
    28 
    29     int row0, col0;                 // Offset for readout
    30     int numCols, numRows;           // Size of readout
    31     ppStackThread *thread = stack->threads->data[0]; // Representative thread
    32     if (!pmReadoutStackSetOutputSize(&col0, &row0, &numCols, &numRows, thread->readouts)) {
    33         psError(PS_ERR_UNKNOWN, false, "problem setting output readout size.");
    34         return false;
    35     }
    36 
    37     pmFPAfileActivate(config->files, false, NULL);
    38     ppStackFileActivation(config, PPSTACK_FILES_COMBINE, true);
    39     view = ppStackFilesIterateDown(config);
    40     if (!view) {
    41         return false;
    42     }
    43 
    44     pmCell *outCell = pmFPAfileThisCell(config->files, view, "PPSTACK.OUTPUT"); // Output cell
    45     options->outRO = pmReadoutAlloc(outCell); // Output readout
    46     psFree(view);
    47 
    48     psString maskBadStr = psMetadataLookupStr(NULL, recipe, "MASK.BAD"); // Name of bits to mask for bad
    49     psImageMaskType maskBad = pmConfigMaskGet(maskBadStr, config); // Bits to mask for bad pixels
    50     if (!pmReadoutStackDefineOutput(options->outRO, col0, row0, numCols, numRows, true, true, maskBad)) {
    51         psError(PS_ERR_UNKNOWN, false, "Unable to prepare output.");
    52         return false;
    53     }
    54 
    55     psFree(options->cells); options->cells = NULL;
    5629
    5730    bool status;                    // Status of read
     
    6942        }
    7043
    71         // call: ppStackReadoutInitial(config, outRO, readouts, subRegions, subKernels)
    7244        psThreadJob *job = psThreadJobAlloc("PPSTACK_INITIAL_COMBINE"); // Job to start
    7345        psArrayAdd(job->args, 1, thread);
     
    128100
    129101    if (options->stats) {
    130         psMetadataAddF32(options->stats, PS_LIST_TAIL, "TIME_FINAL", 0,
    131                          "Time to make final stack", psTimerMark("PPSTACK_FINAL"));
     102        psMetadataAddF32(options->stats, PS_LIST_TAIL, "TIME_INITIAL", 0,
     103                         "Time to make final stack", psTimerMark("PPSTACK_INITIAL"));
    132104    }
    133105
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackConvolve.c

    r23352 r23594  
    3030    int num = options->num;             // Number of inputs
    3131    options->cells = psArrayAlloc(num); // Cells for convolved images --- a handle for reading again
    32     options->subKernels = psArrayAlloc(num); // Subtraction kernels --- required in the stacking
    33     options->subRegions = psArrayAlloc(num); // Subtraction regions --- required in the stacking
     32    options->kernels = psArrayAlloc(num); // PSF-matching kernels --- required in the stacking
     33    options->regions = psArrayAlloc(num); // PSF-matching regions --- required in the stacking
    3434    int numGood = 0;                    // Number of good frames
    3535    options->numCols = 0;
     
    3838    psVectorInit(options->matchChi2, NAN);
    3939    options->weightings = psVectorAlloc(num, PS_TYPE_F32); // Combination weightings for images (1/noise^2)
    40     psVectorInit(options->weightings, NAN);
     40    psVectorInit(options->weightings, 0.0);
    4141    options->covariances = psArrayAlloc(num); // Covariance matrices
    4242
     
    7878
    7979        // Background subtraction, scaling and normalisation is performed automatically by the image matching
    80         psArray *regions = NULL, *kernels = NULL; // Regions and kernels used in subtraction
    8180        psTimerStart("PPSTACK_MATCH");
    82 
    83         if (!ppStackMatch(readout, &regions, &kernels, &options->matchChi2->data.F32[i],
    84                           &options->weightings->data.F32[i], options->sourceLists->data[i],
    85                           options->psf, rng, config)) {
     81        if (!ppStackMatch(readout, options, i, config)) {
    8682            psErrorStackPrint(stderr, "Unable to match image %d --- ignoring.", i);
    87             options->inputMask->data.PS_TYPE_VECTOR_MASK_DATA[i] = PPSTACK_MASK_MATCH;
     83            options->inputMask->data.PS_TYPE_VECTOR_MASK_DATA[i] |= PPSTACK_MASK_MATCH;
    8884            psErrorClear();
    8985            continue;
     
    9288
    9389        if (options->stats) {
    94             pmSubtractionKernels *kernels = psMetadataLookupPtr(NULL, readout->analysis,
    95                                                                 PM_SUBTRACTION_ANALYSIS_KERNEL);// Conv kernel
    9690            psMetadataAddF32(options->stats, PS_LIST_TAIL, "TIME_MATCH", PS_META_DUPLICATE_OK,
    9791                             "Time to match PSF", psTimerMark("PPSTACK_MATCH"));
    98             psMetadataAddF32(options->stats, PS_LIST_TAIL, "STAMP.MEAN", PS_META_DUPLICATE_OK,
    99                              "Mean deviation for stamps", kernels->mean);
    100             psMetadataAddF32(options->stats, PS_LIST_TAIL, "STAMP.RMS", PS_META_DUPLICATE_OK,
    101                              "RMS deviation for stamps", kernels->rms);
    102             psMetadataAddF32(options->stats, PS_LIST_TAIL, "STAMP.NUM", PS_META_DUPLICATE_OK,
    103                              "Number of stamps", kernels->numStamps);
    104             float deconv = psMetadataLookupF32(NULL, readout->analysis,
    105                                                PM_SUBTRACTION_ANALYSIS_DECONV_MAX); // Deconvolution fraction
    106             psMetadataAddF32(options->stats, PS_LIST_TAIL, "KERNEL.DECONV", PS_META_DUPLICATE_OK,
    107                              "Deconvolution fraction for kernel", deconv);
    10892            psMetadataAddF32(options->stats, PS_LIST_TAIL, "PPSTACK.WEIGHTING", PS_META_DUPLICATE_OK,
    10993                             "Weighting for image", options->weightings->data.F32[i]);
     94
     95            if (options->convolve) {
     96                // Pull parameters out of convolution kernel
     97                pmSubtractionKernels *kernels = psMetadataLookupPtr(NULL, readout->analysis,
     98                                                                    PM_SUBTRACTION_ANALYSIS_KERNEL);
     99                psMetadataAddF32(options->stats, PS_LIST_TAIL, "STAMP.MEAN", PS_META_DUPLICATE_OK,
     100                                 "Mean deviation for stamps", kernels->mean);
     101                psMetadataAddF32(options->stats, PS_LIST_TAIL, "STAMP.RMS", PS_META_DUPLICATE_OK,
     102                                 "RMS deviation for stamps", kernels->rms);
     103                psMetadataAddF32(options->stats, PS_LIST_TAIL, "STAMP.NUM", PS_META_DUPLICATE_OK,
     104                                 "Number of stamps", kernels->numStamps);
     105                float deconv = psMetadataLookupF32(NULL, readout->analysis,
     106                                                   PM_SUBTRACTION_ANALYSIS_DECONV_MAX);
     107                psMetadataAddF32(options->stats, PS_LIST_TAIL, "KERNEL.DECONV", PS_META_DUPLICATE_OK,
     108                                 "Deconvolution fraction for kernel", deconv);
     109            }
    110110        }
    111111        psLogMsg("ppStack", PS_LOG_INFO, "Time to match image %d: %f sec", i, psTimerClear("PPSTACK_MATCH"));
    112112
    113         options->subRegions->data[i] = regions;
    114         options->subKernels->data[i] = kernels;
    115 
    116113        // Write the temporary convolved files
    117         pmHDU *hdu = readout->parent->parent->parent->hdu; // HDU for convolved image
    118         assert(hdu);
    119         ppStackWriteImage(options->imageNames->data[i], hdu->header, readout->image, config);
    120         psMetadata *maskHeader = psMetadataCopy(NULL, hdu->header); // Copy of header, for mask
    121         pmConfigMaskWriteHeader(config, maskHeader);
    122         ppStackWriteImage(options->maskNames->data[i], maskHeader, readout->mask, config);
    123         psFree(maskHeader);
    124         psImageCovarianceTransfer(readout->variance, readout->covariance);
    125         ppStackWriteImage(options->varianceNames->data[i], hdu->header, readout->variance, config);
     114        if (options->convolve) {
     115            pmHDU *hdu = readout->parent->parent->parent->hdu; // HDU for convolved image
     116            assert(hdu);
     117            ppStackWriteImage(options->imageNames->data[i], hdu->header, readout->image, config);
     118            psMetadata *maskHeader = psMetadataCopy(NULL, hdu->header); // Copy of header, for mask
     119            pmConfigMaskWriteHeader(config, maskHeader);
     120            ppStackWriteImage(options->maskNames->data[i], maskHeader, readout->mask, config);
     121            psFree(maskHeader);
     122            psImageCovarianceTransfer(readout->variance, readout->covariance);
     123            ppStackWriteImage(options->varianceNames->data[i], hdu->header, readout->variance, config);
    126124#ifdef TESTING
    127         {
    128             psString name = NULL;
    129             psStringAppend(&name, "covariance_%d.fits", i);
    130             ppStackWriteImage(name, hdu->header, readout->covariance->image, config);
    131             pmStackVisualPlotTestImage(readout->covariance->image, name);
    132             psFree(name);
    133         }
     125            {
     126                psString name = NULL;
     127                psStringAppend(&name, "covariance_%d.fits", i);
     128                ppStackWriteImage(name, hdu->header, readout->covariance->image, config);
     129                pmStackVisualPlotTestImage(readout->covariance->image, name);
     130                psFree(name);
     131            }
    134132#endif
     133        }
    135134
    136135        pmCell *inCell = readout->parent; // Input cell
     
    152151    psFree(rng);
    153152
     153    psFree(options->norm); options->norm = NULL;
    154154    psFree(options->sourceLists); options->sourceLists = NULL;
    155155    psFree(options->psf); options->psf = NULL;
     
    183183
    184184    // Reject images out-of-hand on the basis of their match chi^2
    185     {
     185    if (options->convolve) {
    186186        psVector *values = psVectorAllocEmpty(num, PS_TYPE_F32); // Values to sort
    187187        for (int i = 0; i < num; i++) {
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackFiles.c

    r23352 r23594  
    1717
    1818/// Files required for the convolution
    19 static char *filesConvolve[] = { "PPSTACK.INPUT", "PPSTACK.INPUT.MASK", "PPSTACK.INPUT.VARIANCE", NULL };
     19static char *filesConvolve[] = { "PPSTACK.INPUT", "PPSTACK.INPUT.MASK", "PPSTACK.INPUT.VARIANCE",
     20                                 "PPSTACK.CONV.KERNEL", NULL };
    2021
    2122/// Output files for the combination
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackFinish.c

    r23352 r23594  
    6060    }
    6161
     62
     63    // Dump configuration
     64    bool mdok;                          // Status of MD lookup
     65    psString dump = psMetadataLookupStr(&mdok, config->arguments, "DUMP_CONFIG"); // File for config
     66    if (dump) {
     67        pmFPAfile *input = psMetadataLookupPtr(NULL, config->files, "PPSTACK.INPUT"); // Input file
     68        pmConfigDump(config, input->fpa, dump);
     69    }
     70
    6271    return true;
    6372}
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackLoop.c

    r23352 r23594  
    6262        return false;
    6363    }
     64    psFree(options->cells); options->cells = NULL;
     65
     66    // Prepare for combination
     67    if (!ppStackCombinePrepare(stack, options, config)) {
     68        psError(PS_ERR_UNKNOWN, false, "Unable to prepare for combination.");
     69        psFree(stack);
     70        psFree(options);
     71        return false;
     72    }
    6473
    6574    // Initial combination
     
    103112    // Clean up
    104113    psTrace("ppStack", 2, "Cleaning up after combination....\n");
    105     if (!ppStackCombineFinal(stack, options, config)) {
     114    if (!ppStackCleanup(stack, options, config)) {
    106115        psError(PS_ERR_UNKNOWN, false, "Unable to clean up.");
    107116        psFree(stack);
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackLoop.h

    r23352 r23594  
    3434    );
    3535
     36// Prepare for combination
     37bool ppStackCombinePrepare(
     38    ppStackThreadData *stack,           // Stack
     39    ppStackOptions *options,            // Options
     40    pmConfig *config                    // Configuration
     41    );
     42
    3643// Initial combination
    3744bool ppStackCombineInitial(
     
    5461    );
    5562
     63// Cleanup following combination
     64bool ppStackCleanup(
     65    ppStackThreadData *stack,           // Stack
     66    ppStackOptions *options,            // Options
     67    pmConfig *config                    // Configuration
     68    );
     69
    5670// Photometry
    5771bool ppStackPhotometry(
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackMatch.c

    r23352 r23594  
    163163
    164164
    165 bool ppStackMatch(pmReadout *readout, psArray **regions, psArray **kernels, float *chi2, float *weighting,
    166                   psArray *sources, const pmPSF *psf, psRandom *rng, const pmConfig *config)
     165bool ppStackMatch(pmReadout *readout, ppStackOptions *options, int index, const pmConfig *config)
    167166{
    168167    assert(readout);
    169     assert(regions && !*regions);
    170     assert(kernels && !*kernels);
     168    assert(options);
    171169    assert(config);
    172     *weighting = 0.0;
    173170
    174171    psMetadata *recipe = psMetadataLookupMetadata(NULL, config->recipes, PPSTACK_RECIPE); // ppStack recipe
     
    197194    }
    198195
    199     pmReadout *output = pmReadoutAlloc(NULL); // Output readout, for holding results temporarily
    200 
    201     static int numInput = -1;            // Index of input file
    202     numInput++;
     196    // Match the PSF
     197    if (options->convolve) {
     198        pmReadout *conv = pmReadoutAlloc(NULL); // Conv readout, for holding results temporarily
    203199#ifdef TESTING
    204     // Read previously produced kernel
    205     if (psMetadataLookupBool(NULL, config->arguments, "PPSTACK.DEBUG.STACK")) {
    206         const char *outName = psMetadataLookupStr(NULL, config->arguments, "OUTPUT"); // Output root
    207         assert(outName);
    208         // Read convolution kernel
    209         psString filename = NULL;   // Output filename
    210         psStringAppend(&filename, "%s.%d.kernel", outName, numInput);
    211         psString resolved = pmConfigConvertFilename(filename, config, false, false); // Resolved filename
    212         psFree(filename);
    213         psFits *fits = psFitsOpen(resolved, "r"); // FITS file for subtraction kernel
    214         psFree(resolved);
    215         if (!fits || !pmReadoutReadSubtractionKernels(output, fits)) {
    216             psError(PS_ERR_IO, false, "Unable to read previously produced kernel");
     200        // This is a hack to use the temporary convolved images and kernel generated previously.
     201        // This makes the 'matching' operation much faster, allowing debugging of the stack process easier.
     202        // It implicitly assumes the output root name is the same between invocations.
     203
     204        // Read previously produced kernel
     205        if (psMetadataLookupBool(NULL, config->arguments, "PPSTACK.DEBUG.STACK")) {
     206            pmFPAfile *file = pmFPAfileSelectSingle(config->files, "PPSTACK.CONV.KERNEL", index);
     207            psAssert(file, "Require file");
     208
     209            pmFPAview *view = pmFPAviewAlloc(0); // View to readout of interest
     210            view->chip = view->cell = view->readout = 0;
     211            psString filename = pmFPAfileNameFromRule(filerule->rule, file, view); // Filename of interest
     212
     213            // Read convolution kernel
     214            psString resolved = pmConfigConvertFilename(filename, config, false, false); // Resolved filename
     215            psFree(filename);
     216            psFits *fits = psFitsOpen(resolved, "r"); // FITS file for subtraction kernel
     217            psFree(resolved);
     218            if (!fits || !pmReadoutReadSubtractionKernels(conv, fits)) {
     219                psError(PS_ERR_IO, false, "Unable to read previously produced kernel");
     220                psFitsClose(fits);
     221                return false;
     222            }
    217223            psFitsClose(fits);
    218             return false;
    219         }
    220         psFitsClose(fits);
    221 
    222         // Add in variance factor
    223         pmSubtractionKernels *kernels = psMetadataLookupPtr(NULL, output->analysis,
    224                                                             PM_SUBTRACTION_ANALYSIS_KERNEL); // Kernels
    225         float vf = pmSubtractionVarianceFactor(kernels, 0.0, 0.0, false); // Variance factor
    226         psMetadataItem *vfItem = psMetadataLookup(readout->parent->concepts, "CELL.VARFACTOR");
    227         if (!isfinite(vf)) {
    228             vf = 1.0;
    229         }
    230         if (isfinite(vfItem->data.F32)) {
    231             vfItem->data.F32 *= vf;
    232         } else {
    233             vfItem->data.F32 = vf;
    234         }
    235 
    236         // Read image, mask, variance
    237         const char *tempImage = psMetadataLookupStr(NULL, recipe, "TEMP.IMAGE"); // Suffix for image
    238         const char *tempMask = psMetadataLookupStr(NULL, recipe, "TEMP.MASK"); // Suffix for mask
    239         const char *tempVariance = psMetadataLookupStr(NULL, recipe, "TEMP.VARIANCE"); // Suffix for variance map
    240         psString imageName = NULL, maskName = NULL, varianceName = NULL; // Names for convolved images
    241         psStringAppend(&imageName, "%s.%d.%s", outName, numInput, tempImage);
    242         psStringAppend(&maskName, "%s.%d.%s", outName, numInput, tempMask);
    243         psStringAppend(&varianceName, "%s.%d.%s", outName, numInput, tempVariance);
    244 
    245         if (!readImage(&readout->image, imageName, config) || !readImage(&readout->mask, maskName, config) ||
    246             !readImage(&readout->variance, varianceName, config)) {
    247             psError(PS_ERR_IO, false, "Unable to read previously produced image.");
     224
     225            // Add in variance factor
     226            pmSubtractionKernels *kernels = psMetadataLookupPtr(NULL, conv->analysis,
     227                                                                PM_SUBTRACTION_ANALYSIS_KERNEL); // Kernels
     228            float vf = pmSubtractionVarianceFactor(kernels, 0.0, 0.0, false); // Variance factor
     229            psMetadataItem *vfItem = psMetadataLookup(readout->parent->concepts, "CELL.VARFACTOR");
     230            if (!isfinite(vf)) {
     231                vf = 1.0;
     232            }
     233            if (isfinite(vfItem->data.F32)) {
     234                vfItem->data.F32 *= vf;
     235            } else {
     236                vfItem->data.F32 = vf;
     237            }
     238
     239            if (!readImage(&readout->image, options->imageNames->data[index], config) ||
     240                !readImage(&readout->mask, options->maskNames->data[index], config) ||
     241                !readImage(&readout->variance, options->varianceNames->data[index], config)) {
     242                psError(PS_ERR_IO, false, "Unable to read previously produced image.");
     243                psFree(imageName);
     244                psFree(maskName);
     245                psFree(varianceName);
     246                return false;
     247            }
    248248            psFree(imageName);
    249249            psFree(maskName);
    250250            psFree(varianceName);
    251             return false;
    252         }
    253         psFree(imageName);
    254         psFree(maskName);
    255         psFree(varianceName);
    256 
    257         psRegion *region = psMetadataLookupPtr(NULL, output->analysis,
    258                                                PM_SUBTRACTION_ANALYSIS_REGION); // Convolution region
    259 
    260         pmSubtractionAnalysis(readout->analysis, kernels, region,
    261                               readout->image->numCols, readout->image->numRows);
    262 
    263         psKernel *kernel = pmSubtractionKernel(kernels, 0.0, 0.0, false); // Convolution kernel
    264         psKernel *covar = psImageCovarianceCalculate(kernel, readout->covariance); // New covariance matrix
    265         psFree(readout->covariance);
    266         readout->covariance = covar;
    267         psFree(kernel);
    268 
    269     } else {
    270 #endif
    271 
    272         // Normal operations here
    273         if (psMetadataLookupBool(&mdok, config->arguments, "HAVE.PSF")) {
    274             assert(psf);
    275             assert(sources);
     251
     252            psRegion *region = psMetadataLookupPtr(NULL, conv->analysis,
     253                                                   PM_SUBTRACTION_ANALYSIS_REGION); // Convolution region
     254
     255            pmSubtractionAnalysis(readout->analysis, kernels, region,
     256                                  readout->image->numCols, readout->image->numRows);
     257
     258            psKernel *kernel = pmSubtractionKernel(kernels, 0.0, 0.0, false); // Convolution kernel
     259            psKernel *covar = psImageCovarianceCalculate(kernel, readout->covariance); // Covariance matrix
     260            psFree(readout->covariance);
     261            readout->covariance = covar;
     262            psFree(kernel);
     263        } else {
     264#endif
     265
     266            // Normal operations here
     267            psAssert(options->psf, "Require target PSF");
     268            psAssert(options->sourceLists && options->sourceLists->data[index], "Require source list");
    276269
    277270            int order = psMetadataLookupS32(NULL, ppsub, "SPATIAL.ORDER"); // Spatial polynomial order
     
    284277            float rej = psMetadataLookupF32(NULL, ppsub, "REJ"); // Rejection threshold
    285278            float sysError = psMetadataLookupF32(NULL, ppsub, "SYS"); // Relative systematic error in kernel
    286             pmSubtractionKernelsType type = pmSubtractionKernelsTypeFromString(
    287                 psMetadataLookupStr(NULL, ppsub, "KERNEL.TYPE")); // Kernel type
     279            const char *typeStr = psMetadataLookupStr(NULL, ppsub, "KERNEL.TYPE"); // Kernel type
     280            pmSubtractionKernelsType type = pmSubtractionKernelsTypeFromString(typeStr); // Kernel type
    288281            psVector *widths = psMetadataLookupPtr(NULL, ppsub, "ISIS.WIDTHS"); // ISIS Gaussian widths
    289282            psVector *orders = psMetadataLookupPtr(NULL, ppsub, "ISIS.ORDERS"); // ISIS Polynomial orders
     
    308301            }
    309302
    310 #if 0
    311             // Testing the normalisation of the fake image
    312             {
    313                 pmReadout *test = pmReadoutAlloc(NULL); // Test readout
    314                 psArray *sources = psArrayAlloc(1);     // Array of sources
    315                 pmSource *source = pmSourceAlloc();     // Source
    316                 sources->data[0] = source;
    317                 source->peak = pmPeakAlloc(500, 500, 10000, PM_PEAK_LONE);
    318                 source->psfMag = -13.0;
    319                 pmReadoutFakeFromSources(test, 1000, 1000, sources, NULL, NULL, psf, 0.1, 0, false, true);
    320                 float sum = 0.0;
    321                 for (int y = 0; y < test->image->numRows; y++) {
    322                     for (int x = 0; x < test->image->numCols; x++) {
    323                         sum += test->image->data.F32[y][x];
    324                     }
    325                 }
    326                 fprintf(stderr, "Photometry: %f --> %f = -13.0 ???\n", sum, -2.5*log10(sum));
    327 
    328                 psFits *fits = psFitsOpen("testphot.fits", "w");
    329                 psFitsWriteImage(fits, NULL, test->image, 0, NULL);
    330                 psFitsClose(fits);
    331                 exit(0);
    332             }
    333 #endif
    334 
    335303            pmReadout *fake = pmReadoutAlloc(NULL); // Fake readout with target PSF
    336304
    337305            // For the sake of stamps, remove nearby sources
    338             psArray *stampSources = stackSourcesFilter(sources, footprint); // Filtered list of sources
     306            psArray *stampSources = stackSourcesFilter(options->sourceLists->data[index],
     307                                                       footprint); // Filtered list of sources
    339308
    340309            if (!pmReadoutFakeFromSources(fake, readout->image->numCols, readout->image->numRows,
    341                                           stampSources, NULL, NULL, psf, NAN, footprint + size,
     310                                          stampSources, NULL, NULL, options->psf, NAN, footprint + size,
    342311                                          false, true)) {
    343312                psError(PS_ERR_UNKNOWN, false, "Unable to generate fake image with target PSF.");
    344313                psFree(fake);
    345314                psFree(optWidths);
    346                 psFree(output);
     315                psFree(conv);
    347316                return false;
    348317            }
     
    357326                pmHDU *hdu = pmHDUFromCell(readout->parent);
    358327                psString name = NULL;
    359                 psStringAppend(&name, "fake_%03d.fits", numInput);
     328                psStringAppend(&name, "fake_%03d.fits", index);
    360329                pmStackVisualPlotTestImage(fake->image, name);
    361330                psFits *fits = psFitsOpen(name, "w");
     
    367336                pmHDU *hdu = pmHDUFromCell(readout->parent);
    368337                psString name = NULL;
    369                 psStringAppend(&name, "real_%03d.fits", numInput);
     338                psStringAppend(&name, "real_%03d.fits", index);
    370339                pmStackVisualPlotTestImage(readout->image, name);
    371340                psFits *fits = psFitsOpen(name, "w");
     
    381350
    382351            // Do the image matching
    383             if (!pmSubtractionMatch(output, NULL, readout, fake, footprint, stride, regionSize, spacing,
    384                                     threshold, stampSources, stampsName, type, size, order, widths, orders,
    385                                     inner, ringsOrder, binning, penalty, optimum, optWidths, optOrder,
    386                                     optThresh, iter, rej, sysError, maskVal, maskBad, maskPoor, poorFrac,
    387                                     badFrac, PM_SUBTRACTION_MODE_1)) {
    388                 psError(PS_ERR_UNKNOWN, false, "Unable to match images.");
    389                 psFree(fake);
    390                 psFree(optWidths);
    391                 psFree(stampSources);
    392                 psFree(output);
    393                 return false;
     352            pmSubtractionKernels *kernel = psMetadataLookupPtr(&mdok, readout->analysis,
     353                                                               PM_SUBTRACTION_ANALYSIS_KERNEL); // Conv kernel
     354            if (kernel) {
     355                if (!pmSubtractionMatchPrecalc(conv, NULL, readout, fake, readout->analysis,
     356                                               stride, sysError, maskVal, maskBad, maskPoor,
     357                                               poorFrac, badFrac)) {
     358                    psError(PS_ERR_UNKNOWN, false, "Unable to convolve images.");
     359                    psFree(fake);
     360                    psFree(optWidths);
     361                    psFree(stampSources);
     362                    psFree(conv);
     363                    return false;
     364                }
     365            } else {
     366                if (!pmSubtractionMatch(conv, NULL, readout, fake, footprint, stride, regionSize, spacing,
     367                                        threshold, stampSources, stampsName, type, size, order, widths,
     368                                        orders, inner, ringsOrder, binning, penalty,
     369                                        optimum, optWidths, optOrder, optThresh, iter, rej, sysError,
     370                                        maskVal, maskBad, maskPoor, poorFrac, badFrac,
     371                                        PM_SUBTRACTION_MODE_1)) {
     372                    psError(PS_ERR_UNKNOWN, false, "Unable to match images.");
     373                    psFree(fake);
     374                    psFree(optWidths);
     375                    psFree(stampSources);
     376                    psFree(conv);
     377                    return false;
     378                }
    394379            }
    395380
     
    398383                pmHDU *hdu = pmHDUFromCell(readout->parent);
    399384                psString name = NULL;
    400                 psStringAppend(&name, "conv_%03d.fits", numInput);
    401                 pmStackVisualPlotTestImage(output->image, name);
     385                psStringAppend(&name, "conv_%03d.fits", index);
     386                pmStackVisualPlotTestImage(conv->image, name);
    402387                psFits *fits = psFitsOpen(name, "w");
    403388                psFree(name);
    404                 psFitsWriteImage(fits, hdu->header, output->image, 0, NULL);
     389                psFitsWriteImage(fits, hdu->header, conv->image, 0, NULL);
    405390                psFitsClose(fits);
    406391            }
     
    408393                pmHDU *hdu = pmHDUFromCell(readout->parent);
    409394                psString name = NULL;
    410                 psStringAppend(&name, "diff_%03d.fits", numInput);
     395                psStringAppend(&name, "diff_%03d.fits", index);
    411396                pmStackVisualPlotTestImage(fake->image, name);
    412397                psFits *fits = psFitsOpen(name, "w");
    413398                psFree(name);
    414                 psBinaryOp(fake->image, output->image, "-", fake->image);
     399                psBinaryOp(fake->image, conv->image, "-", fake->image);
    415400                psFitsWriteImage(fits, hdu->header, fake->image, 0, NULL);
    416401                psFitsClose(fits);
     
    428413            // Set the variance factor
    429414            psMetadataItem *vfItem = psMetadataLookup(readout->parent->concepts, "CELL.VARFACTOR");
    430             float vf = psMetadataLookupF32(NULL, output->analysis, PM_SUBTRACTION_ANALYSIS_VARFACTOR_1);
     415            float vf = psMetadataLookupF32(NULL, conv->analysis, PM_SUBTRACTION_ANALYSIS_VARFACTOR_1);
    431416            if (!isfinite(vf)) {
    432417                vf = 1.0;
     
    443428            psFree(readout->variance);
    444429            psFree(readout->covariance);
    445             readout->image  = psMemIncrRefCounter(output->image);
    446             readout->mask   = psMemIncrRefCounter(output->mask);
    447             readout->variance = psMemIncrRefCounter(output->variance);
    448             readout->covariance = psImageCovarianceTruncate(output->covariance, COVAR_FRAC);
    449         } else {
    450             // Fake the convolution
    451             psRegion *region = psRegionAlloc(0, readout->image->numCols - 1, 0, readout->image->numRows - 1);
    452             psMetadataAddPtr(output->analysis, PS_LIST_TAIL, PM_SUBTRACTION_ANALYSIS_REGION,
    453                              PS_DATA_REGION | PS_META_DUPLICATE_OK, "Fake subtraction region", region);
    454             psFree(region);
    455             pmSubtractionKernels *kernels = pmSubtractionKernelsPOIS(FAKE_SIZE, 0, penalty,
    456                                                                      PM_SUBTRACTION_MODE_1);
    457             // Set solution to delta function
    458             kernels->solution1 = psVectorAlloc(kernels->num + 2, PS_TYPE_F64);
    459             psVectorInit(kernels->solution1, 0.0);
    460             int normIndex = PM_SUBTRACTION_INDEX_NORM(kernels); // Index for normalisation
    461             kernels->solution1->data.F64[normIndex] = 1.0;
    462             psMetadataAddPtr(output->analysis, PS_LIST_TAIL, PM_SUBTRACTION_ANALYSIS_KERNEL,
    463                              PS_DATA_UNKNOWN | PS_META_DUPLICATE_OK, "Fake subtraction kernel", kernels);
    464             psFree(kernels);
    465         }
    466 
     430            readout->image  = psMemIncrRefCounter(conv->image);
     431            readout->mask   = psMemIncrRefCounter(conv->mask);
     432            readout->variance = psMemIncrRefCounter(conv->variance);
     433            readout->covariance = psImageCovarianceTruncate(conv->covariance, COVAR_FRAC);
    467434#ifdef TESTING
    468         // Write convolution kernel
     435        }
     436#endif
     437
     438        // Extract the regions and solutions used in the image matching
     439        // This stops them from being freed when we iterate back up the FPA
     440        psArray *regions = options->regions->data[index] = psArrayAllocEmpty(ARRAY_BUFFER); // Match regions
    469441        {
    470             const char *outName = psMetadataLookupStr(NULL, config->arguments, "OUTPUT"); // Output root
    471             assert(outName);
    472 
    473             psString filename = NULL;   // Output filename
    474             psStringAppend(&filename, "%s.%d.kernel", outName, numInput);
    475             psString resolved = pmConfigConvertFilename(filename, config, true, false); // Resolved filename
    476             psFree(filename);
    477             psFits *fits = psFitsOpen(resolved, "w"); // FITS file for subtraction kernel
    478             psFree(resolved);
    479             pmReadoutWriteSubtractionKernels(output, fits);
    480             psFitsClose(fits);
    481         }
    482     }
    483 #endif
    484 
    485     readout->analysis = psMetadataCopy(readout->analysis, output->analysis);
    486 
    487 // Extract the regions and solutions used in the image matching
    488 // This stops them from being freed when we iterate back up the FPA
    489     *regions = psArrayAllocEmpty(ARRAY_BUFFER); // Array of regions
    490     {
    491         psString regex = NULL;          // Regular expression
    492         psStringAppend(&regex, "^%s$", PM_SUBTRACTION_ANALYSIS_REGION);
    493         psMetadataIterator *iter = psMetadataIteratorAlloc(output->analysis, PS_LIST_HEAD, regex); // Iterator
    494         psFree(regex);
    495         psMetadataItem *item = NULL;// Item from iteration
    496         while ((item = psMetadataGetAndIncrement(iter))) {
    497             assert(item->type == PS_DATA_REGION);
    498             *regions = psArrayAdd(*regions, ARRAY_BUFFER, item->data.V);
    499         }
    500         psFree(iter);
    501     }
    502     *kernels = psArrayAllocEmpty(ARRAY_BUFFER); // Array of kernels
    503     {
    504         psString regex = NULL;          // Regular expression
    505         psStringAppend(&regex, "^%s$", PM_SUBTRACTION_ANALYSIS_KERNEL);
    506         psMetadataIterator *iter = psMetadataIteratorAlloc(output->analysis, PS_LIST_HEAD, regex); // Iterator
    507         psFree(regex);
    508         psMetadataItem *item = NULL;// Item from iteration
    509         while ((item = psMetadataGetAndIncrement(iter))) {
    510             assert(item->type == PS_DATA_UNKNOWN);
    511             // Set the normalisation dimensions, since these will be otherwise unavailable when reading the
    512             // images by scans.
    513             pmSubtractionKernels *kernel = item->data.V; // Kernel used in subtraction
    514             kernel->numCols = readout->image->numCols;
    515             kernel->numRows = readout->image->numRows;
    516 
    517             *kernels = psArrayAdd(*kernels, ARRAY_BUFFER, kernel);
    518         }
    519         psFree(iter);
    520     }
    521     assert((*regions)->n == (*kernels)->n);
    522 
    523     // Record chi^2
    524     {
    525         *chi2 = 0.0;
    526         int num = 0;                    // Number of measurements of chi^2
    527         psString regex = NULL;          // Regular expression
    528         psStringAppend(&regex, "^%s$", PM_SUBTRACTION_ANALYSIS_KERNEL);
    529         psMetadataIterator *iter = psMetadataIteratorAlloc(output->analysis, PS_LIST_HEAD, regex); // Iterator
    530         psFree(regex);
    531         psMetadataItem *item = NULL;// Item from iteration
    532         while ((item = psMetadataGetAndIncrement(iter))) {
    533             assert(item->type == PS_DATA_UNKNOWN);
    534             pmSubtractionKernels *kernels = item->data.V; // Convolution kernels
    535             *chi2 += kernels->mean;
    536             num++;
    537         }
    538         psFree(iter);
    539         *chi2 /= psImageCovarianceFactor(readout->covariance) * num;
    540     }
    541 
    542     // Reject image completely if the maximum deconvolution fraction exceeds the limit
    543     float deconv = psMetadataLookupF32(NULL, output->analysis,
    544                                        PM_SUBTRACTION_ANALYSIS_DECONV_MAX); // Maximum deconvolution fraction
    545     if (deconv > deconvLimit) {
    546         psWarning("Maximum deconvolution fraction (%f) exceeds limit (%f) --- rejecting\n",
    547                   deconv, deconvLimit);
    548         psFree(output);
    549         return NULL;
     442            psString regex = NULL;          // Regular expression
     443            psStringAppend(&regex, "^%s$", PM_SUBTRACTION_ANALYSIS_REGION);
     444            psMetadataIterator *iter = psMetadataIteratorAlloc(conv->analysis, PS_LIST_HEAD, regex);
     445            psFree(regex);
     446            psMetadataItem *item = NULL;// Item from iteration
     447            while ((item = psMetadataGetAndIncrement(iter))) {
     448                assert(item->type == PS_DATA_REGION);
     449                regions = psArrayAdd(regions, ARRAY_BUFFER, item->data.V);
     450            }
     451            psFree(iter);
     452        }
     453        psArray *kernels = options->kernels->data[index] = psArrayAllocEmpty(ARRAY_BUFFER); // Match kernels
     454        {
     455            psString regex = NULL;          // Regular expression
     456            psStringAppend(&regex, "^%s$", PM_SUBTRACTION_ANALYSIS_KERNEL);
     457            psMetadataIterator *iter = psMetadataIteratorAlloc(conv->analysis, PS_LIST_HEAD, regex);
     458            psFree(regex);
     459            psMetadataItem *item = NULL;// Item from iteration
     460            while ((item = psMetadataGetAndIncrement(iter))) {
     461                assert(item->type == PS_DATA_UNKNOWN);
     462                // Set the normalisation dimensions, since these will be otherwise unavailable when reading
     463                // the images by scans.
     464                pmSubtractionKernels *kernel = item->data.V; // Kernel used in subtraction
     465                kernel->numCols = readout->image->numCols;
     466                kernel->numRows = readout->image->numRows;
     467
     468                kernels = psArrayAdd(kernels, ARRAY_BUFFER, kernel);
     469            }
     470            psFree(iter);
     471        }
     472        psAssert((regions)->n == (kernels)->n, "Number of match regions and kernels should match");
     473
     474        // Record chi^2
     475        {
     476            double sum = 0.0;           // Sum of chi^2
     477            int num = 0;                // Number of measurements of chi^2
     478            psString regex = NULL;      // Regular expression
     479            psStringAppend(&regex, "^%s$", PM_SUBTRACTION_ANALYSIS_KERNEL);
     480            psMetadataIterator *iter = psMetadataIteratorAlloc(conv->analysis, PS_LIST_HEAD, regex);
     481            psFree(regex);
     482            psMetadataItem *item = NULL;// Item from iteration
     483            while ((item = psMetadataGetAndIncrement(iter))) {
     484                assert(item->type == PS_DATA_UNKNOWN);
     485                pmSubtractionKernels *kernels = item->data.V; // Convolution kernels
     486                sum += kernels->mean;
     487                num++;
     488            }
     489            psFree(iter);
     490            options->matchChi2->data.F32[index] = sum / (psImageCovarianceFactor(readout->covariance) * num);
     491        }
     492
     493        // Reject image completely if the maximum deconvolution fraction exceeds the limit
     494        float deconv = psMetadataLookupF32(NULL, conv->analysis,
     495                                           PM_SUBTRACTION_ANALYSIS_DECONV_MAX); // Max deconvolution fraction
     496        if (deconv > deconvLimit) {
     497            psWarning("Maximum deconvolution fraction (%f) exceeds limit (%f) --- rejecting\n",
     498                      deconv, deconvLimit);
     499            psFree(conv);
     500            return NULL;
     501        }
     502
     503        readout->analysis = psMetadataCopy(readout->analysis, conv->analysis);
     504
     505        psFree(conv);
     506    } else {
     507        // Match the normalisation
     508        float norm = powf(10.0, -0.4 * options->norm->data.F32[index]); // Normalisation
     509        psBinaryOp(readout->image, readout->image, "*", psScalarAlloc(norm, PS_TYPE_F32));
     510        psBinaryOp(readout->variance, readout->variance, "*", psScalarAlloc(PS_SQR(norm), PS_TYPE_F32));
    550511    }
    551512
    552513    // Ensure the background value is zero
    553514    psStats *bg = psStatsAlloc(PS_STAT_ROBUST_MEDIAN | PS_STAT_ROBUST_STDEV); // Statistics for background
     515    psRandom *rng = psRandomAlloc(PS_RANDOM_TAUS); // Random number generator
    554516    if (!psImageBackground(bg, NULL, readout->image, readout->mask, maskVal | maskBad, rng)) {
    555517        psWarning("Can't measure background for image.");
     
    565527    if (!psImageBackground(bg, NULL, readout->variance, readout->mask, maskVal | maskBad, rng)) {
    566528        psError(PS_ERR_UNKNOWN, false, "Can't measure mean variance for image.");
    567         psFree(output);
     529        psFree(rng);
     530        psFree(bg);
    568531        return false;
    569532    }
    570     *weighting = 1.0 / (psStatsGetValue(bg, PS_STAT_ROBUST_MEDIAN) *
    571                         psImageCovarianceFactor(readout->covariance));
     533    options->weightings->data.F32[index] = 1.0 / (psStatsGetValue(bg, PS_STAT_ROBUST_MEDIAN) *
     534                                                  psImageCovarianceFactor(readout->covariance));
    572535    psMetadataAddF32(readout->analysis, PS_LIST_TAIL, "PPSTACK.WEIGHTING", 0,
    573                      "Weighting by 1/noise^2 for stack", *weighting);
    574 
     536                     "Weighting by 1/noise^2 for stack", options->weightings->data.F32[index]);
     537
     538    psFree(rng);
    575539    psFree(bg);
    576 
    577 #if 0
    578 #define RADIUS 10                       // Radius of photometry
    579 #define MIN_ERR 0.05                    // Minimum photometric error, mag
    580 #define MAX_MAG -13                     // Maximum magnitude for source
    581 
    582     // Ensure the normalisation is correct
    583     // XXX Ideally, would like to do proper PSF-fit photometry, but will settle for aperture photometry
    584     int numSources = sources->n;        // Number of sources
    585     psVector *ratio = psVectorAlloc(numSources, PS_TYPE_F32); // Flux ratios for sources
    586     psVector *ratioMask = psVectorAlloc(numSources, PS_TYPE_MASK); // Mask for flux ratios
    587     psVectorInit(ratioMask, 0xFF);
    588     psImage *image = readout->image;    // Image of interest
    589     psImage *mask = readout->mask;      // Mask of interest
    590     int numCols = image->numCols, numRows = image->numRows; // Size of image
    591     for (int i = 0; i < numSources; i++) {
    592         pmSource *source = sources->data[i]; // Source of interest
    593         if (!source || source->mode & SOURCE_MASK || !isfinite(source->psfMag) || !isfinite(source->errMag) ||
    594             source->errMag > MIN_ERR || source->psfMag > MAX_MAG) {
    595             continue;
    596         }
    597 
    598         float xSrc, ySrc;              // Source coordinates
    599         coordsFromSource(&xSrc, &ySrc, source);
    600         int xMin = PS_MAX(0, xSrc - RADIUS), xMax = PS_MIN(numCols - 1, xSrc + RADIUS); // Bounds in x
    601         int yMin = PS_MAX(0, ySrc - RADIUS), yMax = PS_MIN(numRows - 1, ySrc + RADIUS); // Bounds in y
    602         int numPix = 0;                 // Number of pixels
    603         float sum = 0.0;                // Sum of pixels
    604         for (int y = yMin; y <= yMax; y++) {
    605             for (int x = xMin; x <= xMax; x++) {
    606                 if (mask->data.PS_TYPE_MASK_DATA[y][x] & maskBad) {
    607                     continue;
    608                 }
    609                 sum += image->data.F32[y][x];
    610                 numPix++;
    611             }
    612         }
    613         if (sum >= 0 && numPix > 0) {
    614             float mag = -2.5 * log10(sum * M_PI * PS_SQR(RADIUS) / numPix); // Instrumental magnitude
    615             ratio->data.F32[i] = mag - source->psfMag;
    616             ratioMask->data.PS_TYPE_MASK_DATA[i] = 0;
    617         }
    618     }
    619 
    620     psStats *stats = psStatsAlloc(PS_STAT_ROBUST_MEDIAN | PS_STAT_ROBUST_STDEV); // Statistics
    621     if (!psVectorStats(stats, ratio, NULL, ratioMask, 0xFF)) {
    622         psWarning("Unable to measure normalisation --- assuming correct.");
    623     } else {
    624         psLogMsg("ppStack", PS_LOG_INFO, "Renormalising image by %f (+/- %f) mag\n",
    625                  stats->robustMedian, stats->robustStdev);
    626         float norm = powf(10.0, -0.4 * stats->robustMedian); // Normalisation to apply
    627         psBinaryOp(image, image, "*", psScalarAlloc(norm, PS_TYPE_F32));
    628     }
    629     psFree(stats);
    630     psFree(ratio);
    631     psFree(ratioMask);
    632 #endif
    633540
    634541#ifdef TESTING
     
    636543        pmHDU *hdu = pmHDUFromCell(readout->parent);
    637544        psString name = NULL;
    638         psStringAppend(&name, "convolved_%03d.fits", numInput);
    639         pmStackVisualPlotTestImage(output->image, name);
     545        psStringAppend(&name, "convolved_%03d.fits", index);
     546        pmStackVisualPlotTestImage(readout->image, name);
    640547        psFits *fits = psFitsOpen(name, "w");
    641548        psFree(name);
    642         psFitsWriteImage(fits, hdu->header, output->image, 0, NULL);
     549        psFitsWriteImage(fits, hdu->header, readout->image, 0, NULL);
    643550        psFitsClose(fits);
    644551    }
    645552#endif
    646 
    647     psFree(output);
    648553
    649554    return true;
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackOptions.c

    r23352 r23594  
    1818    psFree(options->inputMask);
    1919    psFree(options->sourceLists);
     20    psFree(options->norm);
    2021    psFree(options->cells);
    21     psFree(options->subKernels);
    22     psFree(options->subRegions);
     22    psFree(options->kernels);
     23    psFree(options->regions);
    2324    psFree(options->matchChi2);
    2425    psFree(options->weightings);
     
    3536    psMemSetDeallocator(options, (psFreeFunc)stackOptionsFree);
    3637
     38    options->convolve = true;
    3739    options->stats = NULL;
    3840    options->statsFile = NULL;
     
    4446    options->inputMask = NULL;
    4547    options->sourceLists = NULL;
     48    options->norm = NULL;
    4649    options->cells = NULL;
    47     options->subKernels = NULL;
    48     options->subRegions = NULL;
     50    options->kernels = NULL;
     51    options->regions = NULL;
    4952    options->numCols = 0;
    5053    options->numRows = 0;
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackOptions.h

    r23352 r23594  
    88typedef struct {
    99    // Setup
     10    bool convolve;                      // Convolve images?
    1011    psMetadata *stats;                  // Statistics for output
    1112    FILE *statsFile;                    // File to which to write statistics
     
    1718    psVector *inputMask;                // Mask for inputs
    1819    psArray *sourceLists;               // Individual lists of sources for matching
     20    psVector *norm;                     // Normalisation for each image
    1921    // Convolve
    2022    psArray *cells;                     // Cells for convolved images --- a handle for reading again
    21     psArray *subKernels;                // Subtraction kernels --- required in the stacking
    22     psArray *subRegions;                // Subtraction regions --- required in the stacking
     23    psArray *kernels;                   // PSF-matching kernels --- required in the stacking
     24    psArray *regions;                   // PSF-matching regions --- required in the stacking
    2325    int numCols, numRows;               // Size of image
    2426    psVector *matchChi2;                // chi^2 for stamps from matching
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackPhotometry.c

    r23352 r23594  
    7474        return false;
    7575    }
    76     psFree(photView);
    7776
    7877    if (!pmFPAfileDropInternal(config->files, "PSPHOT.BACKMDL") ||
     
    9392                         "Time to do photometry", psTimerMark("PPSTACK_PHOT"));
    9493    }
     94    psFree(photView);
     95
    9596    psLogMsg("ppStack", PS_LOG_INFO, "Time to do photometry: %f sec", psTimerClear("PPSTACK_PHOT"));
    9697
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackPrepare.c

    r23352 r23594  
    127127    psVectorInit(options->inputMask, 0);
    128128
    129     if (psMetadataLookupBool(NULL, config->arguments, "HAVE.PSF")) {
    130         pmFPAfileActivate(config->files, false, NULL);
    131         ppStackFileActivation(config, PPSTACK_FILES_PREPARE, true);
    132         pmFPAview *view = ppStackFilesIterateDown(config);
    133         if (!view) {
    134             return false;
    135         }
    136 
    137         // Generate list of PSFs
    138         psMetadataIterator *fileIter = psMetadataIteratorAlloc(config->files, PS_LIST_HEAD,
    139                                                                "^PPSTACK.INPUT$"); // Iterator
    140         psMetadataItem *fileItem; // Item from iteration
    141         psArray *psfs = psArrayAlloc(num); // PSFs for PSF envelope
    142         int numCols = 0, numRows = 0;   // Size of image
    143         int index = 0;                  // Index for file
    144         while ((fileItem = psMetadataGetAndIncrement(fileIter))) {
    145             assert(fileItem->type == PS_DATA_UNKNOWN);
    146             pmFPAfile *inputFile = fileItem->data.V; // An input file
     129    pmFPAfileActivate(config->files, false, NULL);
     130    ppStackFileActivation(config, PPSTACK_FILES_PREPARE, true);
     131    pmFPAview *view = ppStackFilesIterateDown(config);
     132    if (!view) {
     133        return false;
     134    }
     135
     136    psMetadataIterator *fileIter = psMetadataIteratorAlloc(config->files, PS_LIST_HEAD, "^PPSTACK.INPUT$");
     137    psMetadataItem *fileItem; // Item from iteration
     138    psArray *psfs = psArrayAlloc(num); // PSFs for PSF envelope
     139    int numCols = 0, numRows = 0;   // Size of image
     140    int index = 0;                  // Index for file
     141    while ((fileItem = psMetadataGetAndIncrement(fileIter))) {
     142        assert(fileItem->type == PS_DATA_UNKNOWN);
     143        pmFPAfile *inputFile = fileItem->data.V; // An input file
     144
     145        // Get list of PSFs, to determine target PSF
     146        if (options->convolve) {
    147147            pmChip *chip = pmFPAviewThisChip(view, inputFile->fpa); // The chip: holds the PSF
    148148            pmPSF *psf = psMetadataLookupPtr(NULL, chip->analysis, "PSPHOT.PSF"); // PSF
     
    173173                numRows = naxis2;
    174174            }
    175 
    176             pmReadout *ro = pmFPAviewThisReadout(view, inputFile->fpa); // Readout with sources
    177             psArray *sources = psMetadataLookupPtr(NULL, ro->analysis, "PSPHOT.SOURCES"); // Sources
    178             if (!sources) {
    179                 psError(PS_ERR_UNEXPECTED_NULL, false, "Unable to find sources in readout.");
    180                 return NULL;
    181             }
    182             options->sourceLists->data[index] = psMemIncrRefCounter(sources);
    183 
    184             // Re-do photometry if we don't trust the source lists
    185             if (psMetadataLookupBool(NULL, recipe, "PHOT")) {
    186                 psTrace("ppStack", 2, "Photometering input %d of %d....\n", index, num);
    187                 pmFPAfileActivate(config->files, false, NULL);
    188                 ppStackFileActivationSingle(config, PPSTACK_FILES_CONVOLVE, true, index);
    189                 pmFPAfile *file = pmFPAfileSelectSingle(config->files, "PPSTACK.INPUT", index); // File
    190                 pmFPAview *photView = ppStackFilesIterateDown(config);
    191                 if (!photView) {
    192                     psFree(view);
    193                     return false;
    194                 }
    195 
    196                 pmReadout *ro = pmFPAviewThisReadout(view, file->fpa); // Readout of interest
    197 
    198                 if (!ppStackInputPhotometer(ro, sources, config)) {
    199                     psError(PS_ERR_UNKNOWN, false, "Unable to do photometry on input sources");
    200                     psFree(view);
    201                     psFree(photView);
    202                     return false;
    203                 }
    204 
     175        }
     176
     177
     178        pmReadout *ro = pmFPAviewThisReadout(view, inputFile->fpa); // Readout with sources
     179        psArray *sources = psMetadataLookupPtr(NULL, ro->analysis, "PSPHOT.SOURCES"); // Sources
     180        if (!sources) {
     181            psError(PS_ERR_UNEXPECTED_NULL, false, "Unable to find sources in readout.");
     182            return NULL;
     183        }
     184        options->sourceLists->data[index] = psMemIncrRefCounter(sources);
     185
     186        // Re-do photometry if we don't trust the source lists
     187        if (psMetadataLookupBool(NULL, recipe, "PHOT")) {
     188            psTrace("ppStack", 2, "Photometering input %d of %d....\n", index, num);
     189            pmFPAfileActivate(config->files, false, NULL);
     190            ppStackFileActivationSingle(config, PPSTACK_FILES_CONVOLVE, true, index);
     191            pmFPAfile *file = pmFPAfileSelectSingle(config->files, "PPSTACK.INPUT", index); // File
     192            pmFPAview *photView = ppStackFilesIterateDown(config);
     193            if (!photView) {
     194                psFree(view);
     195                return false;
     196            }
     197
     198            pmReadout *ro = pmFPAviewThisReadout(view, file->fpa); // Readout of interest
     199
     200            if (!ppStackInputPhotometer(ro, sources, config)) {
     201                psError(PS_ERR_UNKNOWN, false, "Unable to do photometry on input sources");
     202                psFree(view);
    205203                psFree(photView);
    206                 if (!ppStackFilesIterateUp(config)) {
    207                     psFree(view);
    208                     return false;
    209                 }
    210                 pmFPAfileActivate(config->files, false, NULL);
    211                 ppStackFileActivation(config, PPSTACK_FILES_PREPARE, true);
    212             }
    213 
    214             index++;
    215         }
    216         psFree(fileIter);
    217 
    218         // Zero point calibration
    219         options->sumExposure = ppStackSourcesTransparency(options->sourceLists, options->inputMask,
    220                                                           view, config);
    221         if (!isfinite(options->sumExposure) || options->sumExposure <= 0) {
    222             psError(PS_ERR_UNKNOWN, false, "Unable to calculate transparency differences");
    223             psFree(view);
    224             return false;
    225         }
    226 
    227         // Generate target PSF
     204                return false;
     205            }
     206
     207            psFree(photView);
     208            if (!ppStackFilesIterateUp(config)) {
     209                psFree(view);
     210                return false;
     211            }
     212            pmFPAfileActivate(config->files, false, NULL);
     213            ppStackFileActivation(config, PPSTACK_FILES_PREPARE, true);
     214        }
     215
     216        index++;
     217    }
     218    psFree(fileIter);
     219
     220    // Generate target PSF
     221    if (options->convolve) {
    228222        options->psf = ppStackPSF(config, numCols, numRows, psfs, options->inputMask);
    229223        psFree(psfs);
     
    240234                         "Target PSF", options->psf);
    241235        outChip->data_exists = true;
    242 
     236    }
     237
     238    // Zero point calibration
     239    if (!ppStackSourcesTransparency(options, view, config)) {
     240        psError(PS_ERR_UNKNOWN, false, "Unable to calculate transparency differences");
    243241        psFree(view);
    244 
    245         if (!ppStackFilesIterateUp(config)) {
    246             return false;
    247         }
     242        return false;
     243    }
     244    psFree(view);
     245
     246    if (!ppStackFilesIterateUp(config)) {
     247        return false;
    248248    }
    249249
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackReadout.c

    r23352 r23594  
    150150
    151151    if (!pmStackCombine(outRO, stack, maskVal | maskBad, maskBad, kernelSize, iter,
    152                         combineRej, combineSys, combineDiscard, true, useVariance, safe)) {
     152                        combineRej, combineSys, combineDiscard, true, useVariance, safe, false)) {
    153153        psError(PS_ERR_UNKNOWN, false, "Unable to combine input readouts with rejection.");
    154154        psFree(stack);
     
    185185    assert(outRO);
    186186    assert(readouts);
    187     assert(rejected);
    188     assert(readouts->n == rejected->n);
     187    assert(!rejected || readouts->n == rejected->n);
    189188    assert(mask && mask->n == readouts->n && mask->type.type == PS_TYPE_VECTOR_MASK);
    190189    assert(weightings && weightings->n == readouts->n && weightings->type.type == PS_TYPE_F32);
     
    197196
    198197    bool mdok;                          // Status of MD lookup
     198    int iter = psMetadataLookupS32(NULL, recipe, "ITER"); // Rejection iterations
     199    float combineRej = psMetadataLookupF32(NULL, recipe, "COMBINE.REJ"); // Combination threshold
     200    float combineSys = psMetadataLookupF32(NULL, recipe, "COMBINE.SYS"); // Combination systematic error
     201    float combineDiscard = psMetadataLookupF32(NULL, recipe, "COMBINE.DISCARD"); // Olympic discard fraction
    199202    bool useVariance = psMetadataLookupBool(&mdok, recipe, "VARIANCE"); // Use variance for rejection?
     203    bool safe = psMetadataLookupBool(&mdok, recipe, "SAFE"); // Be safe when combining small numbers of pixels
    200204
    201205    psString maskValStr = psMetadataLookupStr(NULL, recipe, "MASK.VAL"); // Name of bits to mask going in
     
    207211    psArray *stack = psArrayAlloc(num); // Array for stacking
    208212
    209     int numGood = num;                  // Number of good inputs: images that haven't been completely rejected
     213    bool entire = true;                 // Combine entire image?
     214    if (rejected) {
     215        // We have rejection from a previous combination: combine without flagging pixels to inspect
     216        entire = false;
     217        safe = false;
     218        iter = 0;
     219        combineRej = NAN;
     220        combineSys = NAN;
     221    }
     222
    210223    for (int i = 0; i < num; i++) {
    211224        pmReadout *ro = readouts->data[i];
    212         if (!ro || !rejected->data[i] || mask->data.PS_TYPE_VECTOR_MASK_DATA[i]) {
    213             // Image completely rejected
    214             numGood--;
     225        if (mask->data.U8[i] & (PPSTACK_MASK_REJECT | PPSTACK_MASK_BAD)) {
     226            // Image completely rejected since previous combination
     227            entire = true;
     228            continue;
     229        } else if (mask->data.U8[i]) {
     230            // Image completely rejected before original combination
    215231            continue;
    216232        }
     
    234250        pmStackData *data = pmStackDataAlloc(ro, weightings->data.F32[i],
    235251                                             addVariance ? addVariance->data.F32[i] : NAN);
    236         data->reject = psMemIncrRefCounter(rejected->data[i]);
     252        data->reject = rejected ? psMemIncrRefCounter(rejected->data[i]) : NULL;
    237253        stack->data[i] = data;
    238254    }
    239255
    240     if (!pmStackCombine(outRO, stack, maskVal | maskBad, maskBad, 0, 0, NAN, NAN, NAN,
    241                         numGood != num, useVariance, false)) {
     256    if (!pmStackCombine(outRO, stack, maskVal | maskBad, maskBad, 0,
     257                        iter, combineRej, combineSys, combineDiscard,
     258                        entire, useVariance, safe, !rejected)) {
    242259        psError(PS_ERR_UNKNOWN, false, "Unable to combine input readouts.");
    243260        psFree(stack);
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackReject.c

    r23352 r23594  
    1414    psAssert(options, "Require options");
    1515    psAssert(config, "Require configuration");
     16
     17    if (!options->convolve) {
     18        // No need to do complicated rejection when we haven't convolved
     19        return true;
     20    }
    1621
    1722    int num = options->num;             // Number of inputs
     
    8691
    8792        psPixels *reject = pmStackReject(options->inspect->data[i], options->numCols, options->numRows,
    88                                          threshold, poorFrac, stride, options->subRegions->data[i],
    89                                          options->subKernels->data[i]); // Rejected pixels
     93                                         threshold, poorFrac, stride, options->regions->data[i],
     94                                         options->kernels->data[i]); // Rejected pixels
    9095
    9196#ifdef TESTING
     
    141146
    142147    psFree(options->inspect); options->inspect = NULL;
    143     psFree(options->subKernels); options->subKernels = NULL;
    144     psFree(options->subRegions); options->subRegions = NULL;
     148    psFree(options->kernels); options->kernels = NULL;
     149    psFree(options->regions); options->regions = NULL;
    145150
    146151    if (numRejected >= num - 1) {
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackSetup.c

    r23352 r23594  
    1111#include "ppStackLoop.h"
    1212
     13#define BUFFER 16                       // Buffer for name array
     14
     15// Generate an array of input filenames
     16static psArray *stackNameArray(const ppStackOptions *options, // Stack options
     17                               pmConfig *config, // Configuration
     18                               const char *name // Name of file
     19    )
     20{
     21    psAssert(config, "Require configuration");
     22    psAssert(config, "Require file name");
     23
     24    psArray *array = psArrayAllocEmpty(options->num); // Array with filenames
     25    pmFPAview *view = pmFPAviewAlloc(0);// View to readout
     26    view->chip = view->cell = view->readout = -1;
     27
     28    for (int i = 0; i < options->num; i++) {
     29        pmFPAfile *file = pmFPAfileSelectSingle(config->files, name, i); // File of interest
     30
     31        psString filename = pmFPAfileName(file, view, config); // Filename of interest
     32        psAssert(filename, "Can't determine filename");
     33        psArrayAdd(array, array->n, filename);
     34        psFree(filename);               // Drop reference
     35    }
     36
     37    return array;
     38}
     39
     40
    1341bool ppStackSetup(ppStackOptions *options, pmConfig *config)
    1442{
     
    1846    psMetadata *recipe = psMetadataLookupMetadata(NULL, config->recipes, PPSTACK_RECIPE); // ppStack recipe
    1947    psAssert(recipe, "We've thrown an error on this before.");
     48
     49    options->convolve = psMetadataLookupBool(NULL, config->arguments, "CONVOLVE"); // Convolve images?
     50    if (!psMetadataLookupBool(NULL, config->arguments, "HAVE.PSF")) {
     51        psWarning("No PSFs provided --- unable to convolve to common PSF.");
     52        options->convolve = false;
     53    }
    2054
    2155    int num = psMetadataLookupS32(NULL, config->arguments, "INPUTS.NUM"); // Number of inputs
     
    3670    }
    3771
    38     const char *tempDir = psMetadataLookupStr(NULL, recipe, "TEMP.DIR"); // Directory for temporary images
    39     if (!tempDir) {
    40         psError(PS_ERR_BAD_PARAMETER_VALUE, false, "Unable to find TEMP.DIR in recipe");
    41         return false;
     72    // Generate temporary names for convolved images
     73    if (options->convolve) {
     74        const char *tempDir = psMetadataLookupStr(NULL, recipe, "TEMP.DIR"); // Directory for temporary images
     75        if (!tempDir) {
     76            psError(PS_ERR_BAD_PARAMETER_VALUE, false, "Unable to find TEMP.DIR in recipe");
     77            return false;
     78        }
     79
     80        psString outputName = psStringCopy(psMetadataLookupStr(NULL, config->arguments,
     81                                                               "OUTPUT")); // Name for temporary files
     82        const char *tempName = basename(outputName);
     83        if (!tempName) {
     84            psError(PS_ERR_BAD_PARAMETER_VALUE, false, "Unable to construct basename for temporary files.");
     85            psFree(outputName);
     86            return false;
     87        }
     88
     89        const char *tempImage = psMetadataLookupStr(NULL, recipe, "TEMP.IMAGE"); // Suffix for images
     90        const char *tempMask = psMetadataLookupStr(NULL, recipe, "TEMP.MASK"); // Suffix for masks
     91        const char *tempVariance = psMetadataLookupStr(NULL, recipe, "TEMP.VARIANCE"); // Suffix for var maps
     92        if (!tempImage || !tempMask || !tempVariance) {
     93            psError(PS_ERR_BAD_PARAMETER_VALUE, false,
     94                    "Unable to find TEMP.IMAGE, TEMP.MASK and TEMP.VARIANCE in recipe");
     95            psFree(outputName);
     96            return false;
     97        }
     98
     99        options->imageNames = psArrayAlloc(num);
     100        options->maskNames = psArrayAlloc(num);
     101        options->varianceNames = psArrayAlloc(num);
     102        for (int i = 0; i < num; i++) {
     103            psString imageName = NULL, maskName = NULL, varianceName = NULL; // Names for convolved images
     104            psStringAppend(&imageName, "%s/%s.%d.%s", tempDir, tempName, i, tempImage);
     105            psStringAppend(&maskName, "%s/%s.%d.%s", tempDir, tempName, i, tempMask);
     106            psStringAppend(&varianceName, "%s/%s.%d.%s", tempDir, tempName, i, tempVariance);
     107            psTrace("ppStack", 5, "Temporary files: %s %s %s\n", imageName, maskName, varianceName);
     108            options->imageNames->data[i] = imageName;
     109            options->maskNames->data[i] = maskName;
     110            options->varianceNames->data[i] = varianceName;
     111        }
     112        psFree(outputName);
     113    } else {
     114        options->imageNames = stackNameArray(options, config, "PPSTACK.INPUT");
     115        options->maskNames = stackNameArray(options, config, "PPSTACK.INPUT.MASK");
     116        options->varianceNames = stackNameArray(options, config, "PPSTACK.INPUT.VARIANCE");
    42117    }
    43 
    44     psString outputName = psStringCopy(psMetadataLookupStr(NULL, config->arguments,
    45                                                            "OUTPUT")); // Name for temporary files
    46     const char *tempName = basename(outputName);
    47     if (!tempName) {
    48         psError(PS_ERR_BAD_PARAMETER_VALUE, false, "Unable to construct basename for temporary files.");
    49         psFree(outputName);
    50         return false;
    51     }
    52 
    53     const char *tempImage = psMetadataLookupStr(NULL, recipe, "TEMP.IMAGE"); // Suffix for temporary images
    54     const char *tempMask = psMetadataLookupStr(NULL, recipe, "TEMP.MASK"); // Suffix for temporary masks
    55     const char *tempVariance = psMetadataLookupStr(NULL, recipe, "TEMP.VARIANCE"); // Suffix for temp var maps
    56     if (!tempImage || !tempMask || !tempVariance) {
    57         psError(PS_ERR_BAD_PARAMETER_VALUE, false,
    58                 "Unable to find TEMP.IMAGE, TEMP.MASK and TEMP.VARIANCE in recipe");
    59         psFree(outputName);
    60         return false;
    61     }
    62 
    63     options->imageNames = psArrayAlloc(num);
    64     options->maskNames = psArrayAlloc(num);
    65     options->varianceNames = psArrayAlloc(num);
    66     for (int i = 0; i < num; i++) {
    67         psString imageName = NULL, maskName = NULL, varianceName = NULL; // Names for convolved images
    68         psStringAppend(&imageName, "%s/%s.%d.%s", tempDir, tempName, i, tempImage);
    69         psStringAppend(&maskName, "%s/%s.%d.%s", tempDir, tempName, i, tempMask);
    70         psStringAppend(&varianceName, "%s/%s.%d.%s", tempDir, tempName, i, tempVariance);
    71         psTrace("ppStack", 5, "Temporary files: %s %s %s\n", imageName, maskName, varianceName);
    72         options->imageNames->data[i] = imageName;
    73         options->maskNames->data[i] = maskName;
    74         options->varianceNames->data[i] = varianceName;
    75     }
    76     psFree(outputName);
    77118
    78119    if (!pmConfigMaskSetBits(NULL, NULL, config)) {
  • branches/cnb_branches/cnb_branch_20090301/ppStack/src/ppStackSources.c

    r23352 r23594  
    99//#define TESTING                         // Enable debugging output
    1010
     11#ifdef TESTING
    1112// Size of fake image; set by hand because it's trouble to get it from other places
    1213#define FAKE_COLS 4861
    1314#define FAKE_ROWS 4913
     15#endif
    1416
    1517#ifdef TESTING
     
    5355
    5456
    55 float ppStackSourcesTransparency(const psArray *sourceLists, psVector *inputMask,
    56                                  const pmFPAview *view, const pmConfig *config)
     57bool ppStackSourcesTransparency(ppStackOptions *options, const pmFPAview *view, const pmConfig *config)
    5758{
    58     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);
    62     PS_ASSERT_PTR_NON_NULL(view, NAN);
    63     PS_ASSERT_PTR_NON_NULL(config, NAN);
     59    PS_ASSERT_PTR_NON_NULL(options, false);
     60    PS_ASSERT_PTR_NON_NULL(view, false);
     61    PS_ASSERT_PTR_NON_NULL(config, false);
     62
     63    psArray *sourceLists = options->sourceLists; // Source lists for each input
     64    psVector *inputMask = options->inputMask; // Mask for inputs
     65
     66    PS_ASSERT_ARRAY_NON_NULL(sourceLists, false);
     67    PS_ASSERT_VECTOR_NON_NULL(inputMask, false);
     68    PS_ASSERT_VECTOR_TYPE(inputMask, PS_TYPE_U8, false);
     69    PS_ASSERT_VECTOR_SIZE(inputMask, sourceLists->n, false);
    6470
    6571#if defined(TESTING) && 0
     
    100106    if (!airmassZP) {
    101107        psError(PS_ERR_UNKNOWN, false, "Unable to find ZP.AIRMASS in recipe.");
    102         return NAN;
     108        return false;
    103109    }
    104110
     
    139145                    exptime, airmass, expFilter);
    140146            psFree(zp);
    141             return NAN;
     147            return false;
    142148        }
    143149
     
    149155                        "Unable to find airmass term (ZP.AIRMASS) for filter %s", filter);
    150156                psFree(zp);
    151                 return NAN;
     157                return false;
    152158            }
    153159        } else if (strcmp(filter, expFilter) != 0) {
    154160            psError(PS_ERR_BAD_PARAMETER_VALUE, false, "Filters don't match: %s vs %s", filter, expFilter);
    155161            psFree(zp);
    156             return NAN;
     162            return false;
    157163        }
    158164
     
    160166        sumExpTime += exptime;
    161167    }
     168
     169    options->sumExposure = sumExpTime;
    162170
    163171    psArray *matches = pmSourceMatchSources(sourceLists, radius, true); // List of matches
     
    165173        psError(PS_ERR_UNKNOWN, false, "Unable to match sources");
    166174        psFree(zp);
    167         return NAN;
     175        return false;
    168176    }
    169177
     
    177185    if (!trans) {
    178186        psError(PS_ERR_UNKNOWN, false, "Unable to measure transparencies");
    179         return NAN;
     187        return false;
    180188    }
    181189
     
    186194    for (int i = 0; i < trans->n; i++) {
    187195        if (!isfinite(trans->data.F32[i])) {
    188             inputMask->data.U8[i] = PPSTACK_MASK_CAL;
     196            inputMask->data.U8[i] |= PPSTACK_MASK_CAL;
    189197        }
    190198    }
     
    223231    // m_0 = m_1 + zp_1 + trans_1 - c1 * airmass_0 - 2.5log(t_0)
    224232    // We don't need to know the magnitude zero point for the filter, since it cancels out
     233    options->norm = psVectorAlloc(num, PS_TYPE_F32);
    225234    for (int i = 0; i < num; i++) {
    226235        if (!isfinite(trans->data.F32[i])) {
     
    229238        psArray *sources = sourceLists->data[i]; // Sources of interest
    230239        float magCorr = airmassTerm - 2.5*log10(sumExpTime) - zp->data.F32[i] - trans->data.F32[i];
     240        options->norm->data.F32[i] = magCorr;
    231241        psLogMsg("ppStack", PS_LOG_INFO, "Applying magnitude correction to image %d: %f\n", i, magCorr);
    232242
     
    248258            psError(PS_ERR_UNKNOWN, false, "Unable to match sources");
    249259            psFree(zp);
    250             return NAN;
     260            return false;
    251261        }
    252262        psVector *trans = pmSourceMatchRelphot(matches, zp, iter, tol, starLimit, transIter, transRej,
     
    259269#endif
    260270
    261     return sumExpTime;
     271    return true;
    262272}
  • branches/cnb_branches/cnb_branch_20090301/ppStats/src/ppStats.h

    r23352 r23594  
    149149
    150150// used by ppStatsFromMetadata:
    151 psDataType psDataTypeFromString (char *typename);
    152 ppStatsEntry *ppStatsEntryAlloc ();
     151psDataType psDataTypeFromString(char *typename);
     152ppStatsEntry *ppStatsEntryAlloc(void);
    153153
    154154psArray *ppStatsFromMetadataEntries (psMetadata *recipe);
  • branches/cnb_branches/cnb_branch_20090301/ppSub

  • branches/cnb_branches/cnb_branch_20090301/ppSub/src/ppSubArguments.c

    r23352 r23594  
    260260    }
    261261
    262     psMetadataAddStr(config->arguments, PS_LIST_TAIL, "OUTPUT", 0, "Name of the output image", argv[3]);
     262    psMetadataAddStr(config->arguments, PS_LIST_TAIL, "OUTPUT", 0, "Name of the output image", argv[1]);
    263263
    264264
     
    282282    const char *refImage = psMetadataLookupStr(NULL, arguments, "-refimage"); // Name of reference image
    283283    if (refImage && strlen(refImage) > 0) {
    284         fileList("INPUT", refImage, "Name of the reference image", config);
     284        fileList("REF", refImage, "Name of the reference image", config);
    285285    }
    286286    const char *refMask = psMetadataLookupStr(NULL, arguments, "-refmask"); // Name of reference mask
  • branches/cnb_branches/cnb_branch_20090301/ppSub/src/ppSubCamera.c

    r23352 r23594  
    3333
    3434    // look for the file on the RUN metadata
    35     pmFPAfile *file = pmFPAfileDefineFromRun(&status, config, filerule); // File to return
     35    pmFPAfile *file = pmFPAfileDefineFromRun(&status, bind, config, filerule); // File to return
    3636    if (!status) {
    3737        psError(PS_ERR_UNKNOWN, false, "Failed to load file definition for %s", filerule);
     
    6666static pmFPAfile *defineOutputFile(pmConfig *config, // Configuration
    6767                                   pmFPAfile *template,    // File to use as basis for definition
     68                                   bool source, // Is template a source (T), or for binding (F)?
    6869                                   char *filerule,     // Name of file rule
    6970                                   pmFPAfileType fileType // Type of file
     
    7172{
    7273
    73     pmFPAfile *file = pmFPAfileDefineFromFile(config, template, 1, 1, filerule);
     74    pmFPAfile *file = source ? pmFPAfileDefineFromFile(config, template, 1, 1, filerule) :
     75        pmFPAfileDefineOutput(config, template->fpa, filerule);
    7476    if (!file) {
    7577        psError(PS_ERR_IO, false, _("Unable to generate output file from %s"), filerule);
     
    9698
    9799    // look for the file on the RUN metadata
    98     pmFPAfile *file = pmFPAfileDefineFromRun(&status, config, filerule); // File to return
     100    pmFPAfile *file = pmFPAfileDefineFromRun(&status, bind, config, filerule); // File to return
    99101    if (!status) {
    100102        psError(PS_ERR_UNKNOWN, false, "Failed to load file definition for %s", filerule);
     
    108110    // define new version of file
    109111    if (!file) {
    110         pmFPAfileDefineOutput(config, bind ? bind->fpa : NULL, filerule);
     112        file = pmFPAfileDefineOutput(config, bind ? bind->fpa : NULL, filerule);
    111113        if (!status) {
    112114            psError(PS_ERR_UNKNOWN, false, "Failed to load file definition for %s", filerule);
     
    160162
    161163    // Output 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    pmFPAfile *output = defineOutputFile(config, input, true, "PPSUB.OUTPUT", PM_FPA_FILE_IMAGE);
     165    pmFPAfile *outMask = defineOutputFile(config, output, false, "PPSUB.OUTPUT.MASK", PM_FPA_FILE_MASK);
    164166    if (!output || !outMask) {
    165167        psError(PS_ERR_UNKNOWN, false, "Unable to define output files");
     
    170172    pmFPAfile *outVar = NULL;
    171173    if (inVar && refVar) {
    172         outVar = defineOutputFile(config, output, "PPSUB.OUTPUT.VARIANCE", PM_FPA_FILE_VARIANCE);
     174        outVar = defineOutputFile(config, output, false, "PPSUB.OUTPUT.VARIANCE", PM_FPA_FILE_VARIANCE);
    173175        if (!outVar) {
    174176            psError(PS_ERR_UNKNOWN, false, "Unable to define output files");
     
    180182
    181183    // Convolved input image
    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    pmFPAfile *inConvImage = defineOutputFile(config, input, true, "PPSUB.INPUT.CONV", PM_FPA_FILE_IMAGE);
     185    pmFPAfile *inConvMask = defineOutputFile(config, inConvImage, false, "PPSUB.INPUT.CONV.MASK",
     186                                             PM_FPA_FILE_MASK);
    184187    if (!inConvImage || !inConvMask) {
    185188        psError(PS_ERR_UNKNOWN, false, "Unable to define output files");
     
    187190    }
    188191    if (inVar) {
    189         pmFPAfile *inConvVar = defineOutputFile(config, input, "PPSUB.INPUT.CONV.VARIANCE",
     192        pmFPAfile *inConvVar = defineOutputFile(config, inConvImage, false, "PPSUB.INPUT.CONV.VARIANCE",
    190193                                                PM_FPA_FILE_VARIANCE);
    191194        if (!inConvVar) {
     
    196199
    197200    // Convolved ref image
    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);
     201    pmFPAfile *refConvImage = defineOutputFile(config, input, true, "PPSUB.REF.CONV", PM_FPA_FILE_IMAGE);
     202    pmFPAfile *refConvMask = defineOutputFile(config, refConvImage, false, "PPSUB.REF.CONV.MASK",
     203                                              PM_FPA_FILE_MASK);
    200204    if (!refConvImage || !refConvMask) {
    201205        psError(PS_ERR_UNKNOWN, false, "Unable to define output files");
     
    203207    }
    204208    if (refVar) {
    205         pmFPAfile *refConvVar = defineOutputFile(config, input, "PPSUB.REF.CONV.VARIANCE",
     209        pmFPAfile *refConvVar = defineOutputFile(config, refConvImage, false, "PPSUB.REF.CONV.VARIANCE",
    206210                                                 PM_FPA_FILE_VARIANCE);
    207211        if (!refConvVar) {
  • branches/cnb_branches/cnb_branch_20090301/ppSub/src/ppSubDefineOutput.c

    r21524 r23594  
    2626    psAssert(view, "Require view");
    2727
    28     // generate an output readout
    2928    pmCell *outCell = pmFPAfileThisCell(config->files, view, "PPSUB.OUTPUT"); // Output cell
    30     pmReadout *outRO = pmReadoutAlloc(outCell); // Output readout: subtraction
    3129    pmFPA *outFPA = outCell->parent->parent; // Output FPA
    3230    pmHDU *outHDU = outFPA->hdu; // Output HDU
    3331    if (!outHDU->header) {
    3432        outHDU->header = psMetadataAlloc();
     33    }
     34
     35    // generate an output readout (first check if it's already there by virtue of kernels)
     36    pmReadout *outRO = pmFPAfileThisReadout(config->files, view, "PPSUB.OUTPUT.KERNELS"); // RO with kernel
     37    if (!outRO) {
     38        outRO = pmReadoutAlloc(outCell); // Output readout: subtraction
    3539    }
    3640
  • branches/cnb_branches/cnb_branch_20090301/ppSub/src/ppSubMatchPSFs.c

    r23352 r23594  
    5050
    5151    // Load pre-calculated kernel, if available
    52     pmReadout *kernelRO = pmFPAfileThisReadout(config->files, view, "PPSUB.OUTPUT.KERNEL"); // RO with kernel
     52    pmReadout *kernelRO = pmFPAfileThisReadout(config->files, view, "PPSUB.OUTPUT.KERNELS"); // RO with kernel
    5353
    5454    // Sources in image, used for stamps: these must be loaded from previous analysis stages
     
    123123    float optThresh = psMetadataLookupF32(&mdok, recipe, "OPTIMUM.TOL"); // Tolerance for search
    124124
    125     // XXX Do we need/want to define different values for BAD and POOR subtraction vs BAD and POOR warp?
    126125    psImageMaskType maskVal = pmConfigMaskGet("MASK.VALUE", config); // Bits to mask in inputs
    127     psImageMaskType maskPoor = pmConfigMaskGet("POOR.WARP", config); // Bits to mask for poor pixels
     126    psImageMaskType maskPoor = pmConfigMaskGet("CONV.POOR", config); // Bits to mask for poor pixels
    128127    psImageMaskType maskBad = pmConfigMaskGet("BLANK", config); // Bits to mask for bad pixels
    129128
  • branches/cnb_branches/cnb_branch_20090301/ppSub/src/ppSubSetMasks.c

    r21524 r23594  
    4343    psAssert(satValue, "SAT must be non-zero");
    4444
    45     psImageMaskType badValue = pmConfigMaskGet("BAD", config);
    46     psAssert(badValue, "BAD must be non-zero");
     45    psImageMaskType lowValue = pmConfigMaskGet("LOW", config);
     46    if (!lowValue) {
     47        // Look up old name for backward compatability
     48        lowValue = pmConfigMaskGet("BAD", config);
     49    }
     50    psAssert(lowValue, "LOW or BAD must be non-zero");
    4751
    4852    // input images
     
    5862    if (!inRO->mask) {
    5963        if (psMetadataLookupBool(NULL, recipe, "MASK.GENERATE")) {
    60             pmReadoutSetMask(inRO, satValue, badValue);
     64            pmReadoutSetMask(inRO, satValue, lowValue);
    6165        } else {
    6266            inRO->mask = psImageAlloc(numCols, numRows, PS_TYPE_IMAGE_MASK);
     
    6670    if (!refRO->mask) {
    6771        if (psMetadataLookupBool(NULL, recipe, "MASK.GENERATE")) {
    68             pmReadoutSetMask(refRO, satValue, badValue);
     72            pmReadoutSetMask(refRO, satValue, lowValue);
    6973        } else {
    7074            refRO->mask = psImageAlloc(numCols, numRows, PS_TYPE_IMAGE_MASK);
     
    9599    float poorFrac = psMetadataLookupF32(&mdok, recipe, "POOR.FRACTION"); // Fraction for "poor"
    96100
    97     psImageMaskType maskPoor = pmConfigMaskGet("POOR.WARP", config); // Bits to mask for poor pixels
     101    psImageMaskType maskPoor = pmConfigMaskGet("CONV.POOR", config); // Bits to mask for poor pixels
    98102    psImageMaskType maskBad = pmConfigMaskGet("BLANK", config); // Bits to mask for bad pixels
    99103
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/db/psDB.c

    r22708 r23594  
    14471447
    14481448    mysqlType       *mType;             // type tmp variable
    1449     static bool     isNull = true;      // used in a MYSQL_BIND to indicate NULL
     1449    static my_bool isNull = true;       // used in a MYSQL_BIND to indicate NULL
    14501450
    14511451    MYSQL_BIND *bind = mysqlRow->bind;
     
    14721472                bind[i].length  = 0;
    14731473                bind[i].buffer  = &item->data.U8;
    1474                 bind[i].is_null = psDBIsPTypeNaN(item->type, &item->data.U8)
    1475                                   ? (my_bool *)&isNull
    1476                                   : NULL;
     1474                bind[i].is_null = psDBIsPTypeNaN(item->type, &item->data.U8) ? &isNull : NULL;
    14771475                break;
    14781476            }
     
    14801478                bind[i].length  = 0;
    14811479                bind[i].buffer  = &item->data.U16;
    1482                 bind[i].is_null = psDBIsPTypeNaN(item->type, &item->data.U16)
    1483                                   ? (my_bool *)&isNull
    1484                                   : NULL;
     1480                bind[i].is_null = psDBIsPTypeNaN(item->type, &item->data.U16) ? &isNull : NULL;
    14851481                break;
    14861482            }
     
    14881484                bind[i].length  = 0;
    14891485                bind[i].buffer  = &item->data.U32;
    1490                 bind[i].is_null = psDBIsPTypeNaN(item->type, &item->data.U32)
    1491                                   ? (my_bool *)&isNull
    1492                                   : NULL;
     1486                bind[i].is_null = psDBIsPTypeNaN(item->type, &item->data.U32) ? &isNull : NULL;
    14931487                break;
    14941488            }
     
    14961490                bind[i].length  = 0;
    14971491                bind[i].buffer  = &item->data.U64;
    1498                 bind[i].is_null = psDBIsPTypeNaN(item->type, &item->data.U64)
    1499                                   ? (my_bool *)&isNull
    1500                                   : NULL;
     1492                bind[i].is_null = psDBIsPTypeNaN(item->type, &item->data.U64) ? &isNull : NULL;
    15011493                break;
    15021494            }
     
    15041496                bind[i].length  = 0;
    15051497                bind[i].buffer  = &item->data.S8;
    1506                 bind[i].is_null = psDBIsPTypeNaN(item->type, &item->data.S8)
    1507                                   ? (my_bool *)&isNull
    1508                                   : NULL;
     1498                bind[i].is_null = psDBIsPTypeNaN(item->type, &item->data.S8) ? &isNull : NULL;
    15091499                break;
    15101500            }
     
    15121502                bind[i].length  = 0;
    15131503                bind[i].buffer  = &item->data.S16;
    1514                 bind[i].is_null = psDBIsPTypeNaN(item->type, &item->data.S16)
    1515                                   ? (my_bool *)&isNull
    1516                                   : NULL;
     1504                bind[i].is_null = psDBIsPTypeNaN(item->type, &item->data.S16) ? &isNull : NULL;
    15171505                break;
    15181506            }
     
    15201508                bind[i].length  = 0;
    15211509                bind[i].buffer  = &item->data.S32;
    1522                 bind[i].is_null = psDBIsPTypeNaN(item->type, &item->data.S32)
    1523                                   ? (my_bool *)&isNull
    1524                                   : NULL;
     1510                bind[i].is_null = psDBIsPTypeNaN(item->type, &item->data.S32) ? &isNull : NULL;
    15251511                break;
    15261512            }
     
    15281514                bind[i].length  = 0;
    15291515                bind[i].buffer  = &item->data.S64;
    1530                 bind[i].is_null = psDBIsPTypeNaN(item->type, &item->data.S64)
    1531                                   ? (my_bool *)&isNull
    1532                                   : NULL;
     1516                bind[i].is_null = psDBIsPTypeNaN(item->type, &item->data.S64) ? &isNull : NULL;
    15331517                break;
    15341518            }
     
    15361520                bind[i].length  = 0;
    15371521                bind[i].buffer  = &item->data.F32;
    1538                 bind[i].is_null = psDBIsPTypeNaN(item->type, &item->data.F32)
    1539                                   ? (my_bool *)&isNull
    1540                                   : NULL;
     1522                bind[i].is_null = psDBIsPTypeNaN(item->type, &item->data.F32) ? &isNull : NULL;
    15411523                break;
    15421524            }
     
    15441526                bind[i].length  = 0;
    15451527                bind[i].buffer  = &item->data.F64;
    1546                 bind[i].is_null = psDBIsPTypeNaN(item->type, &item->data.F64)
    1547                                   ? (my_bool *)&isNull
    1548                                   : NULL;
     1528                bind[i].is_null = psDBIsPTypeNaN(item->type, &item->data.F64) ? &isNull : NULL;
    15491529                break;
    15501530            }
     
    15581538                bind[i].length  = 0;
    15591539                bind[i].buffer  = &item->data.B;
    1560                 bind[i].is_null = psDBIsPTypeNaN(item->type, &item->data.B)
    1561                                   ? (my_bool *)&isNull
    1562                                   : NULL;
     1540                bind[i].is_null = psDBIsPTypeNaN(item->type, &item->data.B) ? &isNull : NULL;
    15631541                break;
    15641542            }
     
    15711549                    bind[i].length  = &bind[i].buffer_length;
    15721550                    bind[i].buffer  = psStringCopy(item->data.V);
    1573                     bind[i].is_null = *item->data.str == '\0'
    1574                                       ? (my_bool *)&isNull
    1575                                       : NULL;
     1551                    bind[i].is_null = *item->data.str == '\0' ? &isNull : NULL;
    15761552                } else {
    15771553                    // handles the case of NULL as a NULL database value
     
    15791555                    bind[i].length  = &bind[i].buffer_length;
    15801556                    bind[i].buffer  = NULL;
    1581                     bind[i].is_null = (my_bool *)&isNull;
     1557                    bind[i].is_null = &isNull;
    15821558                }
    15831559                break;
     
    16251601                    bind[i].length  = &bind[i].buffer_length;
    16261602                    bind[i].buffer  = NULL;
    1627                     bind[i].is_null = (my_bool *)&isNull;
     1603                    bind[i].is_null = &isNull;
    16281604                }
    16291605                break;
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/fits/psFitsHeader.c

    r23352 r23594  
    569569                    continue;
    570570                }
     571            } else if (keywordInList(name, noWriteCompressedKeys) ||
     572                       (keyStarts && keywordStartsWith(name, noWriteCompressedKeyStarts))) {
     573                continue;
    571574            }
    572575
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/imageops/psImageBinning.c

    r21107 r23594  
    3131}
    3232
    33 psImageBinning *psImageBinningAlloc() {
     33psImageBinning *psImageBinningAlloc(void) {
    3434    psImageBinning *binning = (psImageBinning*)psAlloc(sizeof(psImageBinning));
    3535    psMemSetDeallocator(binning, (psFreeFunc)psImageBinningFree);
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/imageops/psImageBinning.h

    r21107 r23594  
    4242
    4343
    44 psImageBinning *psImageBinningAlloc() PS_ATTR_MALLOC;
     44psImageBinning *psImageBinningAlloc(void) PS_ATTR_MALLOC;
    4545bool psMemCheckBinning(psPtr ptr);
    4646
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/imageops/psImageCovariance.c

    r23352 r23594  
    260260{
    261261    PS_ASSERT_IMAGE_NON_NULL(variance, NULL);
     262    if (!covar) {
     263        // Transferred all we could!
     264        return true;
     265    }
    262266    PS_ASSERT_KERNEL_NON_NULL(covar, NULL);
    263267
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/jpeg/psImageJpeg.c

    r22681 r23594  
    3535}
    3636
    37 psImageJpegColormap *psImageJpegColormapAlloc ()
     37psImageJpegColormap *psImageJpegColormapAlloc(void)
    3838{
    3939    psImageJpegColormap *map = psAlloc(sizeof(psImageJpegColormap));
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/jpeg/psImageJpeg.h

    r14452 r23594  
    11/* @file  psImageJpeg.h
    22 * @brief functions to generate JPEG images from psImage
    3  * 
     3 *
    44 * @author EAM
    55 * @version $Revision: 1.3 $ $Name: not supported by cvs2svn $
     
    2828
    2929// allocate a colormap (does not define the map values)
    30 psImageJpegColormap *psImageJpegColormapAlloc() PS_ATTR_MALLOC;
     30psImageJpegColormap *psImageJpegColormapAlloc(void) PS_ATTR_MALLOC;
    3131
    3232// set the colormap values using the supplied name
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/math/psMinimizeLMM.c

    r21183 r23594  
    9595    // check for non-finite entries in result
    9696    for (int i = 0; i < Beta->n; i++) {
    97         if (!isfinite(Beta->data.F32[i])) {
    98             // psError(PS_ERR_BAD_PARAMETER_VALUE, 3, "Fit value diverges: vector[%d] is %.2f\n", i, Beta->data.F32[i]);
    99             return false;
    100         }
     97        if (!isfinite(Beta->data.F32[i])) {
     98            // psError(PS_ERR_BAD_PARAMETER_VALUE, 3, "Fit value diverges: vector[%d] is %.2f\n", i, Beta->data.F32[i]);
     99            return false;
     100        }
    101101    }
    102102
     
    104104    // (we must do this before truncating Beta below)
    105105    if (dLinear) {
    106         *dLinear = psMinLM_dLinear(Beta, beta, lambda);
    107     }
    108 
    109     // full-length Beta for checkLimits functions 
     106        *dLinear = psMinLM_dLinear(Beta, beta, lambda);
     107    }
     108
     109    // full-length Beta for checkLimits functions
    110110    psVector *tmpBeta = psVectorAlloc(params->n, PS_TYPE_F32);
    111111    psVectorInit (tmpBeta, 0.0);
     
    113113    // set tmpBeta values which are not masked
    114114    for (int j = 0, n = 0; j < params->n; j++) {
    115         if (paramMask && (paramMask->data.PS_TYPE_VECTOR_MASK_DATA[j])) continue;
    116         tmpBeta->data.F32[j] = Beta->data.F32[n];
    117         n++;
     115        if (paramMask && (paramMask->data.PS_TYPE_VECTOR_MASK_DATA[j])) continue;
     116        tmpBeta->data.F32[j] = Beta->data.F32[n];
     117        n++;
    118118    }
    119119
     
    127127        if (checkLimits) {
    128128            checkLimits (PS_MINIMIZE_BETA_LIMIT, j, Params->data.F32, tmpBeta->data.F32);
    129         }
     129        }
    130130
    131131        Params->data.F32[j] = params->data.F32[j] - tmpBeta->data.F32[j];
     
    135135            checkLimits (PS_MINIMIZE_PARAM_MIN,  j, Params->data.F32, tmpBeta->data.F32);
    136136            checkLimits (PS_MINIMIZE_PARAM_MAX,  j, Params->data.F32, tmpBeta->data.F32);
    137         }
     137        }
    138138    }
    139139
    140140    // apply tmpBeta after limits have been checked
    141141    for (int j = 0, n = 0; j < params->n; j++) {
    142         if (paramMask && (paramMask->data.PS_TYPE_VECTOR_MASK_DATA[j])) continue;
    143         Beta->data.F32[n] = tmpBeta->data.F32[j];
    144         n++;
     142        if (paramMask && (paramMask->data.PS_TYPE_VECTOR_MASK_DATA[j])) continue;
     143        Beta->data.F32[n] = tmpBeta->data.F32[j];
     144        n++;
    145145    }
    146146
     
    169169    // if none are available, return false
    170170    if (!psMinLM_AllocAB (&Alpha, &Beta, params, paramMask)) {
    171         return false;
     171        return false;
    172172    }
    173173
     
    241241    // beta only counts unmasked parameters
    242242    for (int i = 0; i < beta->n; i++) {
    243         dh = lambda*B[i] + b[i];
    244         sh = 0.5*B[i]*dh;
    245         Sh += sh;
     243        dh = lambda*B[i] + b[i];
     244        sh = 0.5*B[i]*dh;
     245        Sh += sh;
    246246        dLinear += lambda*PS_SQR(B[i]) + B[i]*b[i];
    247247    }
     
    295295        assert (!isnan(chisq));
    296296
    297         // we track alpha,beta and params,deriv separately
     297        // we track alpha,beta and params,deriv separately
    298298        for (int j = 0, J = 0; j < params->n; j++) {
    299299            if (paramMask && (paramMask->data.PS_TYPE_VECTOR_MASK_DATA[j])) continue;
     
    304304                if (paramMask && (paramMask->data.PS_TYPE_VECTOR_MASK_DATA[k])) continue;
    305305                alpha->data.F32[J][K] += weight * deriv->data.F32[k];
    306                 K++;
     306                K++;
    307307            }
    308308            beta->data.F32[J] += weight * delta;
    309             J++;
     309            J++;
    310310        }
    311311    }
     
    328328between that function at the specified coords and the specified value at those
    329329coords.
    330  
     330
    331331This requires F32 input data; all internal calls use F32.
    332332XXX Make an F64 version?
     
    386386    // Alpha & Beta only contain elements to represent the unmasked parameters
    387387    if (!psMinLM_AllocAB (&Alpha, &Beta, params, paramMask)) {
    388         psAbort ("programming error: no unmasked parameters to be fit\n");
    389     }
    390    
     388        psAbort ("programming error: no unmasked parameters to be fit\n");
     389    }
     390
    391391    psImage *alpha   = psImageAlloc(Alpha->numCols, Alpha->numRows, PS_TYPE_F32);
    392392    psVector *beta   = psVectorAlloc(Beta->n, PS_TYPE_F32);
     
    490490            psTrace ("psLib.math", 5, "failure to calculate covariance matrix\n");
    491491        }
    492         // set covar values which are not masked
    493         psImageInit (covar, 0.0);
    494         for (int j = 0, J = 0; j < params->n; j++) {
    495             if (paramMask && (paramMask->data.PS_TYPE_VECTOR_MASK_DATA[j])) {
    496                 covar->data.F32[j][j] = 1.0;
    497                 continue;
    498             }
    499             for (int k = 0, K = 0; k < params->n; k++) {
    500                 if (paramMask && (paramMask->data.PS_TYPE_VECTOR_MASK_DATA[k])) continue;
    501                 covar->data.F32[j][k] = Alpha->data.F32[J][K];
    502                 K++;
    503             }
    504             J++;
    505         }
     492        // set covar values which are not masked
     493        psImageInit (covar, 0.0);
     494        for (int j = 0, J = 0; j < params->n; j++) {
     495            if (paramMask && (paramMask->data.PS_TYPE_VECTOR_MASK_DATA[j])) {
     496                covar->data.F32[j][j] = 1.0;
     497                continue;
     498            }
     499            for (int k = 0, K = 0; k < params->n; k++) {
     500                if (paramMask && (paramMask->data.PS_TYPE_VECTOR_MASK_DATA[k])) continue;
     501                covar->data.F32[j][k] = Alpha->data.F32[J][K];
     502                K++;
     503            }
     504            J++;
     505        }
    506506    }
    507507
     
    533533    // count unmasked parameters
    534534    if (paramMask) {
    535         nParams = 0;
    536         for (int i = 0; i < paramMask->n; i++) {
    537             if (paramMask->data.PS_TYPE_VECTOR_MASK_DATA[i]) continue;
    538             nParams ++;
    539         }
    540     }
    541 
    542     if (nParams == 0) { 
    543         return false;
     535        nParams = 0;
     536        for (int i = 0; i < paramMask->n; i++) {
     537            if (paramMask->data.PS_TYPE_VECTOR_MASK_DATA[i]) continue;
     538            nParams ++;
     539        }
     540    }
     541
     542    if (nParams == 0) {
     543        return false;
    544544    }
    545545
     
    585585}
    586586
    587 psMinConstraint* psMinConstraintAlloc()
     587psMinConstraint* psMinConstraintAlloc(void)
    588588{
    589589    psMinConstraint *tmp = psAlloc(sizeof(psMinConstraint));
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/math/psMinimizeLMM.h

    r15046 r23594  
    9494psMinConstraint;
    9595
    96 psMinConstraint *psMinConstraintAlloc() PS_ATTR_MALLOC;
     96psMinConstraint *psMinConstraintAlloc(void) PS_ATTR_MALLOC;
    9797
    9898/** Allocates a psMinimization structure.
     
    174174    psF32 lambda);
    175175
    176 // allocate alpha and beta for unmasked parameters only 
     176// allocate alpha and beta for unmasked parameters only
    177177bool psMinLM_AllocAB (psImage **Alpha, psVector **Beta, const psVector *params, const psVector *paramMask);
    178178
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/math/psSparse.c

    r19501 r23594  
    245245psSparseBorder *psSparseBorderAlloc(psSparse *sparse, int Nborder)
    246246{
     247    psAssert(sparse->Nrows > 0, "Require positive size: nrows = %d", sparse->Nrows);
     248    psAssert(Nborder > 0, "Require positive size: nborder = %d", Nborder);
     249
    247250    psSparseBorder *border = (psSparseBorder *)psAlloc(sizeof(psSparseBorder));
    248251    psMemSetDeallocator(border, (psFreeFunc) psSparseBorderFree);
     
    451454        square = psImageCopy (square, border->Tjj, PS_TYPE_F64);
    452455        if (!psMatrixGJSolve (square, Go)) {
    453             psError(PS_ERR_UNKNOWN, false, "Unable to solve for lower square.");
    454             psFree (dG);
    455             psFree (Go);
    456             psFree (dF);
    457             psFree (Fo);
    458             psFree (square);
    459             return false;
    460         }
     456            psError(PS_ERR_UNKNOWN, false, "Unable to solve for lower square.");
     457            psFree (dG);
     458            psFree (Go);
     459            psFree (dF);
     460            psFree (Fo);
     461            psFree (square);
     462            return false;
     463        }
    461464        yVec = psVectorCopy (yVec, Go, PS_TYPE_F32);
    462465
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/math/psSpline.c

    r12434 r23594  
    103103tabulated function at n points, this routine calculates the second
    104104derivatives of the interpolating cubic splines at those n points.
    105  
     105
    106106The first and second derivatives at the endpoints were previously undefined in
    107107the SDR.  From bugzilla #???, they are required to be 0.0, implementing natural
    108108splines.
    109  
     109
    110110Endpoints are defined by
    111111    PS_LEFT_SPLINE_DERIV
    112112    PS_RIGHT_SPLINE_DERIV
    113  
     113
    114114This routine assumes that vectors x and y are of the appropriate types/sizes
    115115(F32).
    116  
     116
    117117XXX: use recycled vectors for internal data.
    118118XXX: do an F64 version?
     
    177177}
    178178
    179 psSpline1D *psSpline1DAlloc()
     179psSpline1D *psSpline1DAlloc(void)
    180180{
    181181    psSpline1D *tmpSpline = (psSpline1D *) psAlloc(sizeof(psSpline1D));
     
    192192psVectorFitSpline1D(): given a set of x/y vectors, this routine generates the
    193193linear or cublic splines which satisfy those data points.
    194  
     194
    195195The formula for calculating the spline polynomials is derived from Numerical
    196196Recipes in C.  The basic idea is that the polynomial is
     
    206206into a polynomial in terms of x, and then saving the coefficients of the
    207207powers of x in the spline polynomials.  This gets pretty complicated.
    208  
     208
    209209XXX: What types must be supported?
    210210 *****************************************************************************/
     
    354354(vectorBinDisectF32()).  Then it evaluates the spline at that x location
    355355by a call to the 1D polynomial functions.
    356  
     356
    357357XXX: The spline eval functions require input and output to be F32.  however
    358358     the spline fit functions require F32 and F64.
    359  
     359
    360360XXX: This only works if spline->knots if psF32.  Must we add support for psU32 and
    361361psF64?
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/math/psSpline.h

    r14452 r23594  
    4646 *  @return psSpline1D*    new 1-D spline struct
    4747 */
    48 psSpline1D *psSpline1DAlloc() PS_ATTR_MALLOC;
     48psSpline1D *psSpline1DAlloc(void) PS_ATTR_MALLOC;
    4949
    5050/** Evaluates 1-D spline polynomials at a specific coordinate.
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/math/psStats.c

    r23352 r23594  
    265265    for (long i = 0; i < num; i++) {
    266266        // Check if the data is with the specified range
    267         if (maskData && (maskData[i] & maskVal)) {
     267        if (!isfinite(vector[i]))
     268            continue;
     269        if (useRange && (vector[i] < stats->min))
    268270            continue;
    269         }
    270 
    271         if (useRange) {
    272             if (vector[i] < stats->min || vector[i] > stats->max) {
    273                 continue;
    274             }
    275         } else if (!isfinite(vector[i])) {
    276             stats->max = stats->min = NAN;
    277             psError(PS_ERR_IEEE, true, "Element %ld of vector is Inf/NaN", i);
    278             return 0;
    279         }
     271        if (useRange && (vector[i] > stats->max))
     272            continue;
     273        if (maskData && (maskData[i] & maskVal))
     274            continue;
    280275
    281276        numValid++;
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/mathtypes/psImage.c

    r21347 r23594  
    5555
    5656        // drop my entry on my parent's array of children
    57         // lock parent before freeing child : psArrayRemoveDataNoFree is NOT thread safe
    58         psMutexLock (parent);
     57        // lock parent before freeing child : psArrayRemoveDataNoFree is NOT thread safe
     58        psMutexLock (parent);
    5959        psArrayRemoveDataNoFree (parent->children, image);
    60         psMutexUnlock (parent);
     60        psMutexUnlock (parent);
    6161
    6262        // drop my reference to my parent
     
    8787    int rowSize = numCols * elementSize;        // row size in bytes.
    8888
    89     if (numRows < 1) {
    90         psError(PS_ERR_BAD_PARAMETER_VALUE, true,
    91                 _("Specified number of rows (%d) or columns (%d) is invalid."),
    92                 numRows, numCols);
    93         return NULL;
    94     }
    95     if (numCols < 1) {
    96         psError(PS_ERR_BAD_PARAMETER_VALUE, true,
    97                 _("Specified number of rows (%d) or columns (%d) is invalid."),
    98                 numRows, numCols);
    99         return NULL;
     89    if (numRows < 1 || numCols < 1) {
     90        psAbort(_("Specified number of rows (%d) or columns (%d) is invalid."), numRows, numCols);
    10091    }
    10192
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/sys/psError.c

    r19034 r23594  
    146146
    147147psErrorCode p_psErrorV(const char* filename,
    148                        unsigned int lineno,
    149                        const char* func,
    150                        psErrorCode code,
    151                        bool new,
    152                        const char* format,
    153                        va_list ap)
     148                       unsigned int lineno,
     149                       const char* func,
     150                       psErrorCode code,
     151                       bool new,
     152                       const char* format,
     153                       va_list ap)
    154154{
    155155  char errMsg[MAX_STRING_LENGTH];
     
    245245}
    246246
    247 long psErrorGetStackSize()
     247long psErrorGetStackSize(void)
    248248{
    249249    psArray *errorStack = psErrorStackGet();
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/sys/psError.h

    r19034 r23594  
    8787 *  @return int The number of items on the error stack
    8888 */
    89 long psErrorGetStackSize();
     89long psErrorGetStackSize(void);
    9090
    9191
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/sys/psLogMsg.c

    r23352 r23594  
    7676}
    7777
    78 int psLogGetLevel()
     78int psLogGetLevel(void)
    7979{
    8080    return globalLogLevel;
  • branches/cnb_branches/cnb_branch_20090301/psLib/src/sys/psLogMsg.h

    r14452 r23594  
    6363 *  @return int:        The current file descriptor.
    6464 */
    65 int psLogGetDestination();
     65int psLogGetDestination(void);
    6666
    6767
     
    8383 *  @return int:        The current logging level.
    8484 */
    85 int psLogGetLevel();
     85int psLogGetLevel(void);
    8686
    8787/** This procedure sets the log format for future log messages.  The argument
  • branches/cnb_branches/cnb_branch_20090301/psModules

  • branches/cnb_branches/cnb_branch_20090301/psModules/src/astrom/pmAstrometryDistortion.c

    r21183 r23594  
    4040}
    4141
    42 pmAstromGradient *pmAstromGradientAlloc ()
     42pmAstromGradient *pmAstromGradientAlloc (void)
    4343{
    4444
     
    126126            grad = pmAstromGradientAlloc ();
    127127
    128             // XXX psTraceSetLevel("psLib.math.psVectorClipFitPolynomial2D", 7);
     128            // XXX psTraceSetLevel("psLib.math.psVectorClipFitPolynomial2D", 7);
    129129
    130130            // fit the collection of positions and offsets with a local 1st order gradient
     
    138138            grad->dTPdM.x = local->coeff[0][1];
    139139
    140             // XXX psTraceSetLevel("psLib.math.psVectorClipFitPolynomial2D", 0);
     140            // XXX psTraceSetLevel("psLib.math.psVectorClipFitPolynomial2D", 0);
    141141
    142142            // fit the collection of positions and offsets with a local 1st order gradient
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/astrom/pmAstrometryDistortion.h

    r12486 r23594  
    2727pmAstromGradient;
    2828
    29 pmAstromGradient *pmAstromGradientAlloc ();
     29pmAstromGradient *pmAstromGradientAlloc (void);
    3030
    3131/* The following function determines the position residual, in the tangent
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/astrom/pmAstrometryVisual.c

    r23351 r23594  
    4747/* Initialization Routines  */
    4848
    49 bool pmAstromVisualClose()
     49bool pmAstromVisualClose(void)
    5050{
    5151    if(kapa != -1)
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/astrom/pmAstrometryVisual.h

    r23351 r23594  
    2626/** Close plotting windows at the end of a run
    2727 * @return true for success */
    28 bool pmAstromVisualClose();
     28bool pmAstromVisualClose(void);
    2929
    3030
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/camera/pmFPARead.c

    r22699 r23594  
    554554          }
    555555          psFree(header);
    556           bad = pmConfigMaskGet("BAD", config);
     556          bad = pmConfigMaskGet("LOW", config);
     557          if (!bad) {
     558              // XXX look up old name for compatability
     559              bad = pmConfigMaskGet("BAD", config);
     560          }
    557561          break;
    558562      }
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/camera/pmFPAWrite.c

    r23351 r23594  
    172172
    173173    if (writeBlank || writeImage) {
    174         pmConceptSource source = PM_CONCEPT_SOURCE_HEADER | PM_CONCEPT_SOURCE_CELLS |
    175                                  PM_CONCEPT_SOURCE_DEFAULTS | PM_CONCEPT_SOURCE_DATABASE;
    176         if (!pmConceptsWriteCell(cell, source, true, config)) {
     174        if (!pmConceptsWriteCell(cell, true, config)) {
    177175            psError(PS_ERR_IO, false, "Unable to write concepts for cell.");
    178176            return false;
     
    225223
    226224        if (writeBlank || writeImage) {
    227             pmConceptSource source = PM_CONCEPT_SOURCE_HEADER | PM_CONCEPT_SOURCE_CELLS |
    228                                      PM_CONCEPT_SOURCE_DEFAULTS | PM_CONCEPT_SOURCE_DATABASE;
    229             if (!pmConceptsWriteChip(chip, source, true, true, config)) {
     225            if (!pmConceptsWriteChip(chip, true, true, config)) {
    230226                psError(PS_ERR_IO, false, "Unable to write concepts for chip.\n");
    231227                return false;
     
    294290
    295291        if (writeBlank || writeImage) {
    296             pmConceptSource source = PM_CONCEPT_SOURCE_HEADER | PM_CONCEPT_SOURCE_CELLS |
    297                                      PM_CONCEPT_SOURCE_DEFAULTS | PM_CONCEPT_SOURCE_DATABASE;
    298             if (!pmConceptsWriteFPA(fpa, source, true, config)) {
     292            if (!pmConceptsWriteFPA(fpa, true, config)) {
    299293                psError(PS_ERR_IO, false, "Unable to write concepts for FPA.\n");
    300294                return false;
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/camera/pmFPAfile.c

    r23351 r23594  
    2020#include "pmConceptsCopy.h"
    2121
     22static int fileNum = 0;                 // Number of file
     23
    2224static void pmFPAfileFree(pmFPAfile *file)
    2325{
     
    5658}
    5759
    58 pmFPAfile *pmFPAfileAlloc()
     60pmFPAfile *pmFPAfileAlloc(void)
    5961{
    6062    pmFPAfile *file = psAlloc(sizeof(pmFPAfile));
     
    100102
    101103    file->save = false;
     104
     105    file->index = fileNum++;
    102106
    103107    file->imageId = 0;
     
    350354            psStringSubstitute(&newRule, name, "{OUTPUT}");
    351355        }
     356    }
     357
     358    if (strstr(newRule, "{FILE.INDEX}")) {
     359        // Number of the file in list
     360        psString num = NULL;            // Number to use
     361        psStringAppend(&num, "%d", file->index);
     362        psStringSubstitute(&newRule, num, "{FILE.INDEX}");
     363        psFree(num);
    352364    }
    353365
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/camera/pmFPAfile.h

    r23351 r23594  
    109109    psString formatName;                // name of the camera format
    110110
     111    int index;                          // Index of file
     112
    111113    psS64 imageId, sourceId;            // Image and source identifiers
    112114} pmFPAfile;
    113115
    114116// allocate an empty pmFPAfile structure
    115 pmFPAfile *pmFPAfileAlloc ();
     117pmFPAfile *pmFPAfileAlloc(void);
    116118
    117119// select the readout from the named pmFPAfile; if the named file does not exist,
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/camera/pmFPAfileDefine.c

    r23351 r23594  
    382382
    383383    // place the resulting file in the config system
    384     psMetadataAddPtr(config->files, PS_LIST_TAIL, name, PS_DATA_UNKNOWN, "Output file", file);
     384    psMetadataAddPtr(config->files, PS_LIST_TAIL, name, PS_DATA_UNKNOWN | PS_META_DUPLICATE_OK,
     385                     "Output file", file);
    385386    psFree(file);                       // we free this copy of file, but 'files' still has a copy
    386387    return file;                        // the returned value is a view into the version on 'files'
     
    719720}
    720721
    721 pmFPAfile *pmFPAfileDefineFromRun(bool *success, pmConfig *config, const char *filename)
     722pmFPAfile *pmFPAfileDefineFromRun(bool *success, pmFPAfile *bind, pmConfig *config, const char *filename)
    722723{
    723724    PS_ASSERT_PTR_NON_NULL(config, NULL);
     
    732733    }
    733734
    734     pmFPAfile *file = fpaFileDefineFromArray(config, NULL, filename, filenames); // File of interest
     735    pmFPAfile *file = fpaFileDefineFromArray(config, bind, filename, filenames); // File of interest
    735736    psFree(filenames);
    736737
     
    742743}
    743744
     745psArray *pmFPAfileDefineMultipleFromRun(bool *success, psArray *bind, pmConfig *config, const char *filename)
     746{
     747    PS_ASSERT_PTR_NON_NULL(config, NULL);
     748    PS_ASSERT_STRING_NON_EMPTY(filename, NULL);
     749
     750    if (success) {
     751        *success = false;
     752    }
     753
     754    psArray *files = pmConfigRunFileGet(config, filename); // Filenames used, to return
     755    if (!files || files->n == 0) {
     756        if (success) {
     757            *success = true;
     758        }
     759        return NULL;
     760    }
     761    if (bind && files->n != bind->n) {
     762        psError(PS_ERR_BAD_PARAMETER_VALUE, true,
     763                "Length of filenames (%ld) and bind files (%ld) does not match.",
     764                files->n, bind->n);
     765        psFree(files);
     766        return NULL;
     767    }
     768
     769    psArray *dummy = psArrayAlloc(1);   // Dummy array of single filename
     770    for (int i = 0; i < files->n; i++) {
     771        psFree(dummy->data[0]);
     772        dummy->data[0] = files->data[i];
     773        pmFPAfile *bindFile = bind ? bind->data[i] : NULL; // File to which to bind
     774        files->data[i] = psMemIncrRefCounter(fpaFileDefineFromArray(config, bindFile, filename, dummy));
     775        if (!files->data[i]) {
     776            psError(PS_ERR_UNKNOWN, false, "Unable to define file %s %d", filename, i);
     777            psFree(dummy);
     778            psFree(files);
     779            return NULL;
     780        }
     781    }
     782    psFree(dummy);
     783
     784    if (success) {
     785        *success = true;
     786    }
     787
     788    return files;
     789}
    744790
    745791// define the named pmFPAfile from the camera->config
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/camera/pmFPAfileDefine.h

    r23351 r23594  
    6767pmFPAfile *pmFPAfileDefineFromRun(
    6868    bool *found,                        ///< Found files?
     69    pmFPAfile *bind,                    ///< File to which to bind, or NULL
    6970    pmConfig *config,                   ///< Configuration
    7071    const char *filename                ///< Name of file
    7172    );
    7273
     74/// Define multiple files based on the filenames in the RUN metadata in the configuration
     75///
     76/// An array of the files defined is returned
     77psArray *pmFPAfileDefineMultipleFromRun(
     78    bool *found,                        ///< Found files?
     79    psArray *bind,                      ///< Files to which to bind, or NULL
     80    pmConfig *config,                   ///< Configuration
     81    const char *filename                ///< Name of file
     82    );
    7383
    7484// look for the given argname on the argument list.  find the give filename from the file rules
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/camera/pmFPAfileFitsIO.c

    r22699 r23594  
    183183          }
    184184
    185           pmConceptSource sources = PM_CONCEPT_SOURCE_HEADER | PM_CONCEPT_SOURCE_CELLS |
    186               PM_CONCEPT_SOURCE_DEFAULTS | PM_CONCEPT_SOURCE_DATABASE; // Concept sources to write
    187185          if (cell) {
    188               if (!pmConceptsWriteCell(cell, sources, true, config)) {
     186              if (!pmConceptsWriteCell(cell, true, config)) {
    189187                  psError(PS_ERR_IO, false, "Unable to write concepts for cell.\n");
    190188                  return false;
    191189              }
    192190          } else if (chip) {
    193               if (!pmConceptsWriteChip(chip, sources, true, true, config)) {
     191              if (!pmConceptsWriteChip(chip, true, true, config)) {
    194192                  psError(PS_ERR_IO, false, "Unable to write concepts for chip.\n");
    195193                  return false;
    196194              }
    197           } else if (!pmConceptsWriteFPA(fpa, sources, true, config)) {
     195          } else if (!pmConceptsWriteFPA(fpa, true, config)) {
    198196              psError(PS_ERR_IO, false, "Unable to write concepts for FPA.\n");
    199197              return false;
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/camera/pmFPAfileIO.c

    r23351 r23594  
    166166    }
    167167
    168     if (!pmConfigRunFileAdd(config, file)) {
     168    if (!pmConfigRunFileAddRead(config, file)) {
    169169        psError(PS_ERR_UNKNOWN, false, "Unable to add file to run-time information");
    170170        return false;
     
    421421    }
    422422
    423     if (!pmConfigRunFileAdd(config, file)) {
     423    if (!pmConfigRunFileAddWrite(config, file)) {
    424424        psError(PS_ERR_UNKNOWN, false, "Unable to add file to run-time information");
    425425        return false;
     
    635635}
    636636
     637psString pmFPAfileName(const pmFPAfile *file, const pmFPAview *view, pmConfig *config)
     638{
     639    PS_ASSERT_PTR_NON_NULL(file, NULL);
     640    PS_ASSERT_PTR_NON_NULL(view, NULL);
     641    PS_ASSERT_PTR_NON_NULL(config, NULL);
     642
     643    psString filename = pmFPAfileNameFromRule(file->filerule, file, view); // Filename, based on rule
     644    if (!filename) {
     645        psError(PS_ERR_IO, true, "Cannot determine file name from rule");
     646        return false;
     647    }
     648
     649    // indirect filenames: these come from a list on the command line or elsewhere
     650    if (!strcasecmp(filename, "@FILES")) {
     651        psString filesrc = pmFPAfileNameFromRule(file->filesrc, file, view); // Source of file name
     652        if (!filesrc) {
     653            psError(PS_ERR_IO, false, "error converting filesrc to name %s", file->filesrc);
     654            return false;
     655        }
     656        psFree(filename);
     657        filename = psMemIncrRefCounter(psMetadataLookupStr(NULL, file->names, filesrc));
     658        if (!filename) {
     659            psError(PS_ERR_IO, false, "filename lookup error (@FILES) for %s : %s", file->filesrc, filesrc);
     660            psFree(filesrc);
     661            return false;
     662        }
     663        psFree(filesrc);
     664    }
     665
     666    // get name from detrend database
     667    // file->detrend->detID contains the desired -det_id detID -iteration iter string
     668    if (!strcasecmp(filename, "@DETDB")) {
     669        if (!file->detrend) {
     670            psError(PS_ERR_UNEXPECTED_NULL, true, "Unable to find information about selected detrend.");
     671            return false;
     672        }
     673        psMetadata *menu = psMetadataLookupMetadata(NULL, file->camera, "CLASSID"); // Menu of class IDs
     674        if (!menu) {
     675            psError(PS_ERR_IO, false, "Unable to find CLASSID metadata in camera configuration");
     676            return false;
     677        }
     678        const char *rule = psMetadataLookupStr(NULL, menu, file->detrend->level); // Rule for class_id
     679        if (!rule || strlen(rule) == 0) {
     680            psError(PS_ERR_IO, false, "Unable to find %s in CLASSID in camera configuration",
     681                    file->detrend->level);
     682            return false;
     683        }
     684        psString classId = pmFPAfileNameFromRule(rule, file, view); // The class identifier, for pmDetrendFile
     685        if (!classId) {
     686            psError(PS_ERR_IO, false, "error converting CLASSID rule to name: %s\n", rule);
     687            return false;
     688        }
     689
     690        psTrace("psModules.camera", 6, "looking for detrend (%s, %s)\n", file->detrend->detID, classId);
     691        psFree(filename);
     692        filename = pmDetrendFile(file->detrend->detID, classId, config);
     693        if (!filename) {
     694            psError(PS_ERR_IO, false, "failed to find a valid detrend image for detID %s : classID %s",
     695                    file->detrend->detID, classId);
     696            psFree(classId);
     697            return false;
     698        }
     699
     700        psTrace("psModules.camera", 6, "got detrend file %s", filename);
     701        psFree(classId);
     702    }
     703
     704    return filename;
     705}
     706
    637707// open file (if not already opened).
    638708// this function is only called only within pmFPAfileRead or pmFPAfileWrite.
     
    672742
    673743    // determine the file name, free a name allocated earlier
    674     psFree (file->filename);
    675     file->filename = pmFPAfileNameFromRule (file->filerule, file, view);
    676     if (file->filename == NULL) {
    677         psError(PS_ERR_IO, true, "Filename is NULL");
    678         return false;
    679     }
    680 
    681     // indirect filenames: these come from a list on the command line or elsewhere
    682     if (!strcasecmp (file->filename, "@FILES")) {
    683         char *filesrc = pmFPAfileNameFromRule (file->filesrc, file, view);
    684         if (filesrc == NULL) {
    685             psError(PS_ERR_IO, false, "error converting filesrc to name %s\n", file->filesrc);
    686             return false;
    687         }
    688 
    689         psFree (file->filename);
    690         file->filename = psMetadataLookupStr (&status, file->names, filesrc);
    691 
    692         if (file->filename == NULL) {
    693             psError(PS_ERR_IO, true, "filename lookup error (@FILES) for %s : %s\n", file->filesrc, filesrc);
    694             psFree (filesrc);
    695             return false;
    696         }
    697         // psMetadataLookupStr just returns a view, file->filename must be protected
    698         psMemIncrRefCounter (file->filename);
    699         psFree (filesrc);
    700     }
    701 
    702     // get name from detrend database
    703     // file->detrend->detID contains the desired -det_id detID -iteration iter string
    704     if (!strcasecmp (file->filename, "@DETDB")) {
    705         if (!file->detrend) {
    706             psError(PS_ERR_UNEXPECTED_NULL, true, "Unable to find information about selected detrend.");
    707             return false;
    708         }
    709 
    710         psString classId = NULL;        // The class identifier, to pass to pmDetrendFile
    711         psMetadata *menu = psMetadataLookupMetadata(&status, file->camera, "CLASSID"); // Menu of class IDs
    712         if (!status || !menu) {
    713             psError(PS_ERR_IO, false, "Unable to find CLASSID metadata in camera configuration");
    714             return false;
    715         }
    716         const char *rule = psMetadataLookupStr(&status, menu, file->detrend->level); // Rule for class_id
    717         if (!status || !rule || strlen(rule) == 0) {
    718             psError(PS_ERR_IO, false, "Unable to find %s in CLASSID in camera configuration", file->detrend->level);
    719             return false;
    720         }
    721         classId = pmFPAfileNameFromRule(rule, file, view);
    722         if (!classId) {
    723             psError(PS_ERR_IO, false, "error converting CLASSID rule to name: %s\n", rule);
    724             return false;
    725         }
    726         psTrace ("psModules.camera", 6, "looking for detrend (%s, %s)\n", file->detrend->detID, classId);
    727         psFree (file->filename);
    728 
    729         file->filename = pmDetrendFile(file->detrend->detID, classId, config);
    730         if (file->filename == NULL) {
    731             psError(PS_ERR_IO, false, "failed to find a valid detrend image for detID %s : classID %s\n", file->detrend->detID, classId);
    732             psFree (classId);
    733             return false;
    734         }
    735 
    736         psTrace ("psModules.camera", 6, "got detrend file %s\n", file->filename);
    737         psFree (classId);
     744    psFree(file->filename);
     745    file->filename = pmFPAfileName(file, view, config);
     746    if (!file->filename) {
     747        psError(PS_ERR_IO, true, "Unable to determine filename");
     748        return false;
    738749    }
    739750
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/camera/pmFPAfileIO.h

    r18364 r23594  
    1515/// @addtogroup Camera Camera Layout
    1616/// @{
     17
     18// Determine appropriate file name
     19psString pmFPAfileName(const pmFPAfile *file, const pmFPAview *view, pmConfig *config);
    1720
    1821// open the real file corresponding to the given pmFPAfile appropriate to the current view
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/concepts/pmConceptsStandard.c

    r23351 r23594  
    606606}
    607607
     608// Get the current value of a concept
     609static psMetadataItem *conceptGet(const pmFPA *fpa, // FPA of interest
     610                                  const pmChip *chip, // Chip of interest, or NULL
     611                                  const pmCell *cell, // Cell of interest, or NULL
     612                                  const char *name // Concept name
     613    )
     614{
     615    psMetadataItem *item = NULL;        // Item with time system
     616    if (cell) {
     617        item = psMetadataLookup(cell->concepts, name);
     618    }
     619    if (!item && chip) {
     620        item = psMetadataLookup(chip->concepts, name);
     621    }
     622    if (!item && fpa) {
     623        item = psMetadataLookup(fpa->concepts, name);
     624    }
     625    if (!item) {
     626        psError(PS_ERR_UNEXPECTED_NULL, true, "Unable to find %s in concepts", name);
     627        return NULL;
     628    }
     629    return item;
     630}
     631
     632// Determine the corresponding TIMESYS for one of the TIME concepts
     633static psTimeType conceptGetTimesysForTime(const char *name, // Concept name ("CELL.TIME" or "FPA.TIME")
     634                                           const pmFPA *fpa, // FPA of interest
     635                                           const pmChip *chip, // Chip of interest, or NULL
     636                                           const pmCell *cell // Cell of interest, or NULL
     637                                           )
     638{
     639    assert(name);
     640
     641    psString timesysName = psStringCopy(name); // e.g., "CELL.TIME" --> "CELL.TIMESYS"
     642    psStringSubstitute(&timesysName, "TIMESYS", "TIME");
     643    psMetadataItem *item = conceptGet(fpa, chip, cell, timesysName); // Time system
     644    psFree(timesysName);
     645
     646    if (!item || item->type != PS_TYPE_S32) {
     647        psWarning("Unable to find %s --- assuming UTC", timesysName);
     648        return PS_TIME_UTC;
     649    }
     650    return item->data.S32;
     651}
     652
     653// Set the corresponding TIMESYS for one of the TIME concepts
     654static bool conceptSetTimesysForTime(const char *name, // Concept name ("CELL.TIME" or "FPA.TIME")
     655                                     const pmFPA *fpa, // FPA of interest
     656                                     const pmChip *chip, // Chip of interest, or NULL
     657                                     const pmCell *cell, // Cell of interest, or NULL
     658                                     psTimeType timeSys // The time system value
     659                                     )
     660{
     661    assert(name);
     662
     663    psString timesysName = psStringCopy(name); // e.g., "CELL.TIME" --> "CELL.TIMESYS"
     664    psStringSubstitute(&timesysName, "TIMESYS", "TIME");
     665    psMetadataItem *item = conceptGet(fpa, chip, cell, timesysName); // Time system
     666    psFree(timesysName);
     667
     668    if (!item) {
     669        psError(PS_ERR_UNEXPECTED_NULL, true, "Unable to find %s in concepts when setting %s\n",
     670                timesysName, name);
     671        return false;
     672    }
     673
     674    if (item->data.S32 != -1 && item->data.S32 != timeSys) {
     675        psWarning("Time system is set to %x; but should be %x", item->data.S32, timeSys);
     676    }
     677
     678    item->data.S32 = timeSys;
     679
     680    return true;
     681}
    608682
    609683psMetadataItem *p_pmConceptParse_TIMESYS(const psMetadataItem *concept,
     
    622696    if (concept->type != PS_DATA_STRING || strlen(sys) <= 0) {
    623697        // XXX is this too low verbosity?
    624         psLogMsg ("psModules.concepts", PS_LOG_DETAIL, "Can't interpret %s --- assuming UTC.\n", pattern->name);
     698        psWarning("Can't interpret %s --- assuming UTC.", pattern->name);
    625699    } else if (strcasecmp(sys, "TAI") == 0) {
    626700        timeSys = PS_TIME_TAI;
     
    633707    } else {
    634708        // XXX is this too low verbosity?
    635         psLogMsg ("psModules.concepts", PS_LOG_DETAIL, "Can't interpret %s --- assuming UTC.\n", pattern->name);
     709        psWarning("Can't interpret %s --- assuming UTC.", pattern->name);
     710    }
     711
     712    psMetadataItem *old = conceptGet(fpa, chip, cell, pattern->name); // Old value
     713    if (old && old->data.S32 != -1 && old->data.S32 != timeSys) {
     714        psWarning("%s is already set (%x) and not consistent with new value (%x)",
     715                  pattern->name, old->data.S32, timeSys);
    636716    }
    637717
     
    639719}
    640720
    641 // Determine the corresponding TIMESYS for one of the TIME concepts
    642 static psTimeType conceptGetTimesysForTime(const char *name, // Concept name ("CELL.TIME" or "FPA.TIME")
    643                                            const pmFPA *fpa, // FPA of interest
    644                                            const pmChip *chip, // Chip of interest, or NULL
    645                                            const pmCell *cell // Cell of interest, or NULL
    646                                            )
    647 {
    648     assert(name);
    649 
    650     psString timesysName = psStringCopy(name); // e.g., "CELL.TIME" --> "CELL.TIMESYS"
    651     psStringSubstitute(&timesysName, "TIMESYS", "TIME");
    652     bool mdok = false;                  // Result of MD lookup
    653     psTimeType timeSys = 0xFFFFFFFF;    // The time system
    654     if (cell) {
    655         timeSys = psMetadataLookupS32(&mdok, cell->concepts, timesysName);
    656     }
    657     if (!mdok && chip) {
    658         timeSys = psMetadataLookupS32(&mdok, chip->concepts, timesysName);
    659     }
    660     if (!mdok && fpa) {
    661         timeSys = psMetadataLookupS32(&mdok, fpa->concepts, timesysName);
    662     }
    663     if (!mdok || (timeSys == 0xFFFFFFFF)) {
    664         psWarning("Unable to find %s in concepts when parsing %s --- assuming UTC.\n",
    665                   timesysName, name);
    666         timeSys = PS_TIME_UTC;
    667     }
    668     psFree(timesysName);
    669 
    670     return timeSys;
    671 }
     721
    672722
    673723psMetadataItem *p_pmConceptParse_TIME(const psMetadataItem *concept,
     
    896946    }
    897947
    898     time->type = timeSys;
     948    if (jdTime || mjdTime) {
     949        conceptSetTimesysForTime(pattern->name, fpa, chip, cell, PS_TIME_TAI);
     950    } else {
     951        time->type = timeSys;
     952    }
    899953
    900954    psMetadataItem *item = psMetadataItemAllocPtr(pattern->name, PS_DATA_TIME, pattern->comment, time);
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/concepts/pmConceptsWrite.c

    r22699 r23594  
    6262        while ((cItem = psListGetAndIncrement(cIter))) {
    6363            if (cItem->type != PS_DATA_STRING) {
    64                 psWarning("psMetadataItem from list is of type %x instead of "
    65                          "%x (PS_DATA_STRING) --- can't interpret.\n", cItem->type, PS_DATA_STRING);
     64                psWarning("psMetadataItem from list is of type %x instead of %x (PS_DATA_STRING) --- can't interpret.\n", cItem->type, PS_DATA_STRING);
    6665                psFree(cIter);
    6766                psFree(sIter);
     
    183182        }
    184183    default:
    185         psWarning("Type of %s is not suitable for a FITS header --- not added.\n",
     184      psWarning("Type of %s is not suitable for a FITS header --- not added.\n",
    186185                 item->name);
    187186        return false;
     
    226225}
    227226
     227// Return the camera format appropriate for a focal plane hierarchy
     228static psMetadata *conceptsCameraFormat(const pmFPA *fpa, const pmChip *chip, const pmCell *cell)
     229{
     230    pmHDU *hdu = pmHDUGetLowest(fpa, chip, cell); // The HDU at the lowest level
     231    if (!hdu) {
     232        return NULL;
     233    }
     234    return hdu->format;
     235}
     236
     237// Return the DATABASE metadata from the format
     238static psMetadata *conceptsDatabase(const psMetadata *format)
     239{
     240    bool mdok;                          // Status of MD lookup
     241    return psMetadataLookupMetadata(&mdok, format, "DEFAULTS");
     242}
     243
     244// Return the TRANSLATION metadata from the format
     245static psMetadata *conceptsTranslation(const psMetadata *format)
     246{
     247    bool mdok;                          // Status of MD lookup
     248    return psMetadataLookupMetadata(&mdok, format, "TRANSLATION");
     249}
     250
     251// Return the DEFAULTS metadata from the format
     252static psMetadata *conceptsDefaults(const psMetadata *format)
     253{
     254    bool mdok;                          // Status of MD lookup
     255    return psMetadataLookupMetadata(&mdok, format, "DEFAULTS");
     256}
     257
    228258
    229259//////////////////////////////////////////////////////////////////////////////////////////////////////////////
     
    231261//////////////////////////////////////////////////////////////////////////////////////////////////////////////
    232262
    233 bool p_pmConceptsWriteToCells(const psMetadata *specs, const pmCell *cell, const psMetadata *concepts)
    234 {
    235     PS_ASSERT_PTR_NON_NULL(specs, false);
    236     PS_ASSERT_PTR_NON_NULL(concepts, false);
     263bool p_pmConceptWriteToCells(const pmCell *cell, const pmConceptSpec *spec,
     264                             const psMetadataItem *conceptItem, const psMetadata *format)
     265{
    237266    if (!cell) {
    238267        return false;
     
    242271    }
    243272
    244     pmHDU *hdu = pmHDUGetLowest(NULL, NULL, cell); // The HDU at the lowest level
     273    if (!format) {
     274        format = conceptsCameraFormat(NULL, NULL, cell);
     275        if (!format) {
     276            return false;
     277        }
     278    }
     279
     280    psMetadataItem *cameraItem = psMetadataLookup(cell->config, conceptItem->name); // Version in the config
     281    if (!cameraItem) {
     282        return false;
     283    }
     284
     285    psString nameSource = NULL; // String with the concept name and ".SOURCE" added
     286    psStringAppend(&nameSource, "%s.SOURCE", conceptItem->name);
     287    bool mdok = true;       // Status of MD lookup
     288    psString source = psMetadataLookupStr(&mdok, cell->config, nameSource); // The source
     289    if (mdok && strlen(source) > 0) {
     290        psTrace("psModules.concepts", 8, "%s is %s\n", nameSource, source);
     291        if (strcasecmp(source, "HEADER") == 0) {
     292            if (cameraItem->type != PS_DATA_STRING) {
     293                psWarning("Concept %s is specified by header, but is not of type STR --- ignored.",
     294                          conceptItem->name);
     295                psFree(nameSource);
     296                return false;
     297            }
     298
     299            // Formatted version
     300            psMetadataItem *formatted = conceptFormat(spec, conceptItem, PM_CONCEPT_SOURCE_HEADER,
     301                                                      format, NULL, NULL, cell);
     302            if (!formatted) {
     303                psFree(nameSource);
     304                return true;
     305            }
     306
     307            psTrace("psModules.concepts", 8, "Writing %s to header %s\n",
     308                    conceptItem->name, cameraItem->data.str);
     309            pmHDU *hdu = pmHDUGetLowest(NULL, NULL, cell); // Header data unit
     310            if (!hdu) {
     311                psError(PS_ERR_UNEXPECTED_NULL, false,
     312                        "Unable to find HDU to write concept %s", conceptItem->name);
     313                return false;
     314            }
     315            writeHeader(hdu, cameraItem->data.V, formatted);
     316            psFree(formatted);
     317        } else if (strcasecmp(source, "VALUE") == 0) {
     318            // Formatted version
     319            psMetadataItem *formatted = conceptFormat(spec, conceptItem, PM_CONCEPT_SOURCE_CELLS,
     320                                                      format, NULL, NULL, cell);
     321            if (!formatted) {
     322                psFree(nameSource);
     323                return true;
     324            }
     325
     326            psTrace("psModules.concepts", 8, "Checking %s against camera format.\n", conceptItem->name);
     327            if (!compareConcepts(formatted, cameraItem)) {
     328                psWarning("Concept %s is specified by value in the camera format, but the values don't match",
     329                          conceptItem->name);
     330            }
     331            psFree(formatted);
     332        } else {
     333            psWarning("Concept source %s isn't HEADER or VALUE --- can't write", nameSource);
     334        }
     335    } else {
     336        // Assume it's specified by value
     337        psMetadataItem *formatted = conceptFormat(spec, conceptItem, PM_CONCEPT_SOURCE_CELLS,
     338                                                  format, NULL, NULL, cell);
     339        if (!formatted) {
     340            psFree(nameSource);
     341            return true;
     342        }
     343
     344        if (!compareConcepts(formatted, cameraItem)) {
     345            psWarning("Concept %s is specified by value in the camera format, but the values don't match.",
     346                      conceptItem->name);
     347        }
     348        psFree(formatted);
     349    }
     350    psFree(nameSource);
     351
     352    return true;
     353}
     354
     355bool p_pmConceptWriteToDefaults(const pmFPA *fpa, const pmChip *chip, const pmCell *cell,
     356                                const pmConceptSpec *spec, const psMetadataItem *conceptItem,
     357                                const psMetadata *format, const psMetadata *defaults)
     358{
     359    if (!format) {
     360        format = conceptsCameraFormat(fpa, chip, cell);
     361        if (!format) {
     362            return false;
     363        }
     364    }
     365    if (!defaults) {
     366        defaults = conceptsDefaults(format);
     367        if (!defaults) {
     368            return false;
     369        }
     370    }
     371
     372    psMetadataItem *defaultItem = p_pmConceptsReadSingleFromDefaults(conceptItem->name, defaults,
     373                                                                     fpa, chip, cell);
     374    if (!defaultItem) {
     375        return false;
     376    }
     377    psMetadataItem *formatted = conceptFormat(spec, conceptItem, PM_CONCEPT_SOURCE_DEFAULTS,
     378                                              format, fpa, chip, cell);
     379    if (!formatted) {
     380        return true;
     381    }
     382
     383    if (strcmp(defaultItem->name, conceptItem->name) != 0) {
     384        // Correct the name to match the concept name
     385        defaultItem = psMetadataItemCopy(defaultItem);
     386        psFree(defaultItem->name);
     387        defaultItem->name = psStringCopy(conceptItem->name);
     388    } else {
     389        psMemIncrRefCounter(defaultItem);
     390    }
     391
     392    if (!compareConcepts(formatted, defaultItem)) {
     393        psWarning("Concept %s is specified by the DEFAULTS in the camera format, but the values don't match.",
     394                  conceptItem->name);
     395    }
     396    psFree(defaultItem);
     397    psFree(formatted);
     398
     399    return true;
     400}
     401
     402
     403bool p_pmConceptWriteToHeader(const pmFPA *fpa, const pmChip *chip, const pmCell *cell,
     404                              const pmConceptSpec *spec, const psMetadataItem *conceptItem,
     405                              const psMetadata *format, const psMetadata *translation)
     406{
     407    if (!format) {
     408        format = conceptsCameraFormat(fpa, chip, cell);
     409        if (!format) {
     410            return false;
     411        }
     412    }
     413    if (!translation) {
     414        translation = conceptsTranslation(format);
     415        if (!translation) {
     416            return false;
     417        }
     418    }
     419
     420    psMetadataItem *headerItem = psMetadataLookup(translation, conceptItem->name); // How to format for header
     421    if (!headerItem) {
     422        return false;
     423    }
     424    if (headerItem->type == PS_DATA_METADATA) {
     425        // This is a menu
     426        psTrace("psModules.concepts", 5, "%s is of type METADATA.\n", conceptItem->name);
     427        headerItem = p_pmConceptsDepend(conceptItem->name, headerItem->data.md, translation, fpa, chip, cell);
     428        if (!headerItem) {
     429            return false;
     430        }
     431    }
     432    if (headerItem->type != PS_DATA_STRING) {
     433        psWarning("TRANSLATION keyword for concept %s isn't of type STR --- ignored.", conceptItem->name);
     434        return false;
     435    }
     436    psTrace("psModules.concepts", 3, "Writing %s to header %s\n", conceptItem->name, headerItem->data.str);
     437    psMetadataItem *formatted = conceptFormat(spec, conceptItem, PM_CONCEPT_SOURCE_HEADER,
     438                                              format, fpa, chip, cell);
     439    if (!formatted) {
     440        // Found it, but it doesn't need to be written
     441        return true;
     442    }
     443
     444    pmHDU *hdu = pmHDUGetLowest(fpa, chip, cell); // HDU to which to write
    245445    if (!hdu) {
    246         return false;
    247     }
    248     psMetadata *cameraFormat = hdu->format; // The camera format
    249     psMetadataIterator *specsIter = psMetadataIteratorAlloc(specs, PS_LIST_HEAD, NULL); // Iterator
    250     psMetadataItem *specItem = NULL;    // Item from the specs metadata
    251     while ((specItem = psMetadataGetAndIncrement(specsIter))) {
    252         pmConceptSpec *spec = specItem->data.V; // The specification
    253         psString name = specItem->name; // The concept name
    254         psMetadataItem *cameraItem = psMetadataLookup(cell->config, name); // The concept from the camera,
    255         // or NULL
    256         if (cameraItem) {
    257             // Grab the concept
    258             psMetadataItem *conceptItem = psMetadataLookup(concepts, name); // The concept
    259 
    260             psString nameSource = NULL; // String with the concept name and ".SOURCE" added
    261             psStringAppend(&nameSource, "%s.SOURCE", name);
    262             bool mdok = true;       // Status of MD lookup
    263             psString source = psMetadataLookupStr(&mdok, cell->config, nameSource); // The source
    264             if (mdok && strlen(source) > 0) {
    265                 psTrace("psModules.concepts", 8, "%s is %s\n", nameSource, source);
    266                 if (strcasecmp(source, "HEADER") == 0) {
    267                     if (cameraItem->type != PS_DATA_STRING) {
    268                         psWarning("Concept %s is specified by header, but is not "
    269                                  "of type STR --- ignored.\n", conceptItem->name);
    270                         continue;
    271                     }
    272 
    273                     // Formatted version
    274                     psMetadataItem *formatted = conceptFormat(spec, conceptItem, PM_CONCEPT_SOURCE_HEADER,
    275                                                               cameraFormat, NULL, NULL, cell);
    276                     if (!formatted) {
    277                         continue;
    278                     }
    279 
    280                     psTrace("psModules.concepts", 8, "Writing %s to header %s\n", name, cameraItem->data.str);
    281                     writeHeader(hdu, cameraItem->data.V, formatted);
    282                     psFree(formatted);
    283                 } else if (strcasecmp(source, "VALUE") == 0) {
    284                     // Formatted version
    285                     psMetadataItem *formatted = conceptFormat(spec, conceptItem, PM_CONCEPT_SOURCE_CELLS,
    286                                                               cameraFormat, NULL, NULL, cell);
    287                     if (!formatted) {
    288                         continue;
    289                     }
    290 
    291                     psTrace("psModules.concepts", 8, "Checking %s against camera format.\n", name);
    292                     if (! compareConcepts(formatted, cameraItem)) {
    293                         psWarning("Concept %s is specified by value in the camera "
    294                                  "format, but the values don't match.\n", name);
    295                     }
    296                     psFree(formatted);
    297                 } else {
    298                     psWarning("Concept source %s isn't HEADER or VALUE --- can't "
    299                              "write\n", nameSource);
    300                 }
    301             } else {
    302                 // Assume it's specified by value
    303                 psMetadataItem *formatted = conceptFormat(spec, conceptItem, PM_CONCEPT_SOURCE_CELLS,
    304                                                           cameraFormat, NULL, NULL, cell);
    305                 if (!formatted) {
    306                     continue;
    307                 }
    308 
    309                 if (! compareConcepts(formatted, cameraItem)) {
    310                     psWarning("Concept %s is specified by value in the camera "
    311                              "format, but the values don't match.\n", name);
    312                 }
    313                 psFree(formatted);
    314             }
    315             psFree(nameSource);
    316         }
    317 
    318     }
    319     psFree(specsIter);
     446        psError(PS_ERR_UNEXPECTED_NULL, false, "Unable to find HDU to write concept %s", conceptItem->name);
     447        return false;
     448    }
     449    writeHeader(hdu, headerItem->data.V, formatted);
     450    psFree(formatted);
     451
    320452    return true;
    321453}
    322454
    323 bool p_pmConceptsWriteToDefaults(const psMetadata *specs, const pmFPA *fpa, const pmChip *chip,
    324                                  const pmCell *cell, const psMetadata *concepts)
    325 {
    326     PS_ASSERT_PTR_NON_NULL(specs, false);
    327     PS_ASSERT_PTR_NON_NULL(concepts, false);
    328 
    329     pmHDU *hdu = pmHDUGetLowest(fpa, chip, cell); // The HDU at the lowest level
    330     if (!hdu) {
    331         return false;
    332     }
    333     psMetadata *cameraFormat = hdu->format; // The camera format
    334     bool mdok = true;                   // Status of MD lookup
    335     psMetadata *defaults = psMetadataLookupMetadata(&mdok, cameraFormat, "DEFAULTS"); // The DEFAULTS spec
    336     if (!mdok || !defaults) {
    337         return false;
    338     }
    339 
    340     psMetadataIterator *specsIter = psMetadataIteratorAlloc(specs, PS_LIST_HEAD, NULL); // Iterator
    341     psMetadataItem *specItem = NULL;    // Item from the specs metadata
    342     while ((specItem = psMetadataGetAndIncrement(specsIter))) {
    343         pmConceptSpec *spec = specItem->data.V; // The specification
    344         psString name = specItem->name; // The concept name
    345 
    346         psMetadataItem *defaultItem = p_pmConceptsReadSingleFromDefaults(name, defaults, fpa, chip, cell);
    347         if (!defaultItem) {
    348             continue;
    349         }
    350         psMetadataItem *conceptItem = psMetadataLookup(concepts, name); // The item from the concepts
    351         psMetadataItem *formatted = conceptFormat(spec, conceptItem, PM_CONCEPT_SOURCE_DEFAULTS,
    352                                                   cameraFormat, fpa, chip, cell);
    353         if (!formatted) {
    354             continue;
    355         }
    356 
    357         if (strcmp(defaultItem->name, name) != 0) {
    358             // Correct the name to match the concept name
    359             defaultItem = psMetadataItemCopy(defaultItem);
    360             psFree(defaultItem->name);
    361             defaultItem->name = psStringCopy(name);
    362         } else {
    363             psMemIncrRefCounter(defaultItem);
    364         }
    365 
    366         if (!compareConcepts(formatted, defaultItem)) {
    367             psWarning("Concept %s is specified by the DEFAULTS in the camera "
    368                       "format, but the values don't match.\n", name);
    369         }
    370         psFree(defaultItem);
    371         psFree(formatted);
    372     }
    373     psFree(specsIter);
     455bool p_pmConceptWriteToDatabase(const pmFPA *fpa, const pmChip *chip, const pmCell *cell,
     456                                pmConfig *config, const pmConceptSpec *spec,
     457                                const psMetadataItem *conceptItem, const psMetadata *format,
     458                                const psMetadata *database)
     459{
     460    PS_ASSERT_PTR_NON_NULL(config, false);
     461
     462#ifndef HAVE_PSDB
     463    return false;
     464#else
     465
     466    if (!format) {
     467        format = conceptsCameraFormat(fpa, chip, cell);
     468        if (!format) {
     469            return false;
     470        }
     471    }
     472    if (!database) {
     473        database = conceptsDatabase(format);
     474        if (!database) {
     475            return false;
     476        }
     477    }
     478
     479    psMetadataItem *dbItem = p_pmConceptsReadSingleFromDatabase(conceptItem->name, database, config,
     480                                                                fpa, chip, cell); // Database version
     481    if (!dbItem) {
     482        return false;
     483    }
     484
     485    psMetadataItem *formatted = conceptFormat(spec, conceptItem, PM_CONCEPT_SOURCE_DATABASE,
     486                                              format, fpa, chip, cell);
     487    if (!formatted) {
     488        return false;
     489    }
     490
     491    if (strcmp(dbItem->name, conceptItem->name) != 0) {
     492        // Correct the name to match the concept name
     493        dbItem = psMetadataItemCopy(dbItem);
     494        psFree(dbItem->name);
     495        dbItem->name = psStringCopy(conceptItem->name);
     496    } else {
     497        psMemIncrRefCounter(dbItem);
     498    }
     499
     500    if (!compareConcepts(formatted, dbItem)) {
     501        psWarning("Concept %s is specified by the DATABASE in the camera "
     502                  "format, but the values don't match.\n", conceptItem->name);
     503    }
     504    psFree(dbItem);
     505    psFree(formatted);
     506
    374507    return true;
    375 }
    376 
    377 
    378 bool p_pmConceptsWriteToHeader(const psMetadata *specs, const pmFPA *fpa, const pmChip *chip,
    379                                const pmCell *cell, const psMetadata *concepts)
    380 {
    381     PS_ASSERT_PTR_NON_NULL(specs, false);
    382     PS_ASSERT_PTR_NON_NULL(concepts, false);
    383 
    384     pmHDU *hdu = pmHDUGetLowest(fpa, chip, cell); // The HDU at the lowest level
    385     if (!hdu) {
    386         return false;
    387     }
    388     psMetadata *cameraFormat = hdu->format; // The camera format
    389     bool mdok = true;                   // Status of MD lookup
    390     psMetadata *translation = psMetadataLookupMetadata(&mdok, cameraFormat, "TRANSLATION"); // The TRANSLATION spec
    391     if (!mdok || !translation) {
    392         return false;
    393     }
    394 
    395     psMetadataIterator *specsIter = psMetadataIteratorAlloc(specs, PS_LIST_HEAD, NULL); // Iterator
    396     psMetadataItem *specItem = NULL;    // Item from the specs metadata
    397     while ((specItem = psMetadataGetAndIncrement(specsIter))) {
    398         pmConceptSpec *spec = specItem->data.V; // The specification
    399         psString name = specItem->name; // The concept name
    400         psMetadataItem *headerItem = psMetadataLookup(translation, name); // The item from the TRANSLATION
    401         if (!headerItem) {
    402             continue;
    403         }
    404         if (headerItem->type == PS_DATA_METADATA) {
    405             // This is a menu
    406             psTrace("psModules.concepts", 5, "%s is of type METADATA.\n", name);
    407             headerItem = p_pmConceptsDepend(name, headerItem->data.md, translation, fpa, chip, cell);
    408             if (!headerItem) {
    409                 continue;
    410             }
    411         }
    412         if (headerItem->type != PS_DATA_STRING) {
    413             psWarning("TRANSLATION keyword for concept %s isn't of type STR --- ignored.", name);
    414             continue;
    415         }
    416         psTrace("psModules.concepts", 3, "Writing %s to header %s\n", name, headerItem->data.str);
    417         psMetadataItem *conceptItem = psMetadataLookup(concepts, name); // The item from the concepts
    418         psMetadataItem *formatted = conceptFormat(spec, conceptItem, PM_CONCEPT_SOURCE_HEADER,
    419                                                   cameraFormat, fpa, chip, cell);
    420         if (!formatted) {
    421             continue;
    422         }
    423         writeHeader(hdu, headerItem->data.V, formatted);
    424         psFree(formatted);
    425     }
    426     psFree(specsIter);
     508#endif
     509}
     510
     511
     512bool pmConceptWriteSingle(const pmFPA *fpa, const pmChip *chip, const pmCell *cell,
     513                          pmConfig *config, const psMetadataItem *conceptItem)
     514{
     515    pmConceptsInit();
     516
     517    psMetadata *format = conceptsCameraFormat(fpa, chip, cell); // Camera format
     518    if (!format) {
     519        psError(PS_ERR_UNKNOWN, false, "Unable to retrieve camera format.");
     520        return false;
     521    }
     522
     523    const char *name = conceptItem->name; // Name of concept
     524
     525    psMetadata *conceptsFPA = pmConceptsSpecs(PM_FPA_LEVEL_FPA); // Concept specifications for FPA
     526    bool mdok;                          // Status of MD lookup
     527    pmConceptSpec *spec = psMetadataLookupPtr(&mdok, conceptsFPA, name); // Concept specification of interest
     528    if (!spec) {
     529        psMetadata *conceptsChip = pmConceptsSpecs(PM_FPA_LEVEL_CHIP); // Concept specifications for Chip
     530        spec = psMetadataLookupPtr(&mdok, conceptsChip, name);
     531        if (!spec) {
     532            psMetadata *conceptsCell = pmConceptsSpecs(PM_FPA_LEVEL_CELL); // Concept specifications for Cell
     533            spec = psMetadataLookupPtr(&mdok, conceptsCell, name);
     534            if (!spec) {
     535                psError(PS_ERR_UNEXPECTED_NULL, true, "Unable to find specification for concept %s", name);
     536                return false;
     537            }
     538        }
     539    }
     540
     541    if (!p_pmConceptWriteToCells(cell, spec, conceptItem, format) &&
     542        !p_pmConceptWriteToDefaults(fpa, chip, cell, spec, conceptItem, format, NULL) &&
     543        !p_pmConceptWriteToHeader(fpa, chip, cell, spec, conceptItem, format, NULL) &&
     544        !p_pmConceptWriteToDatabase(fpa, chip, cell, config, spec, conceptItem, format, NULL)) {
     545        return false;
     546    }
    427547    return true;
    428548}
    429 
    430 // XXX Warning: This code has not been tested at all
    431 bool p_pmConceptsWriteToDatabase(const psMetadata *specs, const pmFPA *fpa, const pmChip *chip,
    432                                  const pmCell *cell, pmConfig *config, const psMetadata *concepts)
    433 {
    434     PS_ASSERT_PTR_NON_NULL(specs, false);
    435     PS_ASSERT_PTR_NON_NULL(concepts, false);
    436     PS_ASSERT_PTR_NON_NULL(config, false);
    437 
    438     #ifndef HAVE_PSDB
    439     return false;
    440     #else
    441 
    442     pmHDU *hdu = pmHDUGetLowest(fpa, chip, cell); // The HDU at the lowest level
    443     if (!hdu) {
    444         return false;
    445     }
    446     psMetadata *cameraFormat = hdu->format; // The camera format
    447     bool mdok = true;                   // Status of MD lookup
    448     psMetadata *database = psMetadataLookupMetadata(&mdok, cameraFormat, "DATABASE"); // The DATABASE spec
    449     if (!mdok || !database) {
    450         return false;
    451     }
    452     psMetadataIterator *specsIter = psMetadataIteratorAlloc(specs, PS_LIST_HEAD, NULL); // Iterator
    453     psMetadataItem *specItem = NULL;    // Item from the specs metadata
    454     while ((specItem = psMetadataGetAndIncrement(specsIter))) {
    455         pmConceptSpec *spec = specItem->data.V; // The specification
    456         psString name = specItem->name; // The concept name
    457 
    458         psMetadataItem *dbItem = p_pmConceptsReadSingleFromDatabase(name, database, config, fpa, chip, cell);
    459         if (!dbItem) {
    460             continue;
    461         }
    462 
    463         psMetadataItem *conceptItem = psMetadataLookup(concepts, name); // The item from the concepts
    464         psMetadataItem *formatted = conceptFormat(spec, conceptItem, PM_CONCEPT_SOURCE_DATABASE,
    465                                                   cameraFormat, fpa, chip, cell);
    466         if (!formatted) {
    467             continue;
    468         }
    469 
    470         if (strcmp(dbItem->name, name) != 0) {
    471             // Correct the name to match the concept name
    472             dbItem = psMetadataItemCopy(dbItem);
    473             psFree(dbItem->name);
    474             dbItem->name = psStringCopy(name);
    475         } else {
    476             psMemIncrRefCounter(dbItem);
    477         }
    478 
    479         if (!compareConcepts(formatted, dbItem)) {
    480             psWarning("Concept %s is specified by the DATABASE in the camera "
    481                       "format, but the values don't match.\n", name);
    482         }
    483         psFree(dbItem);
    484         psFree(formatted);
    485     }
    486     psFree(specsIter);
    487     return true;
    488     #endif
    489 }
    490 
    491 
    492 
    493549
    494550
     
    498554                          const pmChip *chip, // The chip
    499555                          const pmCell *cell, // The cell
    500                           pmConceptSource source, // The source of the concepts to write
    501556                          pmConfig *config, // Configuration
    502557                          psMetadata *concepts // The concepts to write out
     
    508563    pmConceptsInit();
    509564
    510     psTrace("psModules.concepts", 3, "Writing concepts (%p %p %p): %d\n", fpa, chip, cell, source);
    511 
    512     if (source & PM_CONCEPT_SOURCE_CELLS) {
    513         p_pmConceptsWriteToCells(*specs, cell, concepts);
    514     }
    515     if (source & PM_CONCEPT_SOURCE_DEFAULTS) {
    516         p_pmConceptsWriteToDefaults(*specs, fpa, chip, cell, concepts);
    517     }
    518     if (source & (PM_CONCEPT_SOURCE_PHU | PM_CONCEPT_SOURCE_HEADER)) {
    519         p_pmConceptsWriteToHeader(*specs, fpa, chip, cell, concepts);
    520     }
    521     if (source & PM_CONCEPT_SOURCE_DATABASE) {
    522         p_pmConceptsWriteToDatabase(*specs, fpa, chip, cell, config, concepts);
    523     }
     565    psTrace("psModules.concepts", 3, "Writing concepts (%p %p %p)\n", fpa, chip, cell);
     566
     567    psMetadata *format = conceptsCameraFormat(fpa, chip, cell); // Camera format
     568    if (!format) {
     569        psError(PS_ERR_UNKNOWN, false, "Unable to retrieve camera format.");
     570        return false;
     571    }
     572
     573    psMetadata *defaults = conceptsDefaults(format); // DEFAULTS configuration
     574    psMetadata *translation = conceptsTranslation(format); // TRANSLATION configuration
     575    psMetadata *database = conceptsDatabase(format); // DATABASE configuration
     576
     577    psMetadataIterator *iter = psMetadataIteratorAlloc(*specs, PS_LIST_HEAD, NULL); // Iterator
     578    psMetadataItem *item = NULL;    // Item from the specs metadata
     579    while ((item = psMetadataGetAndIncrement(iter))) {
     580        pmConceptSpec *spec = item->data.V; // The specification
     581        psString name = item->name; // The concept name
     582
     583        psMetadataItem *concept = psMetadataLookup(concepts, name); // Concept to write
     584
     585        if (!p_pmConceptWriteToCells(cell, spec, concept, format) &&
     586            !p_pmConceptWriteToDefaults(fpa, chip, cell, spec, concept, format, defaults) &&
     587            !p_pmConceptWriteToHeader(fpa, chip, cell, spec, concept, format, translation) &&
     588            !p_pmConceptWriteToDatabase(fpa, chip, cell, config, spec, concept, format, database)) {
     589            psTrace("psModules.concepts", 1, "Unable to write concept %s to any output", name);
     590        }
     591    }
     592    psFree(iter);
    524593
    525594    return true;
     
    527596
    528597
    529 bool pmConceptsWriteFPA(const pmFPA *fpa, pmConceptSource source, bool propagateDown, pmConfig *config)
     598bool pmConceptsWriteFPA(const pmFPA *fpa, bool propagateDown, pmConfig *config)
    530599{
    531600    PS_ASSERT_PTR_NON_NULL(fpa, false);
    532601    psMetadata *conceptsFPA = pmConceptsSpecs(PM_FPA_LEVEL_FPA); // Concept specifications
    533602    psTrace("psModules.concepts", 5, "Writing FPA concepts: %p %p\n", conceptsFPA, fpa->concepts);
    534     bool success = conceptsWrite(&conceptsFPA, fpa, NULL, NULL, source, config, fpa->concepts);
     603    bool success = conceptsWrite(&conceptsFPA, fpa, NULL, NULL, config, fpa->concepts);
    535604    if (propagateDown) {
    536605        psArray *chips = fpa->chips;        // Array of chips
     
    538607            pmChip *chip = chips->data[i];  // Chip of interest
    539608            if (chip && !chip->hdu) {
    540                 success &= pmConceptsWriteChip(chip, source, false, true, config);
     609                success &= pmConceptsWriteChip(chip, false, true, config);
    541610            }
    542611        }
     
    546615
    547616
    548 bool pmConceptsWriteChip(const pmChip *chip, pmConceptSource source, bool propagateUp,
    549                          bool propagateDown, pmConfig *config)
     617bool pmConceptsWriteChip(const pmChip *chip, bool propagateUp, bool propagateDown, pmConfig *config)
    550618{
    551619    PS_ASSERT_PTR_NON_NULL(chip, false);
     
    553621    psTrace("psModules.concepts", 5, "Writing chip concepts: %p %p\n", conceptsChip, chip->concepts);
    554622    pmFPA *fpa = chip->parent;          // FPA to which the chip belongs
    555     bool success = conceptsWrite(&conceptsChip, fpa, chip, NULL, source, config, chip->concepts);
     623    bool success = conceptsWrite(&conceptsChip, fpa, chip, NULL, config, chip->concepts);
    556624    if (propagateUp && !fpa->hdu) {
    557625        psMetadata *conceptsFPA = pmConceptsSpecs(PM_FPA_LEVEL_FPA); // Concept specifications
    558         success &= conceptsWrite(&conceptsFPA, fpa, chip, NULL, source, config, fpa->concepts);
     626        success &= conceptsWrite(&conceptsFPA, fpa, chip, NULL, config, fpa->concepts);
    559627    }
    560628    if (propagateDown) {
     
    563631            pmCell *cell = cells->data[i];  // Cell of interest
    564632            if (cell && !cell->hdu) {
    565                 success &= pmConceptsWriteCell(cell, source, false, config);
     633                success &= pmConceptsWriteCell(cell, false, config);
    566634            }
    567635        }
     
    571639
    572640
    573 bool pmConceptsWriteCell(const pmCell *cell, pmConceptSource source, bool propagateUp, pmConfig *config)
     641bool pmConceptsWriteCell(const pmCell *cell, bool propagateUp, pmConfig *config)
    574642{
    575643    PS_ASSERT_PTR_NON_NULL(cell, false);
     
    579647    pmFPA *fpa = chip->parent;          // FPA to which the chip belongs
    580648
    581     bool success = conceptsWrite(&conceptsCell, fpa, chip, cell, source, config, cell->concepts);
     649    bool success = conceptsWrite(&conceptsCell, fpa, chip, cell, config, cell->concepts);
    582650    if (propagateUp) {
    583651        if (!chip->hdu) {
    584652            psMetadata *conceptsChip = pmConceptsSpecs(PM_FPA_LEVEL_CHIP); // Concept specifications
    585             success &= conceptsWrite(&conceptsChip, fpa, chip, cell, source, config, chip->concepts);
     653            success &= conceptsWrite(&conceptsChip, fpa, chip, cell, config, chip->concepts);
    586654            if (!fpa->hdu) {
    587655                psMetadata *conceptsFPA = pmConceptsSpecs(PM_FPA_LEVEL_FPA); // Concept specifications
    588                 success &= conceptsWrite(&conceptsFPA, fpa, chip, cell, source, config, fpa->concepts);
     656                success &= conceptsWrite(&conceptsFPA, fpa, chip, cell, config, fpa->concepts);
    589657            }
    590658        }
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/concepts/pmConceptsWrite.h

    r22699 r23594  
    2020/// @{
    2121
    22 /// "Write" concepts to (actually, check against) the camera format file's CELLS.
     22/// "Write" concept to (actually, check against) the camera format file's CELLS.
    2323///
    2424/// Examines the CELLS metadata in the camera format file for the current type of cell, and checks that the
    25 /// concepts as defined there match the ones defined in the cell.  A warning is produced if the concepts do
     25/// concept as defined there match the ones defined in the cell.  A warning is produced if the concept does
    2626/// not match.
    27 bool p_pmConceptsWriteToCells(const psMetadata *specs, ///< The concept specifications
     27bool p_pmConceptWriteToCells(const pmCell *cell, ///< The cell
     28                             const pmConceptSpec *spec, ///< Concept specification
     29                             const psMetadataItem *conceptItem, ///< Concept to write
     30                             const psMetadata *format ///< Camera format, or NULL
     31    );
     32
     33/// "Write" concept to (actually, check against) the camera format file's DEFAULTS.
     34///
     35/// Examines the DEFAULTS metadata in the camera format file, and checks that the concept as defined there
     36/// match the one defined in the cell.  A warning is produced if the concept does not match.
     37bool p_pmConceptWriteToDefaults(const pmFPA *fpa, ///< The FPA
     38                                const pmChip *chip, ///< The chip
     39                                const pmCell *cell, ///< The cell
     40                                const pmConceptSpec *spec, ///< Concept specification
     41                                const psMetadataItem *conceptItem,      ///< Concept to write
     42                                const psMetadata *format, ///< Camera format, or NULL
     43                                const psMetadata *defaults ///< DEFAULTS configuration, or NULL
     44    );
     45
     46/// "Write" concept to (actually, add to, pending a later write) the FITS header.
     47///
     48/// Examines the FITS header TRANSLATION metadata in the camera format file, and writes concept to the
     49/// appropriate FITS header(s) in the HDU, in preparation for a future write of the HDU.
     50bool p_pmConceptWriteToHeader(const pmFPA *fpa, ///< The FPA
     51                              const pmChip *chip, ///< The chip
    2852                              const pmCell *cell, ///< The cell
    29                               const psMetadata *concepts ///< The concepts
    30                              );
     53                              const pmConceptSpec *spec, ///< Concept specification
     54                              const psMetadataItem *conceptItem, ///< Concept to write
     55                              const psMetadata *format, ///< Camera format, or NULL
     56                              const psMetadata *translation ///< TRANSLATION configuration, or NULL
     57                              );
    3158
    32 /// "Write" concepts to (actually, check against) the camera format file's DEFAULTS.
     59/// Write concept to the database.
    3360///
    34 /// Examines the DEFAULTS metadata in the camera format file, and checks that the concepts as defined there
    35 /// match the ones defined in the cell.  A warning is produced if the concepts do not match.
    36 bool p_pmConceptsWriteToDefaults(const psMetadata *specs, ///< The concept specifications
    37                                  const pmFPA *fpa, ///< The FPA
    38                                  const pmChip *chip, ///< The chip
    39                                  const pmCell *cell, ///< The cell
    40                                  const psMetadata *concepts ///< The concepts
     61/// Examines the DATABASE metadata in the camera format file, and writes (actually, check against)
     62/// concept to the database.
     63bool p_pmConceptWriteToDatabase(const pmFPA *fpa, ///< The FPA
     64                                const pmChip *chip, ///< The chip
     65                                const pmCell *cell, ///< The cell
     66                                pmConfig *config, ///< Configuration
     67                                const pmConceptSpec *spec, ///< Concept specification
     68                                const psMetadataItem *conceptItem, ///< Concept to write
     69                                const psMetadata *format, ///< Camera format, or NULL
     70                                const psMetadata *database ///< DATABASE configuration, or NULL
    4171                                );
    4272
    43 /// "Write" concepts to (actually, add to, pending a later write) the FITS header.
    44 ///
    45 /// Examines the FITS header TRANSLATION metadata in the camera format file, and writes concepts to the
    46 /// appropriate FITS headers in the HDU, in preparation for a future write of the HDU.
    47 bool p_pmConceptsWriteToHeader(const psMetadata *specs, ///< The concept specifications
    48                                const pmFPA *fpa, ///< The FPA
    49                                const pmChip *chip, ///< The chip
    50                                const pmCell *cell, ///< The cell
    51                                const psMetadata *concepts ///< The concepts
    52                               );
    5373
    54 /// Write concepts to the database.
    55 ///
    56 /// Examines the DATABASE metadata in the camera format file, and writes concepts to the database.
    57 /// Warning: This function has not been tested; use at your own risk.
    58 bool p_pmConceptsWriteToDatabase(const psMetadata *specs, ///< The concept specifications
    59                                  const pmFPA *fpa, ///< The FPA
    60                                  const pmChip *chip, ///< The chip
    61                                  const pmCell *cell, ///< The cell
    62                                  pmConfig *config,///< Configuration
    63                                  const psMetadata *concepts ///< The concepts
    64                                 );
     74bool pmConceptWriteSingle(const pmFPA *fpa, ///< The FPA
     75                          const pmChip *chip, ///< The chip
     76                          const pmCell *cell, ///< The cell
     77                          pmConfig *config, ///< Configuration
     78                          const psMetadataItem *concept ///< Concept to write
     79    );
    6580
    6681
     
    7085/// written for all lower levels by iterating over the components.
    7186bool pmConceptsWriteFPA(const pmFPA *fpa,     ///< FPA for which to write concepts
    72                         pmConceptSource source, ///< Source for concepts
    7387                        bool propagateDown, ///< Propagate to lower levels?
    7488                        pmConfig *config        ///< Configuration
     
    8094/// written for the FPA, and the cell level by iterating over the components.
    8195bool pmConceptsWriteChip(const pmChip *chip,  ///< Chip for which to write concepts
    82                          pmConceptSource source, ///< Source for concepts
    8396                         bool propagateUp,///< Propagate to higher levels?
    8497                         bool propagateDown, ///< Propagate to lower levels?
     
    92105/// only the parent of this cell).
    93106bool pmConceptsWriteCell(const pmCell *cell,  ///< FPA for which to write concepts
    94                          pmConceptSource source, ///< Source for concepts
    95107                         bool propagateUp, ///< Propagate to higher levels?
    96108                         pmConfig *config ///< Configuration
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/config/pmConfig.c

    r23351 r23594  
    806806    pmConfigLoadRecipeOptions(argc, argv, config, "-Df");
    807807    pmConfigLoadRecipeOptions(argc, argv, config, "-Db");
     808
     809    if (!pmConfigReadRecipes(config, PM_RECIPE_SOURCE_CL)) {
     810        psError(PS_ERR_IO, false, "Failed to read recipes from command-line");
     811        psFree(config);
     812        return NULL;
     813    }
    808814
    809815    // Look for command-line options for files to replace
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/config/pmConfigCamera.c

    r23351 r23594  
    159159// Don't update these skycell concepts; last one MUST be 0 (i.e., NULL).
    160160const static char *skycellConceptsCell[] = { "CELL.BIASSEC", "CELL.TRIMSEC", "CELL.READDIR", "CELL.XPARITY",
    161                                              "CELL.YPARITY", "CELL.X0", "CELL.Y0", 0 };
     161                                             "CELL.YPARITY", "CELL.X0", "CELL.Y0", "CELL.TIMESYS", 0 };
    162162const static char *skycellConceptsChip[] = { "CHIP.XPARITY", "CHIP.YPARITY", 0 };
    163 const static char *skycellConceptsFPA[] = { 0 };
     163const static char *skycellConceptsFPA[] = { "FPA.TIMESYS" };
    164164
    165165// What do we call the skycell concept in the FITS header?
     
    332332        psMetadataAddS32(defaults, PS_LIST_TAIL, "CHIP.X0", 0, NULL, 0);
    333333        psMetadataAddS32(defaults, PS_LIST_TAIL, "CELL.READDIR", 0, "Read direction (rows)", 1);
     334        psMetadataAddStr(defaults, PS_LIST_TAIL, "CELL.TIMESYS", 0, "Time system", "TAI");
     335        psMetadataAddStr(defaults, PS_LIST_TAIL, "FPA.TIMESYS", 0, "Time system", "TAI");
    334336
    335337        psMetadataAddMetadata(format, PS_LIST_TAIL, "DEFAULTS", 0, "Default values for concepts", defaults);
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/config/pmConfigMask.c

    r21386 r23594  
    1010
    1111static pmConfigMaskInfo masks[] = {
    12     { "DETECTOR",  NULL,       0x00, true  },   // Something is wrong with the detector
    13     { "DARK",      "DETECTOR", 0x00, true  },   // Pixel doesn't dark-subtract properly
    14     { "FLAT",      "DETECTOR", 0x01, true  },   // Pixel doesn't flat-field properly
    15     { "BLANK",     "DETECTOR", 0x01, true  },   // Pixel doesn't contain valid data
    16     { "RANGE",     NULL,       0x00, true  },   // Pixel is out-of-range of linearity
    17     { "SAT",       "RANGE",    0x01, true  },   // Pixel is saturated
    18     { "BAD",       "RANGE",    0x01, true  },   // Pixel is low
    19     { "BAD.WARP",  NULL,       0x01, true  },   // Pixel is bad after convolution with a bad pixel
    20     { "CR",        NULL,       0x00, true  },   // Pixel contains a cosmic ray
    21     { "GHOST",     NULL,       0x00, true  },   // Pixel contains an optical ghost
    22     { "POOR.WARP", NULL,       0x00, false },   // Pixel is poor after convolution with a bad pixel
    23     // "LOW"  Pixel is low
    24     // "CONV" Pixel is bad after convolution with a bad pixel
     12    // Features of the detector
     13    { "DETECTOR",  NULL,       0x01, true  }, // Something is wrong with the detector
     14    { "FLAT",      "DETECTOR", 0x01, true  }, // Pixel doesn't flat-field properly
     15    { "DARK",      "DETECTOR", 0x01, true  }, // Pixel doesn't dark-subtract properly
     16    { "BLANK",     "DETECTOR", 0x01, true  }, // Pixel doesn't contain valid data
     17    { "CTE",       "DETECTOR", 0x01, true  }, // Pixel has poor CTE
     18    // Invalid signal ranges
     19    { "SAT",       NULL,       0x02, true  }, // Pixel is saturated or non-linear
     20    { "LOW",       "SAT",      0x02, true  }, // Pixel is low
     21    { "SUSPECT",   NULL,       0x04, false }, // Pixel is suspected of being bad
     22    // Non-astronomical structures
     23    { "CR",        NULL,       0x08, true  }, // Pixel contains a cosmic ray
     24    { "SPIKE",     NULL,       0x08, true  }, // Pixel contains a diffraction spike
     25    { "GHOST",     NULL,       0x08, true  }, // Pixel contains an optical ghost
     26    { "STREAK",    NULL,       0x08, true  }, // Pixel contains streak data
     27    { "STARCORE",  NULL,       0x08, true  }, // Pixel contains a bright star core
     28    // Effects of convolution and interpolation
     29    { "CONV.BAD",  NULL,       0x02, true  }, // Pixel is bad after convolution with a bad pixel
     30    { "CONV.POOR", NULL,       0x04, false }, // Pixel is poor after convolution with a bad pixel
    2531};
    2632
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/config/pmConfigRun.c

    r23351 r23594  
    3939}
    4040
    41 
    42 bool pmConfigRunFileAdd(pmConfig *config, const pmFPAfile *file)
     41// Add a file to a nominated metadata in the RUN information
     42static bool configRunFileAdd(pmConfig *config, // Configuration
     43                             const pmFPAfile *file, // File to add
     44                             const char *target // Name of metadata to which to add
     45                             )
    4346{
    4447    PS_ASSERT_PTR_NON_NULL(config, false);
     
    4750    psMetadata *run = configRun(config);// RUN information
    4851    psAssert(run, "Require run-time information");
    49     psMetadata *files = configElement(run, "FILES", "Filerules used during execution");
     52    psMetadata *files = configElement(run, target, "Filerules used during execution");
    5053    psAssert(files, "Require list of files");
    5154
     
    7174}
    7275
    73 psArray *pmConfigRunFileGet(pmConfig *config, const char *name)
     76bool pmConfigRunFileAddRead(pmConfig *config, const pmFPAfile *file)
    7477{
    7578    PS_ASSERT_PTR_NON_NULL(config, false);
    76     PS_ASSERT_STRING_NON_EMPTY(name, false);
     79    PS_ASSERT_PTR_NON_NULL(file, false);
    7780
     81    return configRunFileAdd(config, file, "FILES.INPUT");
     82}
     83
     84bool pmConfigRunFileAddWrite(pmConfig *config, const pmFPAfile *file)
     85{
     86    PS_ASSERT_PTR_NON_NULL(config, false);
     87    PS_ASSERT_PTR_NON_NULL(file, false);
     88
     89    return configRunFileAdd(config, file, "FILES.OUTPUT");
     90}
     91
     92// Get an array of filenames from the nominated RUN information
     93static psArray *configRunFileGet(pmConfig *config, // Configuration
     94                                 const char *name, // Name of file
     95                                 const char *source // Source metadata for file
     96                                 )
     97{
    7898    psMetadata *run = configRun(config);// RUN information
    7999    psAssert(run, "Require run-time information");
    80     psMetadata *files = configElement(run, "FILES", "Filerules used during execution");
     100    psMetadata *files = configElement(run, source, "Filerules used during execution");
    81101    psAssert(files, "Require list of files");
     102
     103    if (psListLength(files->list) == 0) {
     104        // Can't find anything
     105        return NULL;
     106    }
    82107
    83108    psList *list = psListAlloc(NULL);   // List of file names
     
    104129
    105130    return array;
     131}
     132
     133
     134psArray *pmConfigRunFileGet(pmConfig *config, const char *name)
     135{
     136    PS_ASSERT_PTR_NON_NULL(config, false);
     137    PS_ASSERT_STRING_NON_EMPTY(name, false);
     138
     139    // Try the input and output, in turn
     140    psArray *files = configRunFileGet(config, name, "FILES.INPUT"); // Files from RUN metadata
     141    if (!files) {
     142        configRunFileGet(config, name, "FILES.OUTPUT");
     143    }
     144
     145    return files;
    106146}
    107147
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/config/pmConfigRun.h

    r23351 r23594  
    66#include <pmFPAfile.h>
    77
    8 /// Add a file to the list of files used in the run-time information
    9 bool pmConfigRunFileAdd(
     8/// Add a file to the list of files read in the run-time information
     9bool pmConfigRunFileAddRead(
     10    pmConfig *config,                   ///< Configuration
     11    const pmFPAfile *file               ///< File to add
     12    );
     13
     14/// Add a file to the list of files written in the run-time information
     15bool pmConfigRunFileAddWrite(
    1016    pmConfig *config,                   ///< Configuration
    1117    const pmFPAfile *file               ///< File to add
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/detrend/pmDetrendDB.h

    r23351 r23594  
    6363
    6464pmDetrendSelectOptions *pmDetrendSelectOptionsAlloc(const char *camera, psTime time, pmDetrendType type);
    65 pmDetrendSelectResults *pmDetrendSelectResultsAlloc();
     65pmDetrendSelectResults *pmDetrendSelectResultsAlloc(void);
    6666pmDetrendSelectResults *pmDetrendSelect (const pmDetrendSelectOptions *options, const pmConfig *config);
    6767char *pmDetrendFile (const char *detID, const char *classID, const pmConfig *config);
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/detrend/pmDetrendThreads.h

    r18893 r23594  
    1818
    1919/// get the requested number of scan rows per thread
    20 int pmDetrendGetScanRows ();
     20int pmDetrendGetScanRows(void);
    2121
    2222/// @}
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/detrend/pmShutterCorrection.c

    r23351 r23594  
    7171}
    7272
    73 pmShutterCorrection *pmShutterCorrectionAlloc()
     73pmShutterCorrection *pmShutterCorrectionAlloc(void)
    7474{
    7575    pmShutterCorrection *corr = (pmShutterCorrection*)psAlloc(sizeof(pmShutterCorrection));
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/detrend/pmShutterCorrection.h

    r21509 r23594  
    6969
    7070/// Allocator for shutter correction parameters
    71 pmShutterCorrection *pmShutterCorrectionAlloc();
     71pmShutterCorrection *pmShutterCorrectionAlloc(void);
    7272
    7373/// Guess a shutter correction, based on plot of counts vs exposure time
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/extras/pmKapaPlots.c

    r13896 r23594  
    4747}
    4848
    49 bool pmKapaClose ()
     49bool pmKapaClose (void)
    5050{
    5151
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/extras/pmKapaPlots.h

    r12696 r23594  
    11/* @file  pmKapaPlots.h
    2  * @brief functions to make plots with the external program 'kapa' 
     2 * @brief functions to make plots with the external program 'kapa'
    33 *
    44 * @author EAM, IfA
     
    1717// move to psLib or psModules
    1818int pmKapaOpen (bool showWindow);
    19 bool pmKapaClose ();
     19bool pmKapaClose(void);
    2020bool pmKapaPlotVectorPair (psVector *xVec, psVector *yVec);
    2121
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/extras/psPipe.c

    r12888 r23594  
    3535}
    3636
    37 psPipe *psPipeAlloc ()
     37psPipe *psPipeAlloc (void)
    3838{
    3939    psPipe *pipe = (psPipe *)psAlloc(sizeof(psPipe));
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/extras/psPipe.h

    r11253 r23594  
    11/* @file  psPipe.h
    2  * @brief 3-stream pipe 
     2 * @brief 3-stream pipe
    33 *
    44 * @author EAM, IfA
     
    2626
    2727// psPipe functions
    28 psPipe *psPipeAlloc ();
     28psPipe *psPipeAlloc (void);
    2929psPipe *psPipeOpen (char *command);
    3030int     psPipeClose (psPipe *pipe);
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/imcombine/pmStack.c

    r23351 r23594  
    4646    psVector *weights;                  // Pixel weightings
    4747    psVector *sources;                  // Pixel sources (which image did they come from?)
     48    psVector *limits;                   // Rejection limits
    4849    psVector *sort;                     // Buffer for sorting (to get a robust estimator of the standard dev)
    4950} combineBuffer;
     
    5657    psFree(buffer->weights);
    5758    psFree(buffer->sources);
     59    psFree(buffer->limits);
    5860    psFree(buffer->sort);
    5961    return;
     
    7173    buffer->weights = psVectorAlloc(numImages, PS_TYPE_F32);
    7274    buffer->sources = psVectorAlloc(numImages, PS_TYPE_U16);
     75    buffer->limits = psVectorAlloc(numImages, PS_TYPE_F32);
    7376    buffer->sort = psVectorAlloc(numImages, PS_TYPE_F32);
    7477    return buffer;
     
    319322                          bool useVariance, // Use variance for rejection when combining?
    320323                          bool safe,    // Combine safely?
     324                          bool rejectInspect, // Reject values marked for inspection from combination?
    321325                          combineBuffer *buffer // Buffer for combination; to avoid multiple allocations
    322326                         )
     
    336340    psVector *pixelWeights = buffer->weights; // Image weights for the pixel of interest
    337341    psVector *pixelSources = buffer->sources; // Sources for the pixel of interest
     342    psVector *pixelLimits = buffer->limits; // Limits for the pixel of interest
    338343    psVector *sort = buffer->sort;      // Sort buffer
    339344
     
    375380    pixelWeights->n = num;
    376381    pixelSources->n = num;
     382    pixelLimits->n = num;
    377383
    378384#ifdef TESTING
     
    389395    // Default option is that the pixel is bad
    390396    float imageValue = NAN, varianceValue = NAN; // Value for combined image and variance map
    391     psImageMaskType maskValue = bad;         // Value for combined mask
     397    psImageMaskType maskValue = bad;    // Value for combined mask
    392398    switch (num) {
    393399      case 0:
     
    449455              if (PS_SQR(diff) > PS_SQR(rej) * sigma2) {
    450456                  // Not consistent: mark both for inspection
    451                   combineInspect(inputs, x, y, pixelSources->data.U16[0]);
    452                   combineInspect(inputs, x, y, pixelSources->data.U16[1]);
     457                  if (rejectInspect) {
     458                      imageValue = NAN;
     459                      varianceValue = NAN;
     460                      maskValue = bad;
     461                  } else {
     462                      combineInspect(inputs, x, y, pixelSources->data.U16[0]);
     463                      combineInspect(inputs, x, y, pixelSources->data.U16[1]);
     464                  }
    453465#ifdef TESTING
    454466                  if (x == TEST_X && y == TEST_Y) {
     
    501513#endif
    502514
    503                       pixelVariances->data.F32[i] = rej2 * (pixelVariances->data.F32[i] + sysVar);
     515                      pixelLimits->data.F32[i] = rej2 * (pixelVariances->data.F32[i] + sysVar);
    504516                  }
    505517              }
     
    541553#define MASK_PIXEL_FOR_INSPECTION() \
    542554    pixelMasks->data.PS_TYPE_VECTOR_MASK_DATA[j] = 0xff; \
    543     combineInspect(inputs, x, y, pixelSources->data.U16[j]); \
     555    if (!rejectInspect) { \
     556        combineInspect(inputs, x, y, pixelSources->data.U16[j]); \
     557    } \
    544558    numClipped++; \
    545559    totalClipped++;
     
    553567                      // Comparing squares --- cheaper than lots of sqrts
    554568                      // pixelVariances includes the rejection limit, from above
    555                       if (PS_SQR(diff) > pixelVariances->data.F32[j]) {
     569                      if (PS_SQR(diff) > pixelLimits->data.F32[j]) {
    556570                          MASK_PIXEL_FOR_INSPECTION();
    557571#ifdef TESTING
    558572                          if (x == TEST_X && y == TEST_Y) {
    559573                              fprintf(stderr, "Rejecting input %d based on variance: %f > %f\n",
    560                                       j, diff, sqrtf(pixelVariances->data.F32[j]));
     574                                      j, diff, sqrtf(pixelLimits->data.F32[j]));
    561575                          }
    562576#endif
     
    573587              }
    574588          }
     589
     590          if (rejectInspect && totalClipped > 0) {
     591              // Get rid of the masked values
     592              // The alternative to this is to make combinationMeanVariance() accept a mask
     593              int good = 0;            // Index of good value
     594              for (int i = 0; i < num; i++) {
     595                  if (pixelMasks->data.PS_TYPE_VECTOR_MASK_DATA[i]) {
     596                      continue;
     597                  }
     598                  if (i != good) {
     599                      pixelData->data.F32[good] = pixelData->data.F32[i];
     600                      pixelVariances->data.F32[good] = pixelVariances->data.F32[i];
     601                      pixelWeights->data.F32[good] = pixelWeights->data.F32[i];
     602                      pixelData->data.F32[good] = pixelData->data.F32[i];
     603                  }
     604                  good++;
     605              }
     606              pixelData->n = good;
     607              pixelVariances->n = good;
     608              pixelWeights->n = good;
     609              if (combinationMeanVariance(&mean, &var, pixelData, pixelVariances, pixelWeights)) {
     610                  imageValue = mean;
     611                  varianceValue = var;
     612                  maskValue = 0;
     613              } else {
     614                  imageValue = NAN;
     615                  varianceValue = NAN;
     616                  maskValue = bad;
     617              }
     618          }
     619
    575620          break;
    576621      }
     
    734779bool pmStackCombine(pmReadout *combined, psArray *input, psImageMaskType maskVal, psImageMaskType bad,
    735780                    int kernelSize, int numIter, float rej, float sys, float discard,
    736                     bool entire, bool useVariance, bool safe)
     781                    bool entire, bool useVariance, bool safe, bool rejectInspect)
    737782{
    738783    PS_ASSERT_PTR_NON_NULL(combined, false);
     
    838883                    combinePixels(combinedImage, combinedMask, combinedVariance, input, weights,
    839884                                  addVariance, reject, x, y, maskVal, bad, numIter, rej, sys, discard,
    840                                   useVariance, safe, buffer);
     885                                  useVariance, safe, rejectInspect, buffer);
    841886                }
    842887            }
     
    853898                combinePixels(combinedImage, combinedMask, combinedVariance, input, weights,
    854899                              addVariance, reject, x, y, maskVal, bad, numIter, rej, sys, discard,
    855                               useVariance, safe, buffer);
     900                              useVariance, safe, rejectInspect, buffer);
    856901            }
    857902        }
     
    881926                combinePixels(combinedImage, combinedMask, combinedVariance, input, weights,
    882927                              addVariance, NULL, x, y, maskVal, bad, numIter, rej, sys, discard,
    883                               useVariance, safe, buffer);
     928                              useVariance, safe, rejectInspect, buffer);
    884929            }
    885930        }
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/imcombine/pmStack.h

    r21476 r23594  
    5252                    bool entire,        ///< Combine entire image even if rejection lists provided?
    5353                    bool useVariance,   ///< Use variance values for rejection?
    54                     bool safe           ///< Play safe with small numbers of input pixels (mask if N <= 2)?
     54                    bool safe,          ///< Play safe with small numbers of input pixels (mask if N <= 2)?
     55                    bool rejectInspect  ///< Reject pixels instead of marking them for inspection?
    5556    );
    5657
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/imcombine/pmSubtractionIO.c

    r23351 r23594  
    44
    55#include "pmHDU.h"
     6#include "pmHDUUtils.h"
    67#include "pmFPA.h"
    78#include "pmFPAview.h"
     
    143144    psMetadata *header = psMetadataAlloc(); // Header for FITS file
    144145
     146    pmCell *cell = ro->parent;          // Cell of interest
     147    if (cell) {
     148        pmChip *chip = cell->parent;    // Chip of interest
     149        pmFPA *fpa = chip->parent;      // FPA of interest
     150        pmHDU *hdu = pmHDUGetHighest(fpa, chip, cell); // HDU for readout
     151        if (hdu) {
     152            header = psMetadataCopy(header, hdu->header);
     153        }
     154    }
     155
    145156    // CVS tags, used to identify the version of this file (in case incompatibilities are introduced)
    146157    psString cvsFile = psStringCopy("$RCSfile: pmSubtractionIO.c,v $");
     
    533544        return true;
    534545    }
    535     if (file->fileLevel != PM_FPA_LEVEL_FPA) {
    536         return true;
    537     }
    538     if (file->fpa->chips->n == 1) {
    539         return true;
    540     }
    541546
    542547    // find the FPA phu
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/imcombine/pmSubtractionVisual.c

    r23351 r23594  
    4444
    4545/** destroy windows at the end of a run*/
    46 bool pmSubtractionVisualClose()
     46bool pmSubtractionVisualClose(void)
    4747{
    4848    if(kapa != -1)
     
    256256
    257257#else
    258 bool pmSubtractionVisualClose() {return true;}
     258bool pmSubtractionVisualClose(void) {return true;}
    259259bool pmSubtractionVisualPlotConvKernels(psImage *convKernels) {return true;}
    260260bool pmSubtractionVisualPlotStamps(pmSubtractionStampList *stamps, pmReadout *ro) {return true;}
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/imcombine/pmSubtractionVisual.h

    r23351 r23594  
    22#define PM_SUBTRACTION_VISUAL_H
    33
    4 bool pmSubtractionVisualClose();
     4bool pmSubtractionVisualClose(void);
    55bool pmSubtractionVisualPlotConvKernels(psImage *convKernels);
    66bool pmSubtractionVisualPlotStamps(pmSubtractionStampList *stamps, pmReadout *ro);
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/objects/pmDetections.c

    r18828 r23594  
    3030
    3131// generate a pmDetections container with empty (allocated) footprints and peaks containers
    32 pmDetections *pmDetectionsAlloc() {
     32pmDetections *pmDetectionsAlloc(void) {
    3333
    3434    pmDetections *detections = (pmDetections *)psAlloc(sizeof(pmDetections));
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/objects/pmDetections.h

    r18828 r23594  
    2020 */
    2121typedef struct {
    22   psArray *footprints;        // collection of footprints in the image
    23   psArray *peaks;             // collection of all peaks contained by the footprints
    24   psArray *oldPeaks;          // collection of all peaks previously found
     22  psArray *footprints;        // collection of footprints in the image
     23  psArray *peaks;             // collection of all peaks contained by the footprints
     24  psArray *oldPeaks;          // collection of all peaks previously found
    2525  int last;
    2626} pmDetections;
    2727
    28 pmDetections *pmDetectionsAlloc ();
     28pmDetections *pmDetectionsAlloc (void);
    2929
    3030/// @}
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/objects/pmMoments.c

    r23351 r23594  
    2525to zero.
    2626*****************************************************************************/
    27 pmMoments *pmMomentsAlloc()
     27pmMoments *pmMomentsAlloc(void)
    2828{
    2929    psTrace("psModules.objects", 10, "---- %s() begin ----\n", __func__);
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/objects/pmMoments.h

    r19879 r23594  
    5353 *
    5454 */
    55 pmMoments *pmMomentsAlloc();
     55pmMoments *pmMomentsAlloc(void);
    5656
    5757/// @}
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/objects/pmPSF.c

    r20937 r23594  
    5454}
    5555
    56 pmPSFOptions *pmPSFOptionsAlloc () {
     56pmPSFOptions *pmPSFOptionsAlloc (void) {
    5757
    5858    pmPSFOptions *options = (pmPSFOptions *) psAlloc(sizeof(pmPSFOptions));
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/objects/pmPSF.h

    r21183 r23594  
    9696pmPSF *pmPSFAlloc (const pmPSFOptions *options);
    9797bool psMemCheckPSF(psPtr ptr);
    98 pmPSFOptions *pmPSFOptionsAlloc();
     98pmPSFOptions *pmPSFOptionsAlloc(void);
    9999bool psMemCheckPSFOptions(psPtr ptr);
    100100
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/objects/pmSource.h

    r23351 r23594  
    105105 *
    106106 */
    107 pmSource  *pmSourceAlloc();
     107pmSource  *pmSourceAlloc(void);
    108108
    109109/** pmSourceCopy()
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/objects/pmSourceExtendedPars.c

    r21363 r23594  
    4646}
    4747
    48 pmSourceExtendedPars *pmSourceExtendedParsAlloc () {
     48pmSourceExtendedPars *pmSourceExtendedParsAlloc (void) {
    4949    pmSourceExtendedPars *pars = (pmSourceExtendedPars *) psAlloc(sizeof(pmSourceExtendedPars));
    5050    psMemSetDeallocator(pars, (psFreeFunc) pmSourceExtendedParsFree);
     
    7575}
    7676
    77 pmSourceRadialProfile *pmSourceRadialProfileAlloc () {
     77pmSourceRadialProfile *pmSourceRadialProfileAlloc (void) {
    7878
    7979    pmSourceRadialProfile *profile = (pmSourceRadialProfile *) psAlloc(sizeof(pmSourceRadialProfile));
     
    9999}
    100100
    101 pmSourceIsophotalValues *pmSourceIsophotalValuesAlloc () {
     101pmSourceIsophotalValues *pmSourceIsophotalValuesAlloc (void) {
    102102
    103103    pmSourceIsophotalValues *isophot = (pmSourceIsophotalValues *) psAlloc(sizeof(pmSourceIsophotalValues));
     
    125125}
    126126
    127 pmSourcePetrosianValues *pmSourcePetrosianValuesAlloc () {
     127pmSourcePetrosianValues *pmSourcePetrosianValuesAlloc (void) {
    128128
    129129    pmSourcePetrosianValues *petrosian = (pmSourcePetrosianValues *) psAlloc(sizeof(pmSourcePetrosianValues));
     
    150150}
    151151
    152 pmSourceKronValues *pmSourceKronValuesAlloc () {
     152pmSourceKronValues *pmSourceKronValuesAlloc (void) {
    153153
    154154    pmSourceKronValues *kron = (pmSourceKronValues *) psAlloc(sizeof(pmSourceKronValues));
     
    181181}
    182182
    183 pmSourceAnnuli *pmSourceAnnuliAlloc () {
     183pmSourceAnnuli *pmSourceAnnuliAlloc (void) {
    184184
    185185    pmSourceAnnuli *annuli = (pmSourceAnnuli *) psAlloc(sizeof(pmSourceAnnuli));
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/objects/pmSourceExtendedPars.h

    r21363 r23594  
    5555} pmSourceExtendedPars;
    5656
    57 pmSourceExtendedPars *pmSourceExtendedParsAlloc ();
     57pmSourceExtendedPars *pmSourceExtendedParsAlloc(void);
    5858bool psMemCheckSourceExtendedPars(psPtr ptr);
    59 pmSourceRadialProfile *pmSourceRadialProfileAlloc ();
     59pmSourceRadialProfile *pmSourceRadialProfileAlloc(void);
    6060bool psMemCheckSourceRadialProfile(psPtr ptr);
    61 pmSourceIsophotalValues *pmSourceIsophotalValuesAlloc ();
     61pmSourceIsophotalValues *pmSourceIsophotalValuesAlloc(void);
    6262bool psMemCheckSourceIsophotalValues(psPtr ptr);
    63 pmSourcePetrosianValues *pmSourcePetrosianValuesAlloc ();
     63pmSourcePetrosianValues *pmSourcePetrosianValuesAlloc(void);
    6464bool psMemCheckSourcePetrosianValues(psPtr ptr);
    65 pmSourceKronValues *pmSourceKronValuesAlloc ();
     65pmSourceKronValues *pmSourceKronValuesAlloc(void);
    6666bool psMemCheckSourceKronValues(psPtr ptr);
    67 pmSourceAnnuli *pmSourceAnnuliAlloc ();
     67pmSourceAnnuli *pmSourceAnnuliAlloc(void);
    6868bool psMemCheckSourceAnnuli(psPtr ptr);
    6969
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/objects/pmSourceFitSet.c

    r23351 r23594  
    6767}
    6868
    69 void pmSourceFitSetDone () {
     69void pmSourceFitSetDone (void) {
    7070    psFree (fitSets);
    7171}
     
    150150}
    151151
    152 pmSourceFitSetData *pmSourceFitSetDataGet () {
     152pmSourceFitSetData *pmSourceFitSetDataGet (void) {
    153153
    154154    psAssert (fitSets, "pmSourceFitSetInit not called");
     
    172172}
    173173
    174 void pmSourceFitSetDataClear () {
     174void pmSourceFitSetDataClear (void) {
    175175
    176176    int i;
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/objects/pmSourceFitSet.h

    r21183 r23594  
    2424// use this function to init the fit sets based on the number of threads
    2525bool pmSourceFitSetInit (int nThreads);
    26 void pmSourceFitSetDone ();
     26void pmSourceFitSetDone (void);
    2727
    2828// initialize data for a group of object models
     
    3232// functions for selecting the FitSet corresponding to the current thread
    3333pmSourceFitSetData *pmSourceFitSetDataSet (psArray *modelSet);
    34 pmSourceFitSetData *pmSourceFitSetDataGet ();
    35 void pmSourceFitSetDataClear ();
     34pmSourceFitSetData *pmSourceFitSetDataGet (void);
     35void pmSourceFitSetDataClear (void);
    3636
    3737// function used to set limits for a group of models
     
    5454 */
    5555bool pmSourceFitSet(
    56     pmSource *source,                   ///< The input pmSource
    57     psArray *modelSet,                  ///< model to be fitted
    58     pmSourceFitMode mode,               ///< define parameters to be fitted
    59     psImageMaskType maskVal             ///< Vale to mask
     56    pmSource *source,                   ///< The input pmSource
     57    psArray *modelSet,                  ///< model to be fitted
     58    pmSourceFitMode mode,               ///< define parameters to be fitted
     59    psImageMaskType maskVal             ///< Vale to mask
    6060
    6161);
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/objects/pmSourcePlots.c

    r19849 r23594  
    139139}
    140140
    141 pmSourcePlotLayout *pmSourcePlotLayoutAlloc()
     141pmSourcePlotLayout *pmSourcePlotLayoutAlloc(void)
    142142{
    143143    pmSourcePlotLayout *layout = (pmSourcePlotLayout *)psAlloc(sizeof(pmSourcePlotLayout));
  • branches/cnb_branches/cnb_branch_20090301/psModules/src/objects/pmSourcePlots.h

    r15562 r23594  
    2929// typedef bool (*pmSourcePlotFunction)(pmConfig *config, pmFPAview *view, pmSourcePlotLayout *layout);
    3030
    31 pmSourcePlotLayout *pmSourcePlotLayoutAlloc();
     31pmSourcePlotLayout *pmSourcePlotLayoutAlloc(void);
    3232bool psMemCheckSourcePlotLayout(psPtr ptr);
    3333
  • branches/cnb_branches/cnb_branch_20090301/psastro

  • branches/cnb_branches/cnb_branch_20090301/psastro/src

    • Property svn:ignore
      •  

        old new  
        1616gpcModel
        1717psastroModelFit
         18psastroExtract
  • branches/cnb_branches/cnb_branch_20090301/psastro/src/Makefile.am

    r23352 r23594  
    1010# FORCE: ;
    1111
    12 bin_PROGRAMS = psastro psastroModel psastroModelFit gpcModel
     12bin_PROGRAMS = psastro psastroExtract psastroModel psastroModelFit gpcModel
    1313
    1414psastro_CFLAGS = $(PSASTRO_CFLAGS) $(PPSTATS_CFLAGS) $(PSMODULE_CFLAGS) $(PSLIB_CFLAGS)
    1515psastro_LDFLAGS = $(PSASTRO_LIBS) $(PPSTATS_LIBS) $(PSMODULE_LIBS) $(PSLIB_LIBS)
    1616psastro_LDADD = libpsastro.la
     17
     18psastroExtract_CFLAGS = $(PSASTRO_CFLAGS) $(PSMODULE_CFLAGS) $(PSLIB_CFLAGS)
     19psastroExtract_LDFLAGS = $(PSASTRO_LIBS) $(PSMODULE_LIBS) $(PSLIB_LIBS)
     20psastroExtract_LDADD = libpsastro.la
    1721
    1822psastroModel_CFLAGS = $(PSASTRO_CFLAGS) $(PSMODULE_CFLAGS) $(PSLIB_CFLAGS)
     
    3539        psastroDataSave.c           \
    3640        psastroMetadataStats.c      \
     41        psastroCleanup.c
     42
     43psastroExtract_SOURCES = \
     44        psastroExtract.c                    \
     45        psastroExtractArguments.c           \
     46        psastroExtractParseCamera.c   \
     47        psastroExtractDataLoad.c      \
     48        psastroExtractAnalysis.c      \
     49        psastroExtractStar.c      \
     50        psastroExtractStars.c      \
     51        psastroExtractGhosts.c      \
     52        psastroExtractFindChip.c      \
    3753        psastroCleanup.c
    3854
  • branches/cnb_branches/cnb_branch_20090301/psastro/src/psastro.h

    r23352 r23594  
    5858bool              psastroMaskUpdates (pmConfig *config);
    5959
    60 psPlaneDistort   *psPlaneDistortIdentity ();
    61 bool              psPlaneDistortIsIdentity (psPlaneDistort *distort);
    62 
    63 psArray          *psastroLoadRefstars (pmConfig *config);
     60psArray          *psastroLoadRefstars (pmConfig *config, const char *source);
    6461bool              psastroChipAstrom (pmConfig *config);
    6562bool              psastroOneChip (pmFPA *fpa, pmChip *chip, psArray *refset, psArray *rawset, psMetadata *recipe, psMetadata *updates);
    6663bool              psastroOneChipGrid (pmFPA *fpa, pmChip *chip, psArray *refset, psArray *rawset, psMetadata *recipe, psMetadata *updates);
    6764bool              psastroOneChipFit (pmFPA *fpa, pmChip *chip, psArray *refset, psArray *rawset, psMetadata *recipe, psMetadata *updates);
    68 bool              psastroChooseRefstars (pmConfig *config, psArray *refs);
     65bool              psastroChooseRefstars (pmConfig *config, psArray *refs, const char *source);
    6966bool              psastroRefstarSubset (pmReadout *readout);
    7067pmLumFunc        *psastroLuminosityFunction (psArray *stars, pmLumFunc *rawFunc);
     
    121118bool              psastroDumpCorners (char *filenameU, char *filenameD, pmFPA *fpa);
    122119
     120char             *psastroSetMagLimit (float *minMag, float *maxRho, pmConfig *config, const char *source);
    123121
    124122psArray          *psastroReadGetstarCatalog (psFits *fits);
     
    129127bool              psastroMetadataStats (pmConfig *config);
    130128
    131 bool psastroZeroPoint (pmConfig *config);
    132 bool psastroZeroPointReadout(pmReadout *readout, float zeropt, float exptime);
    133 bool psastroZeroPointFromRecipe (float *zeropt, float *exptime, pmFPA *fpa, psMetadata *recipe);
     129bool              psastroZeroPoint (pmConfig *config);
     130bool              psastroZeroPointReadout(pmReadout *readout, float zeropt, float exptime);
     131bool              psastroZeroPointFromRecipe (float *zeropt, float *exptime, pmFPA *fpa, psMetadata *recipe);
     132
     133// psastroExtract functions
     134bool              psastroExtractAnalysis (pmConfig *config);
     135bool              psastroExtractStars (pmConfig *config);
     136bool              psastroExtractGhosts (pmConfig *config);
     137pmChip           *psastroExtractFindChip (float *xChip, float *yChip, pmFPA *fpa, float xFPA, float yFPA);
     138bool              psastroExtractChipBounds (pmFPA *fpa);
     139
     140psImage          *psastroExtractStar (psImage *input, float x, float y, float dX, float dY);
     141bool              psastroExtractParseCamera (pmConfig *config);
     142bool              psastroExtractDataLoad (pmConfig *config);
     143pmConfig         *psastroExtractArguments (int argc, char **argv);
    134144
    135145///@}
  • branches/cnb_branches/cnb_branch_20090301/psastro/src/psastroAnalysis.c

    r21409 r23594  
    4545
    4646    // load the reference stars overlapping the data stars
    47     psArray *refs = psastroLoadRefstars(config);
     47    psArray *refs = psastroLoadRefstars(config, "PSASTRO.INPUT");
    4848    if (!refs) {
    4949        psError (PSASTRO_ERR_UNKNOWN, false, "failed to load reference data\n");
     
    5656    }
    5757
    58     if (!psastroChooseRefstars (config, refs)) {
     58    if (!psastroChooseRefstars (config, refs, "PSASTRO.INPUT")) {
    5959        psError (PSASTRO_ERR_UNKNOWN, false, "failed to select reference data for chips\n");
    6060        psFree(refs);
    6161        return false;
    6262    }
     63    psFree (refs);  // refs of interest are saved on readout->analysis
    6364
    6465    // check the command-line arguments first
     
    7980        if (!psastroChipAstrom (config)) {
    8081            psError (PSASTRO_ERR_UNKNOWN, false, "failed to perform single chip astrometry\n");
    81             psFree(refs);
    8282            return false;
    8383        }
     
    8686        if (!psastroMosaicAstrom (config)) {
    8787            psError (PSASTRO_ERR_UNKNOWN, false, "failed to perform mosaic camera astrometry\n");
    88             psFree(refs);
    8988            return false;
    9089        }
     
    10099    // psastroStackAstrom (config, refs);
    101100
    102     psFree (refs);
    103101    return true;
    104102}
  • branches/cnb_branches/cnb_branch_20090301/psastro/src/psastroChooseRefstars.c

    r21409 r23594  
    2020}
    2121
    22 bool psastroChooseRefstars (pmConfig *config, psArray *refs) {
     22bool psastroChooseRefstars (pmConfig *config, psArray *refs, const char *source) {
    2323
    2424    bool status;
     
    3535
    3636    // select the input data sources
    37     pmFPAfile *input = psMetadataLookupPtr (NULL, config->files, "PSASTRO.INPUT");
     37    pmFPAfile *input = psMetadataLookupPtr (NULL, config->files, source);
    3838    if (!input) {
    3939        psError(PSASTRO_ERR_CONFIG, true, "Can't find input data!\n");
  • branches/cnb_branches/cnb_branch_20090301/psastro/src/psastroLoadRefstars.c

    r21422 r23594  
    1414# define ELIXIR_MODE 1
    1515
    16 char *psastroSetMagLimit (float *minMag, float *maxRho, pmConfig *config);
    17 
    18 psArray *psastroLoadRefstars (pmConfig *config) {
     16psArray *psastroLoadRefstars (pmConfig *config, const char *source) {
    1917
    2018    int fd;
     
    6967    float minMag;
    7068    float maxRho;
    71     char *photcode = psastroSetMagLimit (&minMag, &maxRho, config);
     69    char *photcode = psastroSetMagLimit (&minMag, &maxRho, config, source);
    7270    PS_ASSERT (photcode, NULL);
    7371
     
    240238  goto escape; }
    241239
    242 char *psastroSetMagLimit (float *minMag, float *maxRho, pmConfig *config) {
     240char *psastroSetMagLimit (float *minMag, float *maxRho, pmConfig *config, const char *source) {
    243241
    244242    bool status;
     
    249247
    250248    // select the input data sources
    251     pmFPAfile *input = psMetadataLookupPtr (NULL, config->files, "PSASTRO.INPUT");
     249    pmFPAfile *input = psMetadataLookupPtr (NULL, config->files, source);
    252250    if (!input) {
    253251        psLogMsg ("psastro", PS_LOG_DETAIL, "no supplied reference header data");
  • branches/cnb_branches/cnb_branch_20090301/psconfig

  • branches/cnb_branches/cnb_branch_20090301/psconfig/psbuild

    r23352 r23594  
    1414$verbose = 0;
    1515$use_svn = 1;
     16$svn_trunk = "";
    1617
    1718$extlibs = "none";
     
    3435    if ($ARGV[0] eq "-extperl") {
    3536        $extperl = $ARGV[1];
     37        shift; shift; next;
     38    }
     39    if ($ARGV[0] eq "-trunk") {
     40        $svn_trunk = $ARGV[1];
    3641        shift; shift; next;
    3742    }
     
    293298        print "\033]0; ** psbuild: $module[$i] ** \007";
    294299
     300        if ($svn_trunk && (!-d $workdir || !-r $workdir || !-x $workdir)) {
     301            # try trunk instead
     302            print STDERR "$module[$i] missing from local path, trying trunk path\n";
     303            $workdir = "$svn_trunk/$module[$i]";
     304        }
     305
    295306        if (!-d $workdir || !-r $workdir || !-x $workdir) {
    296307            print STDERR "WARNING: no directory for component $module[$i], skipping\n";
  • branches/cnb_branches/cnb_branch_20090301/psconfig/psconfig.csh.in

    r18708 r23594  
    410410
    411411if ("$PSCONFIG" == "none") then
    412   alias  psconfigure configure
    413   alias  psautogen autogen.sh
     412  alias  psconfigure ./configure
     413  alias  psautogen ./autogen.sh
    414414  alias  psperlbuild perl Build.PL
    415415else
  • branches/cnb_branches/cnb_branch_20090301/psconfig/tagsets/ipp-2.8.dist

    r23352 r23594  
    3333  YNNYY  Nebulous/nebclient     ipp-2-8          -0
    3434  YNNYY  Nebulous               ipp-2-8          -0
     35  YNNYY  Nebulous-Server        ipp-2-8          -0
    3536  YYYYY  PS-IPP-Metadata-Config ipp-2-8          -0
    3637  YYYYY  PS-IPP-Config          ipp-2-8          -0     
     
    6869  YYYYY  DataStore              ipp-2-8          -0
    6970
     71  YNNNN  extsrc/gpcsw           ipp-2-8          -0
     72
    7073# there are externally required C libraries and perl modules (see INSTALL)
  • branches/cnb_branches/cnb_branch_20090301/psphot

  • branches/cnb_branches/cnb_branch_20090301/psphot/src/psphot.h

    r23352 r23594  
    2323
    2424bool            psphotModelTest (pmConfig *config, const pmFPAview *view, psMetadata *recipe);
    25 bool            psphotInit ();
     25bool            psphotInit (void);
    2626bool            psphotReadout (pmConfig *config, const pmFPAview *view);
    2727bool            psphotReadoutFindPSF(pmConfig *config, const pmFPAview *view, psArray *inSources);
     
    3535
    3636// XXX test functions
    37 psArray        *psphotFakeSources ();
     37psArray        *psphotFakeSources (void);
    3838
    3939// psphotReadout functions
     
    7676
    7777// thread-related:
    78 bool            psphotSetThreads ();
     78bool            psphotSetThreads (void);
    7979bool            psphotChooseCellSizes (int *Cx, int *Cy, pmReadout *readout, int nThreads);
    8080bool            psphotCoordToCell (int *group, int *cell, float x, float y, int Cx, int Cy);
     
    136136bool            psphotPlotMoments (pmConfig *config, pmFPAview *view, psArray *sources);
    137137bool            psphotPlotPSFModel (pmConfig *config, pmFPAview *view, psArray *sources);
    138 bool            psphotFitInit ();
    139 bool            psphotFitSummary ();
     138bool            psphotFitInit (int nThreads);
     139bool            psphotFitSummary (void);
    140140
    141141bool            psphotMergeSources (psArray *oldSources, psArray *newSources);
     
    230230psImage *pmPCMDataSaveImage (pmPCMData *pcm);
    231231
    232 int psphotKapaOpen ();
    233 bool psphotKapaClose ();
     232int psphotKapaOpen (void);
     233bool psphotKapaClose (void);
    234234bool psphotImageBackgroundCellHistogram (psVector *values, float mean, float sigma, int ix, int iy);
    235235bool psphotDiagnosticPlots (const pmConfig *config, const char *name, ...);
  • branches/cnb_branches/cnb_branch_20090301/psphot/src/psphotCleanup.c

    r21341 r23594  
    1818}
    1919
    20 psExit psphotGetExitStatus () {
     20psExit psphotGetExitStatus (void) {
    2121
    2222    psErrorCode err = psErrorCodeLast ();
    2323    switch (err) {
    2424      case PS_ERR_NONE:
    25         return PS_EXIT_SUCCESS;
     25        return PS_EXIT_SUCCESS;
    2626      case PSPHOT_ERR_SYS:
    2727        return PS_EXIT_SYS_ERROR;
  • branches/cnb_branches/cnb_branch_20090301/psphot/src/psphotDetect.h

    r21392 r23594  
    1919bool        psphotMosaicChip(pmConfig *config, const pmFPAview *view, char *outFile, char *inFile);
    2020void        psphotCleanup (pmConfig *config);
    21 psExit      psphotGetExitStatus ();
     21psExit      psphotGetExitStatus (void);
    2222
    2323#endif
  • branches/cnb_branches/cnb_branch_20090301/psphot/src/psphotFitSourcesLinear.c

    r21519 r23594  
    6363        pmSource *source = sources->data[i];
    6464
    65         // turn this bit off and turn it on again if we pass this test
    66         source->mode &= ~PM_SOURCE_MODE_LINEAR_FIT;
     65        // turn this bit off and turn it on again if we pass this test
     66        source->mode &= ~PM_SOURCE_MODE_LINEAR_FIT;
    6767
    6868        // skip non-astronomical objects (very likely defects)
     
    7070        if (source->type == PM_SOURCE_TYPE_SATURATED) continue;
    7171
    72         // do not include CRs in the full ensemble fit
     72        // do not include CRs in the full ensemble fit
    7373        if (source->mode & PM_SOURCE_MODE_CR_LIMIT) continue;
    7474
     
    9494        if (y > AnalysisRegion.y1) continue;
    9595
    96         source->mode |= PM_SOURCE_MODE_LINEAR_FIT;
     96        source->mode |= PM_SOURCE_MODE_LINEAR_FIT;
    9797        psArrayAdd (fitSources, 100, source);
    9898    }
    9999    psLogMsg ("psphot.ensemble", PS_LOG_MINUTIA, "built fitSources: %f sec (%ld objects)\n", psTimerMark ("psphot.linear"), sources->n);
     100
     101    if (fitSources->n == 0) {
     102        return true;
     103    }
    100104
    101105    // vectors to store stats for each object
     
    189193    psLogMsg ("psphot.ensemble", PS_LOG_MINUTIA, "solve matrix: %f sec (%d elements)\n", psTimerMark ("psphot.linear"), sparse->Nelem);
    190194
    191     // XXXX **** philosophical question: 
     195    // XXXX **** philosophical question:
    192196    // we measure bright objects in three passes: 1) linear fit; 2) non-linear fit; 3) linear fit:
    193     // should retain the chisq and errors from the intermediate non-linear fit? 
    194     // the non-linear fit provides better values for the position errors, and for 
     197    // should retain the chisq and errors from the intermediate non-linear fit?
     198    // the non-linear fit provides better values for the position errors, and for
    195199    // extended sources, the shape errors
    196200
     
    218222    for (int i = 0; final && (i < fitSources->n); i++) {
    219223        pmSource *source = fitSources->data[i];
    220         if (source->mode & PM_SOURCE_MODE_NONLINEAR_FIT) continue;
     224        if (source->mode & PM_SOURCE_MODE_NONLINEAR_FIT) continue;
    221225        pmModel *model = pmSourceGetModel (NULL, source);
    222226        pmSourceChisq (model, source->pixels, source->maskObj, source->variance, maskVal);
  • branches/cnb_branches/cnb_branch_20090301/psphot/src/psphotMaskReadout.c

    r23352 r23594  
    1212    psMetadataAddImageMask (recipe, PS_LIST_TAIL, "MASK.SAT", PS_META_REPLACE, "user-defined mask", maskSat);
    1313
    14     psImageMaskType maskBad  = pmConfigMaskGet("BAD", config); // Mask value for bad pixels
     14    psImageMaskType maskBad  = pmConfigMaskGet("LOW", config); // Mask value for low pixels
     15    if (!maskBad) {
     16        // XXX: for backward compatability look up old name
     17        maskBad  = pmConfigMaskGet("BAD", config);
     18    }
    1519    psMetadataAddImageMask (recipe, PS_LIST_TAIL, "MASK.BAD", PS_META_REPLACE, "user-defined mask", maskBad);
    1620
  • branches/cnb_branches/cnb_branch_20090301/psphot/src/psphotReadout.c

    r21366 r23594  
    22
    33// this should be called by every program that links against libpsphot
    4 bool psphotInit () {
     4bool psphotInit (void) {
    55
    66    psphotErrorRegister();              // register our error codes/messages
  • branches/cnb_branches/cnb_branch_20090301/psphot/src/psphotReadoutFindPSF.c

    r21366 r23594  
    1111    if (!recipe) {
    1212        psError(PSPHOT_ERR_CONFIG, false, "missing recipe %s", PSPHOT_RECIPE);
     13        return false;
     14    }
     15
     16    // set the photcode for this image
     17    if (!psphotAddPhotcode(recipe, config, view, "PSPHOT.INPUT")) {
     18        psError(PSPHOT_ERR_CONFIG, false, "trouble defining the photcode");
    1319        return false;
    1420    }
  • branches/cnb_branches/cnb_branch_20090301/psphot/src/psphotReadoutKnownSources.c

    r21366 r23594  
    1111    if (!recipe) {
    1212        psError(PSPHOT_ERR_CONFIG, false, "missing recipe %s", PSPHOT_RECIPE);
     13        return false;
     14    }
     15
     16    // set the photcode for this image
     17    if (!psphotAddPhotcode(recipe, config, view, "PSPHOT.INPUT")) {
     18        psError(PSPHOT_ERR_CONFIG, false, "trouble defining the photcode");
    1319        return false;
    1420    }
  • branches/cnb_branches/cnb_branch_20090301/psphot/src/psphotReadoutMinimal.c

    r21366 r23594  
    1919    if (!recipe) {
    2020        psError(PSPHOT_ERR_CONFIG, false, "missing recipe %s", PSPHOT_RECIPE);
     21        return false;
     22    }
     23
     24    // set the photcode for this image
     25    if (!psphotAddPhotcode(recipe, config, view, "PSPHOT.INPUT")) {
     26        psError(PSPHOT_ERR_CONFIG, false, "trouble defining the photcode");
    2127        return false;
    2228    }
  • branches/cnb_branches/cnb_branch_20090301/psphot/src/psphotStandAlone.h

    r12805 r23594  
    1717bool            psphotMosaicChip(pmConfig *config, const pmFPAview *view, char *outFile, char *inFile);
    1818void            psphotCleanup (pmConfig *config);
    19 psExit          psphotGetExitStatus ();
     19psExit          psphotGetExitStatus (void);
    2020
    2121#endif
  • branches/cnb_branches/cnb_branch_20090301/pswarp/src/pswarp.h

    r23352 r23594  
    7272} pswarpTransformTileArgs;
    7373
    74 pswarpTransformTileArgs *pswarpTransformTileArgsAlloc();
     74pswarpTransformTileArgs *pswarpTransformTileArgsAlloc(void);
    7575bool pswarpTransformTile (pswarpTransformTileArgs *args);
    7676
     
    8787bool pswarpMatchRange (int *minX, int *minY, int *maxX, int *maxY, pmReadout *dest, pmReadout *src);
    8888
    89 pswarpMap *pswarpMapAlloc ();
     89pswarpMap *pswarpMapAlloc (void);
    9090pswarpMapGrid *pswarpMapGridAlloc (int Nx, int Ny);
    9191
     
    111111 * define threads for this program
    112112 */
    113 bool pswarpSetThreads ();
     113bool pswarpSetThreads (void);
    114114
    115115/// Return software version
  • branches/cnb_branches/cnb_branch_20090301/pswarp/src/pswarpMapGrid.c

    r21323 r23594  
    4343    // measure the map for the center of each superpixel
    4444    for (ni = 0, i = xMin; ni < nXpts; i += nXpix, ni++) {
    45         for (nj = 0, j = yMin; nj < nYpts; j += nYpix, nj++) {
    46             pswarpMapSetLocalModel (grid->maps[ni][nj], dest, src, i, j);
    47         }
     45        for (nj = 0, j = yMin; nj < nYpts; j += nYpix, nj++) {
     46            pswarpMapSetLocalModel (grid->maps[ni][nj], dest, src, i, j);
     47        }
    4848    }
    49            
     49
    5050    grid->nXpix = nXpix;
    5151    grid->nYpix = nYpix;
     
    112112
    113113    for (int i = 0; i < grid->nXpts - 1; i++) {
    114         for (int j = 0; j < grid->nYpts - 1; j++) {
    115 
    116             // measure the output coordinates for the next grid position using the current grid map
    117             // compare with the coordinates measured using the next grid map
    118             pswarpMapApply (&xRaw, &yRaw, grid->maps[i][j], grid->maps[i][j]->xo + grid->nXpix, grid->maps[i][j]->yo);
    119             pswarpMapApply (&xRef, &yRef, grid->maps[i+1][j], grid->maps[i][j]->xo + grid->nXpix, grid->maps[i][j]->yo);
    120 
    121             double posError = hypot (xRaw-xRef, yRaw-yRef);
    122             maxError = PS_MAX (maxError, posError);
    123         }
    124     }   
     114        for (int j = 0; j < grid->nYpts - 1; j++) {
     115
     116            // measure the output coordinates for the next grid position using the current grid map
     117            // compare with the coordinates measured using the next grid map
     118            pswarpMapApply (&xRaw, &yRaw, grid->maps[i][j], grid->maps[i][j]->xo + grid->nXpix, grid->maps[i][j]->yo);
     119            pswarpMapApply (&xRef, &yRef, grid->maps[i+1][j], grid->maps[i][j]->xo + grid->nXpix, grid->maps[i][j]->yo);
     120
     121            double posError = hypot (xRaw-xRef, yRaw-yRef);
     122            maxError = PS_MAX (maxError, posError);
     123        }
     124    }
    125125    return maxError;
    126126}
     
    176176    psPlaneTransformApply (FP, fpaDest->fromTPA, TP);
    177177    psPlaneTransformApply (V00, chipDest->fromFPA, FP);
    178    
     178
    179179    /** V(1,0) position */
    180180    offset->x = ix + 1;
     
    186186    psPlaneTransformApply (FP, fpaDest->fromTPA, TP);
    187187    psPlaneTransformApply (V10, chipDest->fromFPA, FP);
    188    
     188
    189189    /** V(0,1) position */
    190190    offset->x = ix;
     
    204204    map->Yy = V01->y - V00->y;
    205205    map->Yo = V00->y - map->Yx*ix - map->Yy*iy;
    206  
     206
    207207    map->xo = ix;
    208208    map->yo = iy;
     
    224224}
    225225
    226 pswarpMap *pswarpMapAlloc () {
     226pswarpMap *pswarpMapAlloc(void) {
    227227
    228228  pswarpMap *map = (pswarpMap *) psAlloc (sizeof(pswarpMap));
     
    238238
    239239    for (int i = 0; i < grid->nXpts; i++) {
    240         for (int j = 0; j < grid->nYpts; j++) {
    241             psFree (grid->maps[i][j]);
    242         }
    243         psFree (grid->maps[i]);
     240        for (int j = 0; j < grid->nYpts; j++) {
     241            psFree (grid->maps[i][j]);
     242        }
     243        psFree (grid->maps[i]);
    244244    }
    245245    psFree (grid->maps);
     
    256256      grid->maps[i] = psAlloc (nYpts*sizeof(void *));
    257257      for (int j = 0; j < nYpts; j++) {
    258           grid->maps[i][j] = pswarpMapAlloc();
     258          grid->maps[i][j] = pswarpMapAlloc();
    259259      }
    260260  }
     
    264264  grid->nXpix = 0;
    265265  grid->nYpix = 0;
    266  
     266
    267267  return grid;
    268268}
  • branches/cnb_branches/cnb_branch_20090301/pswarp/src/pswarpParseCamera.c

    r23352 r23594  
    2424
    2525    // look for the file on the RUN metadata
    26     pmFPAfile *file = pmFPAfileDefineFromRun(&status, config, filerule); // File to return
     26    pmFPAfile *file = pmFPAfileDefineFromRun(&status, bind, config, filerule); // File to return
    2727    if (!status) {
    2828        psError(PSWARP_ERR_CONFIG, false, "Failed to load file definition for %s", filerule);
  • branches/cnb_branches/cnb_branch_20090301/pswarp/src/pswarpSetMaskBits.c

    r21368 r23594  
    3333
    3434    // mask for non-linear flat regions (default to DETECTOR if not defined)
    35     psImageMaskType badMask = pmConfigMaskGet("BAD.WARP", config);
     35    psImageMaskType badMask = pmConfigMaskGet("CONV.BAD", config);
    3636    if (!badMask) {
    3737        badMask = 0x01;
    38         pmConfigMaskSet (config, "BAD.WARP", badMask);
     38        pmConfigMaskSet (config, "CONV.BAD", badMask);
    3939    }
    4040    maskOut |= badMask;
    4141
    4242    // mask for non-linear flat regions (default to DETECTOR if not defined)
    43     psImageMaskType poorMask = pmConfigMaskGet("POOR.WARP", config);
     43    psImageMaskType poorMask = pmConfigMaskGet("CONV.POOR", config);
    4444    if (!poorMask) {
    4545        poorMask = 0x02;
    46         pmConfigMaskSet (config, "POOR.WARP", poorMask);
     46        pmConfigMaskSet (config, "CONV.POOR", poorMask);
    4747    }
    4848    maskOut |= poorMask;
  • branches/cnb_branches/cnb_branch_20090301/pswarp/src/pswarpSetThreads.c

    r21323 r23594  
    2323}
    2424
    25 bool pswarpSetThreads () {
     25bool pswarpSetThreads(void) {
    2626
    2727    psThreadTask *task = NULL;
  • branches/cnb_branches/cnb_branch_20090301/pswarp/src/pswarpTransformReadout.c

    r21529 r23594  
    3737    // output mask bits
    3838    psImageMaskType maskIn   = psMetadataLookupImageMask(&mdok, recipe, "MASK.INPUT");
    39     psImageMaskType maskPoor = pmConfigMaskGet("POOR.WARP", config);
    40     psImageMaskType maskBad  = pmConfigMaskGet("BAD.WARP", config);
     39    psImageMaskType maskPoor = pmConfigMaskGet("CONV.POOR", config);
     40    if (!maskPoor) {
     41        maskPoor = pmConfigMaskGet("POOR.WARP", config);
     42    }
     43    psImageMaskType maskBad  = pmConfigMaskGet("CONV.BAD", config);
     44    if (!maskBad) {
     45        maskBad  = pmConfigMaskGet("BAD.WARP", config);
     46    }
    4147    psAssert(mdok, "MASK.INPUT was not defined");
    4248
  • branches/cnb_branches/cnb_branch_20090301/pswarp/src/pswarpTransformTile.c

    r21368 r23594  
    2424}
    2525
    26 pswarpTransformTileArgs *pswarpTransformTileArgsAlloc()
     26pswarpTransformTileArgs *pswarpTransformTileArgsAlloc(void)
    2727{
    2828    pswarpTransformTileArgs *args = psAlloc(sizeof(pswarpTransformTileArgs));
Note: See TracChangeset for help on using the changeset viewer.