IPP Software Navigation Tools IPP Links Communication Pan-STARRS Links

Ignore:
Timestamp:
Mar 5, 2012, 5:19:48 PM (14 years ago)
Author:
mhuber
Message:

merging latest r33407 trunk changes to meh_branches/ppstack_test

Location:
branches/meh_branches/ppstack_test
Files:
14 edited
1 copied

Legend:

Unmodified
Added
Removed
  • branches/meh_branches/ppstack_test

  • branches/meh_branches/ppstack_test/pstamp/scripts

  • branches/meh_branches/ppstack_test/pstamp/scripts/Makefile.am

    r30469 r33415  
    2929        detect_query_create \
    3030        detect_response_create \
     31        dquery_job_run.pl \
    3132        dquery_finish.pl \
    3233        dqueryparse.pl \
  • branches/meh_branches/ppstack_test/pstamp/scripts/detect_query_read

    r29157 r33415  
    222222    if (($colData{FPA_ID}[$i] eq "Not_Set")&&(($colData{'FILTER'}[$i] ne "Not_Set")&&
    223223                                              ($colData{'MJD-OBS'}[$i] ne "Not_Set"))) {
    224         my $dateobs_begin = mjd_to_dateobs($colData{'MJD-OBS'}[$i]);
    225         my $dateobs_end = mjd_to_dateobs($colData{'MJD-OBS'}[$i] + 1);
     224        my $mjd_obs = int $colData{'MJD-OBS'}[$i];
     225        my $dateobs_begin = mjd_to_dateobs($mjd_obs);
     226        my $dateobs_end = mjd_to_dateobs($mjd_obs + 1);
    226227        my $ra = $colData{'RA1_DEG'}[$i];
    227228        my $dec = $colData{'DEC1_DEG'}[$i];
     
    229230        my $cmd;
    230231        if ($colData{STAGE}[$i] eq 'SSdiff') {
    231             $cmd = "$difftool -listrun -dbname $dbname -filter $filter ";
    232             $cmd .= " -dateobs_begin $dateobs_begin -dateobs_end $dateobs_end ";
    233             $cmd .= " -ra $ra -decl $dec -radius 1.5 -limit 1 -diff_mode 4";
     232            # Assumption: All Stack Stack diffs are for a medium deep field
     233            # go find which one the coordinates are in
     234            # XXX: If we don't find one we'll just get the first SSdiff
     235            # in the filter on the day in question
     236            my $field = find_md_field($ra, $dec, 1.6);
     237            $cmd = "$difftool -listssrun -dbname $dbname -filter $filter ";
     238            $cmd .= " -mjd_obs_begin $mjd_obs -mjd_obs_end " . (1 + $mjd_obs);
     239            $cmd .= " -limit 1";
     240            $cmd .= " -tess_id $field%" if $field;
    234241        }
    235242        elsif ($colData{STAGE}[$i] eq 'WSdiff') {
     
    366373
    367374
     375# Given an RA and  DEC return the MD field that contains it if any.
     376# This is much faster than actuallly examining the tessellation
     377# using dvoImagesAtCoords
     378
     379sub find_md_field {
     380    my $ra_deg = shift;
     381    my $dec_deg = shift;
     382    my $radius_deg = shift;
     383
     384    my @MD     = qw(MD01  MD02    MD03     MD04      MD05    MD06      MD07    MD08    MD09     MD10);
     385    my @MD_RA  = (35.875, 53.10, 130.592, 150.000, 161.917, 185.000, 213.454, 242.787, 333.98, 352.312);
     386    my @MD_DEC = (-4.25,  -27.8,   44.317,   2.20,   58.083,  47.117,  53.243, 54.95,    0.283, -0.433);
     387    my $PS_DEG_RAD = 0.017453292519943;
     388
     389    my $ra     = $ra_deg * $PS_DEG_RAD;
     390    my $dec    = $dec_deg * $PS_DEG_RAD;
     391    my $radius = $radius_deg * $PS_DEG_RAD;
     392
     393    for (my $i = 0; $i < scalar @MD; $i++) {
     394       
     395        my $dist = acos((cos($PS_DEG_RAD * $MD_DEC[$i]) * cos($dec) * cos($PS_DEG_RAD * $MD_RA[$i] - $ra)) +(sin($PS_DEG_RAD * $MD_DEC[$i]) * sin($dec)));
     396
     397        if ($dist < $radius) {
     398            return $MD[$i];
     399        }
     400    }
     401    print STDERR "failed to find MD field containing $ra_deg $dec_deg\n";
     402
     403    return undef;
     404}
     405
     406
    368407__END__
  • branches/meh_branches/ppstack_test/pstamp/scripts/detectability_respond.pl

    r29616 r33415  
    2020use PS::IPP::PStamp::RequestFile qw( :standard );
    2121use PS::IPP::PStamp::Job qw( :standard );
    22 use PS::IPP::Config qw($PS_EXIT_SUCCESS
    23                        $PS_EXIT_UNKNOWN_ERROR
    24                        $PS_EXIT_SYS_ERROR
    25                        $PS_EXIT_CONFIG_ERROR
    26                        $PS_EXIT_PROG_ERROR
    27                        $PS_EXIT_DATA_ERROR
    28                        $PS_EXIT_TIMEOUT_ERROR
    29                        metadataLookupStr
    30                        metadataLookupBool
    31                        caturi
    32                        );
     22use PS::IPP::Config qw( :standard );
     23use PS::IPP::Metadata::List qw( parse_md_list );
     24
    3325use Astro::FITS::CFITSIO qw( :constants );
    3426Astro::FITS::CFITSIO::PerlyUnpacking(1);
     
    4133my $EXTVER = 1.0;
    4234my $EXTNAME = 'MOPS_DETECTABILITY_RESPONSE';
    43 my ($req_id,$req_name,$product,$need_magic,$missing_tools,$project);
     35my ($req_id,$job_id,$req_name,$product,$need_magic,$missing_tools,$project);
    4436my ($request_file,$output,$workdir,$dbname,$dbserver,$verbose,$save_temps,$ignore_wisdom);
    4537GetOptions(
     
    4739    'output=s'        =>      \$output,
    4840    'workdir=s'       =>      \$workdir,
     41    'job_id=s'        =>      \$job_id,
    4942    'dbname=s'        =>      \$dbname,
    5043    'dbserver=s'      =>      \$dbserver,
     
    7467
    7568my $ipprc = PS::IPP::Config->new();
     69my $mdcParser = PS::IPP::Metadata::Config->new; # Parser for metadata config files
     70
    7671
    7772if (!$dbserver) {
     
    108103} # End reading wisdom.
    109104else {
    110 #
    111 # Parse input request file using detect_query_read (as it's already written).
    112 #
     105    #
     106    # Parse input request file using detect_query_read (as it's already written).
     107    #
    113108    my $dqr_command = "$detect_query_read --dbname $imagedb --input $request_file";
    114109    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     
    123118    {
    124119        my @column_names = ();
     120        # split output into lines skip until the line which lists the column names is found
     121        # Parse subsequent lines
    125122        foreach my $entry (split /\n/, (join "", @$stdout_buf)) {
    126123            if ($entry =~ /^#/) {
     
    128125                shift(@column_names);  # Dump the hash sign.
    129126            }
    130             else {
     127            elsif (scalar @column_names) {
    131128                # ROWNUM RA1_DEG DEC1_DEG RA2_DEG DEC2_DEG MAG QUERY_ID FPA_ID MJD-OBS FILTER OBSCODE STAGE
    132129                my %row_data;
    133130                @row_data{@column_names} = (split /\s+/, $entry);
    134131                for (my $i = 0; $i <= $#column_names; $i++) {
    135                 push @{ $query{$row_data{"FPA_ID"}}{$column_names[$i]} }, $row_data{$column_names[$i]};
    136                 $Nrows = scalar(keys(%query));
    137 #               print "$row_data{'FPA_ID'} $Nrows $i $column_names[$i] $row_data{$column_names[$i]}\n";
    138             }
    139             }
    140         }
    141     }
    142 #
    143 # Identify target images.  This should properly collate targets on a single imfile.
    144 #
     132                    push @{ $query{$row_data{"FPA_ID"}}{$column_names[$i]} }, $row_data{$column_names[$i]};
     133                    $Nrows = scalar(keys(%query));
     134                    # print "$row_data{'FPA_ID'} $Nrows $i $column_names[$i] $row_data{$column_names[$i]}\n";
     135                }
     136            }
     137        }
     138    }
     139    #
     140    # Identify target images.  This should properly collate targets on a single imfile.
     141    #
    145142    foreach my $fpa_id (keys %query) {
    146143        my %temp_hash;
     
    212209        }
    213210        elsif ($fpa_id eq 'Not_Set') {
     211            # no matching file was found skip
    214212            next;
    215213        }
     
    227225            $need_magic = 0;
    228226        }
    229         my $mjd_min = $mjd;
     227        my $mjd_min = int $mjd;
    230228        my $mjd_max = $mjd + 1;
    231229       
     230        my $req_filter;
     231        if ($filter ne 'Not_Set') {
     232            $req_filter = $filter . '%';
     233        }
    232234       
    233235        # Call the PStamp code to find the images that contain the target on the given MJD in the specified filter.
     
    237239                                          $fpa_id,undef,undef,
    238240                                          $option_mask,$need_magic,
    239                                           # $ra,$dec,
    240                                           $mjd_min,$mjd_max,$filter . ".00000",undef,$verbose); 
     241                                          $mjd_min,$mjd_max,$req_filter,undef,$verbose); 
    241242       
    242243        foreach my $this_image_ref (@{ $pstamp_images_ref }) {
    243             foreach my $key (sort (keys %{ $this_image_ref } )) {
    244                 my $value = ${ $this_image_ref }{$key};
    245                 if ($key eq 'row_index') {
    246                     $value = join ' ', @{ $this_image_ref->{$key} };
    247                 }
    248 
    249 #               print "$this_image_ref $key $value\n";
    250                 foreach my $valid_index (@{ $this_image_ref->{row_index} }) {
    251                     $query{$fpa_id}{IMAGE}[$valid_index] = $this_image_ref->{image};
    252                     $query{$fpa_id}{MASK}[$valid_index] = $this_image_ref->{mask};
    253                     $query{$fpa_id}{WEIGHT}[$valid_index] = $this_image_ref->{weight};
    254                     $query{$fpa_id}{PSF}[$valid_index] = $this_image_ref->{psf};
    255                     $query{$fpa_id}{STAGE_ID}[$valid_index] = $this_image_ref->{stage_id};
    256                     $query{$fpa_id}{IMAGE_DB}[$valid_index] = $this_image_ref->{imagedb};
    257                     $query{$fpa_id}{NEED_MAGIC}[$valid_index] = $need_magic;
    258                     $query{$fpa_id}{BAD_COMPONENT}[$valid_index] = 0;
    259                    
    260                     if (exists($this_image_ref->{astrom})) {
    261                         $query{$fpa_id}{CATALOG}[$valid_index] = $this_image_ref->{astrom};
    262                     }
    263                     else {
    264                         $query{$fpa_id}{CATALOG}[$valid_index] = $this_image_ref->{cmf};
    265                     }
    266                     if (exists($this_image_ref->{class_id})) {
    267                         $query{$fpa_id}{COMPONENT_ID}[$valid_index] = $this_image_ref->{class_id};
    268                         $query{$fpa_id}{CLASS_ID}[$valid_index] = $this_image_ref->{class_id};
    269                        
    270                     }
    271                     else {
    272                         $query{$fpa_id}{COMPONENT_ID}[$valid_index] = $this_image_ref->{skycell_id};
    273                         $query{$fpa_id}{CLASS_ID}[$valid_index] = 'fpa';
    274                     }
    275                    
    276                     $query{$fpa_id}{STATE}[$valid_index] = $this_image_ref->{state};
    277                     if (exists($this_image_ref->{data_state})) {
    278                         $query{$fpa_id}{DATA_STATE}[$valid_index] = $this_image_ref->{data_state};
    279                     }
    280                     else {
    281                         $query{$fpa_id}{DATA_STATE}[$valid_index] = $this_image_ref->{state};
    282                     }
    283                     $query{$fpa_id}{FAULT}[$valid_index] = 0;
     244
     245            if (0) {
     246                foreach my $key (sort (keys %{ $this_image_ref } )) {
     247                    my $value = ${ $this_image_ref }{$key};
     248                    if ($key eq 'row_index') {
     249                        $value = join ' ', @{ $this_image_ref->{$key} };
     250                    }
     251                    print "$this_image_ref $key $value\n";
     252                }
     253            }
     254
     255
     256            foreach my $valid_index (@{ $this_image_ref->{row_index} }) {
     257                $query{$fpa_id}{IMAGE}[$valid_index] = $this_image_ref->{image};
     258                $query{$fpa_id}{MASK}[$valid_index] = $this_image_ref->{mask};
     259                $query{$fpa_id}{WEIGHT}[$valid_index] = $this_image_ref->{weight};
     260                $query{$fpa_id}{PSF}[$valid_index] = $this_image_ref->{psf};
     261                $query{$fpa_id}{STAGE_ID}[$valid_index] = $this_image_ref->{stage_id};
     262                $query{$fpa_id}{IMAGE_DB}[$valid_index] = $this_image_ref->{imagedb};
     263                $query{$fpa_id}{NEED_MAGIC}[$valid_index] = $need_magic;
     264                $query{$fpa_id}{BAD_COMPONENT}[$valid_index] = 0;
     265               
     266                if (exists($this_image_ref->{astrom})) {
     267                    $query{$fpa_id}{CATALOG}[$valid_index] = $this_image_ref->{astrom};
     268                }
     269                else {
     270                    $query{$fpa_id}{CATALOG}[$valid_index] = $this_image_ref->{cmf};
     271                }
     272                if (exists($this_image_ref->{class_id})) {
     273                    $query{$fpa_id}{COMPONENT_ID}[$valid_index] = $this_image_ref->{class_id};
     274                    $query{$fpa_id}{CLASS_ID}[$valid_index] = $this_image_ref->{class_id};
     275                   
     276                }
     277                else {
     278                    $query{$fpa_id}{COMPONENT_ID}[$valid_index] = $this_image_ref->{skycell_id};
     279                    $query{$fpa_id}{CLASS_ID}[$valid_index] = 'fpa';
     280                }
     281               
     282                $query{$fpa_id}{STATE}[$valid_index] = $this_image_ref->{state};
     283                if (exists($this_image_ref->{data_state})) {
     284                    $query{$fpa_id}{DATA_STATE}[$valid_index] = $this_image_ref->{data_state};
     285                }
     286                else {
     287                    $query{$fpa_id}{DATA_STATE}[$valid_index] = $this_image_ref->{state};
     288                }
     289                $query{$fpa_id}{FAULT}[$valid_index] = 0;
    284290                    $query{$fpa_id}{MAGICKED}[$valid_index] = $this_image_ref->{magicked};
    285                     if ($stage eq 'chip') {
    286                         $query{$fpa_id}{BURNTOOL_STATE}[$valid_index] = $this_image_ref->{burntool_state};
    287                     }
    288                    
    289                     # Determine if the data exists.
    290                     if (($query{$fpa_id}{STATE}[$valid_index] eq 'goto_purged') or
    291                         ($query{$fpa_id}{DATA_STATE}[$valid_index] eq 'purged') or
    292                         ($query{$fpa_id}{STATE}[$valid_index] eq 'drop') or
    293                         ($query{$fpa_id}{STATE}[$valid_index] eq 'error_cleaned') or
    294                         ($query{$fpa_id}{STATE}[$valid_index] eq 'goto_scrubbed') or
    295                         ($query{$fpa_id}{DATA_STATE}[$valid_index] eq 'scrubbed')) {
    296                        
    297                         # image is gone and it's not coming back
    298                         $query{$fpa_id}{FAULT}[$valid_index] = $PSTAMP_GONE;
    299                     }
    300                     elsif ($need_magic and ($query{$fpa_id}{MAGICKED}[$valid_index] = 0)) {
    301                         $query{$fpa_id}{FAULT}[$valid_index] = $PSTAMP_NOT_DESTREAKED;
    302                     }
    303                     elsif (($query{$fpa_id}{DATA_STATE}[$valid_index] ne 'full')) {                   
    304                         $query{$fpa_id}{FAULT}[$valid_index] = $PSTAMP_NOT_AVAILABLE;
    305                        
    306                         # updating stacks isn't implemented
    307                         if (($stage eq 'stack')) {
    308                             $query{$fpa_id}{FAULT}[$valid_index] = $PSTAMP_NOT_IMPLEMENTED;
    309                         }
    310                         # updating old burntool data isn't implemented
    311                         elsif ($stage eq 'chip') {
    312                             if ($query{$fpa_id}{BURNTOOL_STATE}[$valid_index] and
    313                                 (abs($query{$fpa_id}{BURNTOOL_STATE}[$valid_index]) < 14)) {
    314                                 $query{$fpa_id}{FAULT}[$valid_index] = $PSTAMP_NOT_IMPLEMENTED;
     291                if ($stage eq 'chip') {
     292                    $query{$fpa_id}{BURNTOOL_STATE}[$valid_index] = $this_image_ref->{burntool_state};
     293                }
     294               
     295                # Determine if the data exists.
     296                if (($query{$fpa_id}{STATE}[$valid_index] eq 'goto_purged') or
     297                    ($query{$fpa_id}{DATA_STATE}[$valid_index] eq 'purged') or
     298                    ($query{$fpa_id}{STATE}[$valid_index] eq 'drop') or
     299                    ($query{$fpa_id}{STATE}[$valid_index] eq 'error_cleaned') or
     300                    ($query{$fpa_id}{STATE}[$valid_index] eq 'goto_scrubbed') or
     301                    ($query{$fpa_id}{DATA_STATE}[$valid_index] eq 'scrubbed')) {
     302                   
     303                    # image is gone and it's not coming back
     304                    $query{$fpa_id}{FAULT}[$valid_index] = $PSTAMP_GONE;
     305                }
     306                elsif ($need_magic and ($query{$fpa_id}{MAGICKED}[$valid_index] eq 0)) {
     307                    $query{$fpa_id}{FAULT}[$valid_index] = $PSTAMP_NOT_DESTREAKED;
     308                }
     309                elsif (($query{$fpa_id}{DATA_STATE}[$valid_index] ne 'full')) {               
     310                    $query{$fpa_id}{FAULT}[$valid_index] = $PSTAMP_NOT_AVAILABLE;
     311                   
     312                    # updating stacks isn't implemented
     313                    if (($stage eq 'stack')) {
     314                        $query{$fpa_id}{FAULT}[$valid_index] = $PSTAMP_NOT_IMPLEMENTED;
     315                    }
     316                    # updating old burntool data isn't implemented
     317                    elsif ($stage eq 'chip') {
     318                        if ($query{$fpa_id}{BURNTOOL_STATE}[$valid_index] and
     319                            (abs($query{$fpa_id}{BURNTOOL_STATE}[$valid_index]) < 14)) {
     320                            $query{$fpa_id}{FAULT}[$valid_index] = $PSTAMP_NOT_IMPLEMENTED;
    315321                            }
    316                         }
    317                     } # End determining error faults.
    318                 }
    319             }
    320         }
     322                    }
     323                } # End determining error faults.
     324            }
     325        }
    321326    }
    322327} # End calculating wisdom
     
    324329my %processing_request;
    325330
     331if ($job_id) {
     332    $wisdom_file = "$wisdom_file.$job_id";
     333}
    326334open(WISDOM,">$wisdom_file") or my_die("failed to open wisdom file $wisdom_file");
    327335foreach my $fpa_id (keys %query) {
    328336    for (my $i = 0; $i <= $#{ $query{$fpa_id}{ROWNUM} }; $i++) {
    329         print WISDOM "$fpa_id\t";
    330         foreach my $key (keys %{ $query{$fpa_id} }) {
    331             print WISDOM "$key $query{$fpa_id}{$key}[$i]\t";
    332         }
    333         print WISDOM "\n";
    334         if ($query{$fpa_id}{BAD_COMPONENT}[$i] == 0) {
    335             @{ $update_request{$query{$fpa_id}{IMAGE}[$i]}{$query{$fpa_id}{FAULT}[$i]} } =
    336                 ($query{$fpa_id}{STATE}[$i],$query{$fpa_id}{STAGE}[$i],$query{$fpa_id}{STAGE_ID}[$i],
    337                  $query{$fpa_id}{COMPONENT_ID}[$i],$query{$fpa_id}{NEED_MAGIC}[$i],$query{$fpa_id}{IMAGE_DB}[$i]);
    338             push @{ $processing_request{$fpa_id}{$query{$fpa_id}{IMAGE}[$i]} }, $i;
    339         }
     337        print WISDOM "$fpa_id\t";
     338        foreach my $key (keys %{ $query{$fpa_id} }) {
     339            print WISDOM "$key $query{$fpa_id}{$key}[$i]\t";
     340        }
     341        print WISDOM "\n";
     342        my $data_state = $query{$fpa_id}{DATA_STATE}[$i];
     343        if ($query{$fpa_id}{BAD_COMPONENT}[$i] == 0) {
     344            if ($data_state ne 'full') {
     345               
     346                @{ $update_request{$query{$fpa_id}{IMAGE}[$i]}{$query{$fpa_id}{FAULT}[$i]} } =
     347                    ($query{$fpa_id}{STATE}[$i],$query{$fpa_id}{STAGE}[$i],$query{$fpa_id}{STAGE_ID}[$i],
     348                     $query{$fpa_id}{COMPONENT_ID}[$i],$query{$fpa_id}{NEED_MAGIC}[$i],$query{$fpa_id}{IMAGE_DB}[$i]);
     349            }
     350            push @{ $processing_request{$fpa_id}{$query{$fpa_id}{IMAGE}[$i]} }, $i;
     351        }
    340352    }
    341353}
    342354close(WISDOM);
    343355
    344 # If there is anything that needs to be updated, create the update request list, and then exit the program.
    345 my $exit_code = 0;
    346 my $update_request_file = "${workdir}/update_request.dat";
    347 open(UPDATE_REQUEST,">$update_request_file") or my_die("failed to open update request_file $update_request_file");
    348 foreach my $images (keys %update_request) {
    349     foreach my $fault (keys %{ $update_request{$images} }) {
    350         if ($fault == 25) {
    351             $exit_code = 25;
    352         }
    353         elsif ($fault != 0) {
    354             $exit_code = 21;
    355         }
    356         my $update_request = join ' ', @{ $update_request{$images}{$fault} };
    357         print UPDATE_REQUEST "$update_request\n";
    358     }
    359 }
    360 close(UPDATE_REQUEST);
    361 if ($exit_code != 0) {
    362     exit($exit_code);
     356if (! defined $job_id) {
     357    # If there is anything that needs to be updated, create the update request list, and then exit the program.
     358    my $exit_code = 0;
     359    my $update_request_file = "${workdir}/update_request.dat";
     360    open(UPDATE_REQUEST,">$update_request_file") or my_die("failed to open update request_file $update_request_file");
     361    foreach my $images (keys %update_request) {
     362        foreach my $fault (keys %{ $update_request{$images} }) {
     363            if ($fault == 25) {
     364                $exit_code = 25;
     365            }
     366            elsif ($fault != 0) {
     367                $exit_code = 21;
     368            }
     369            my $update_request = join ' ', @{ $update_request{$images}{$fault} };
     370            print UPDATE_REQUEST "$update_request\n";
     371        }
     372    }
     373    close(UPDATE_REQUEST);
     374    if ($exit_code != 0) {
     375        exit($exit_code);
     376    }
    363377}
    364378
     
    388402        my $weight= $query{$fpa_id}{WEIGHT}[$index];
    389403        my $stage = $query{$fpa_id}{STAGE}[$index];
    390         # if there's a fault, then we can't process this image.
    391         if (($fault != 0)||($query{$fpa_id}{BAD_COMPONENT}[$index] == 1)) {
    392             $query{$fpa_id}{PROC_ERROR}[$index] = 23;
    393            
    394             $query{$fpa_id}{NPIX}[$index] = 0;
    395             $query{$fpa_id}{QFACTOR}[$index] = 0.0;
    396             $query{$fpa_id}{FLUX}[$index] = 0.0;
    397             $query{$fpa_id}{FLUX_SIG}[$index] = 0.0;
     404        my $stage_id = $query{$fpa_id}{STAGE_ID}[$index];
     405        my $component = $query{$fpa_id}{COMPONENT_ID}[$index];
     406        # print "Input is from $stage $stage_id $component\n";
     407
     408        # if there's a fault or quality problem, then we can't process this image.
     409        # if (($fault != 0)||($query{$fpa_id}{BAD_COMPONENT}[$index] == 1)) {
     410        if ($fault = check_component($stage, $stage_id, $component, $imagedb)) {
     411            foreach my $i (@{ $processing_request{$fpa_id}{$image} }) {
     412                $query{$fpa_id}{PROC_ERROR}[$i] = $fault;
     413               
     414                $query{$fpa_id}{NPIX}[$i] = 0;
     415                $query{$fpa_id}{QFACTOR}[$i] = 0.0;
     416                $query{$fpa_id}{FLUX}[$i] = 0.0;
     417                $query{$fpa_id}{FLUX_SIG}[$i] = 0.0;
     418            }
    398419
    399420            next;
     
    695716            $inHeader->{FPA_ID}->{value} = $fpa_id;
    696717        }
     718
     719        my @keysa = keys %{$query{$fpa_id}};
     720
     721        print "$fpa_id: @keysa\n";
    697722       
    698723        push @{$colData{'ROWNUM'}}, @{ $query{$fpa_id}{ROWNUM} };
     
    710735    $status = 0;
    711736#    print "$output\n";
     737    if (-e $output) {
     738        unlink $output or die "failed to unlink existing response file $output\n";
     739    }
    712740    my $outFits = Astro::FITS::CFITSIO::create_file( $output, $status );
    713741    check_fitsio( $status );
     
    779807}
    780808
     809sub check_component {
     810    my ($stage, $stage_id, $component, $imagedb) = @_;
     811
     812    print "Checking status of component $stage $stage_id $component\n";
     813
     814    my $command;
     815    if ($stage eq 'diff') {
     816        $command = "difftool -diffskyfile -diff_id $stage_id -skycell_id $component";
     817    } elsif ($stage eq 'stack') {
     818        $command = "stacktool -sumskyfile -stack_id $stage_id";
     819    } elsif ($stage eq 'warp') {
     820        $command = "warptool -warped -warp_id $stage_id -skycell_id $component";
     821    } elsif ($stage eq 'chip') {
     822        $command = "chiptool -processedimfile -chip_id $stage_id -class_id $component";
     823    } else {
     824        die("check_component not implemented for stage $stage yet");
     825    }
     826
     827    $command .= " -dbname $imagedb";
     828
     829    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     830        run(command => $command, verbose => $verbose);
     831    unless ($success) {
     832        my $rc = $error_code >> 8;
     833        carp "$command failed $error_code $rc";
     834        exit $PS_EXIT_UNKNOWN_ERROR;
     835    }
     836    my $output = join "", @$stdout_buf;
     837    my $metadata = $mdcParser->parse($output);
     838    my $results = parse_md_list($metadata);
     839    if (scalar @$results != 1) {
     840        carp "$command returned too many components: " . scalar @$results;
     841        exit $PS_EXIT_UNKNOWN_ERROR;
     842    }
     843    my $it = $results->[0];
     844
     845    if ($stage eq 'stack') {
     846        $it->{data_state} = $it->{state};
     847    }
     848
     849    my $return_status = 0;
     850    if ($it->{quality}) {
     851        print "  Bad quality: $it->{quality}\n";
     852        $return_status = $PSTAMP_GONE;
     853    } elsif ($it->{fault}) {
     854        print "  Faulted: $it->{fault}\n";
     855        $return_status = $PSTAMP_GONE;
     856    } elsif ($it->{data_state} ne 'full') {
     857        # XXX does this work for stack?
     858        carp "  Faulted: $it->{data_state}\n";
     859        $return_status = $PSTAMP_GONE;
     860    } else {
     861        print "  Component ok.\n";
     862    }
     863
     864    return $return_status;
     865}
     866
    781867sub my_die {
    782868    my $message = shift;
  • branches/meh_branches/ppstack_test/pstamp/scripts/dquery_finish.pl

    r27874 r33415  
    1313use File::Temp qw( tempfile );
    1414use File::Copy;
     15use Astro::FITS::CFITSIO qw( :constants );
     16Astro::FITS::CFITSIO::PerlyUnpacking(1);
    1517
    1618use PS::IPP::Metadata::Config;
     
    6668if ($product eq "NULL") {
    6769    # parsing failed just with fault = 0 (this leaves previously set fault in place
    68     stop_request($req_id, 0, $verbose);
     70    update_request($req_id, 0, $verbose);
    6971    exit 0;
    7072}
    71 if (0) {
    72 my $prod_dir = "$outputDataStoreRoot/$product";
    73 if (! -e $prod_dir ) {
    74     # something must have gone wrong at the parse stage
    75     stop_request($req_id, $PS_EXIT_SYS_ERROR, $verbose);
    76     die "product directory does not exist $prod_dir";
    77 }
    78 my $outdir = "$prod_dir/$req_name";
    79 }
     73
    8074if (! -e $outdir ) {
    8175    # something must have gone wrong at the parse stage
    8276    print STDERR "output fileset directory $outdir does not exist\n" if $verbose;
    8377    if (! mkdir $outdir ) {
    84         stop_request($req_id, $PS_EXIT_SYS_ERROR, $verbose);
     78        update_request($req_id, $PS_EXIT_SYS_ERROR, $verbose);
    8579        die "cannot create output directory $outdir";
    8680    }
    8781} elsif (! -d $outdir) {
    88     stop_request($req_id, $PS_EXIT_SYS_ERROR, $verbose);
     82    update_request($req_id, $PS_EXIT_SYS_ERROR, $verbose);
    8983    die "output fileset directory $outdir exists but is not a directory";
    9084}
     
    9791{
    9892    my $command = "$pstamptool -listjob -req_id $req_id";
     93    $command .= " -jobType detect_query";   # temporary
    9994    $command .= " -dbname $dbname" if $dbname;
    10095    $command .= " -dbserver $dbserver" if $dbserver;
     
    117112}
    118113
    119 # XXX: have the jobs produce the reglist as with postage stamp requests
    120 my ($REGLIST, $reg_list) = tempfile("$outdir/reqlist.XXXX", UNLINK => !$save_temps);
    121 
     114my ($REGLIST, $reg_list) = tempfile("$outdir/reglist.XXXX", UNLINK => !$save_temps);
     115my $response_file = "response.$req_id.fits";
     116my $response_path = "$outdir/$response_file";
     117
     118print $REGLIST "$response_file|||table|\n";
     119
     120my @columns = qw(ROWNUM PROC_ERROR NPIX QFACTOR FLUX FLUX_SIG FPA_ID STAGE STAGE_ID COMPONENT CMFFILE);
     121my %colData;
     122foreach my $col (@columns) {
     123    $colData{$col} = [];
     124}
     125   
     126my $i = 0;
    122127foreach my $job (@jobs) {
    123128    my $job_id = $job->{job_id};
    124     my $response_file = "response${job_id}.fits";
    125     my $response_path = "$outdir/$response_file";
    126 
    127     if (-e $response_path) {
    128         # the job generated a response file put it into the Data Store
    129         print $REGLIST "$response_file|||table|\n";
    130 
    131         # do the same if we have an error file.  Should the parse data be uploaded as well?
    132         my $err_file = "parse_error.txt";
    133         if (-e "$outdir/$err_file") {
    134             print $REGLIST "$err_file|||text|\n";
    135         }
    136     } else  {
    137         print STDERR "detect_query response file for job $job_id not found\n" if $verbose;
    138         $request_fault = $PS_EXIT_UNKNOWN_ERROR;
    139     }
     129
     130    my $outputBase = $job->{outputBase};
     131    my $results = "${outputBase}results.txt";
     132
     133    read_results($results, \%colData);
     134
     135    my $cmf = $colData{CMFFILE}->[$i];
     136    print $REGLIST "$cmf|||table|\n";
     137
     138    $i++;
    140139}
    141140close $REGLIST;
     141
     142write_response_file($response_path, $req_name, \%colData);
    142143
    143144if (-s $reg_list) {
     
    157158}
    158159
    159 stop_request($req_id, $request_fault, $verbose);
     160update_request($req_id, $request_fault, $verbose);
    160161
    161162exit 0;
    162163
    163 sub stop_request {
     164sub read_results {
     165    my $results_file = shift;
     166    my $results = shift;
     167
     168    open IN, "<$results_file" or my_die("failed to open $results_file", $PS_EXIT_UNKNOWN_ERROR);
     169
     170    foreach my $line (<IN>) {
     171        # skip header
     172        next if $line =~ /ROWNUM/;
     173        chomp $line;
     174        my @words = split " ", $line;
     175        my ($rownum, $proc_error, $npix, $qfactor, $flux, $flux_sig, $fpa_id, $stage, $stage_id, $component, $cmf) = @words;
     176        push @{$results->{ROWNUM}}, $rownum;
     177        push @{$results->{PROC_ERROR}}, $proc_error;
     178        push @{$results->{NPIX}}, $npix;
     179        push @{$results->{QFACTOR}}, $qfactor;
     180        push @{$results->{FLUX}}, $flux;
     181        push @{$results->{FLUX_SIG}}, $flux_sig;
     182        push @{$results->{FPA_ID}}, $fpa_id;
     183        push @{$results->{STAGE}}, $stage;
     184        push @{$results->{STAGE_ID}}, $stage_id;
     185        push @{$results->{COMPONENT}}, $component;
     186        push @{$results->{CMFFILE}}, $cmf;
     187    }
     188    # XXX: make sure that the size of each of these arrays is the same
     189}
     190
     191sub write_response_file {
     192    my $output = shift;
     193    my $query_id = shift;
     194    my $results = shift;
     195
     196    my $columns;
     197    my $headers;
     198
     199    my $EXTVER_IS_1 = 0 ; # (scalar(keys(%query)) == 1);
     200#    print "EXTVER: $EXTVER_IS_1\n";
     201    my ($FPA_ID,$MJD_OBS,$filter,$obscode,$status);
     202    if ($EXTVER_IS_1 == 1) {
     203        # Specification of columns to write
     204        $columns = [
     205            # matching rownum from detectability original request
     206            { name => 'ROWNUM',   type => '20A', writetype => TSTRING },
     207            # any errors that occurred during processing
     208            { name => 'ERROR_CODE',   type => 'V', writetype => TULONG },
     209            # number of pixels used in hypothetical PSF for the query detection
     210            { name => 'DETECT_N', type => 'V',   writetype => TULONG },
     211            # detectibility, indicating the fraction of PSF pixels detetable by IPP
     212            { name => 'DETECT_F', type => 'D',   writetype => TDOUBLE },
     213            # flux of the target source
     214            { name => 'TARGET_FLUX', type => 'D', writetype => TDOUBLE },
     215            # error in the flux of the target source
     216            { name => 'TARGET_FLUX_SIG', type => 'D', writetype => TDOUBLE },
     217            ];
     218       
     219        # Header translation table
     220        $headers = {
     221            'QUERY_ID' => { name => 'QUERY_ID', type => TSTRING,
     222                            comment => 'MOPS Query ID for this batch query' },
     223            'FPA_ID' => { name => 'FPA_ID',   type => TSTRING,
     224                          comment => 'original FPA_ID used at ingest' },
     225#           'MJD-OBS' => { name => 'FPA_ID',   type => TSTRING,
     226#                         comment => 'original FPA_ID used at ingest' },
     227#           'FILTER' => { name => 'FPA_ID',   type => TSTRING,
     228#                         comment => 'original FPA_ID used at ingest' },
     229#           'OBSCODE' => { name => 'FPA_ID',   type => TSTRING,
     230#                         comment => 'original FPA_ID used at ingest' },
     231        };
     232    }
     233    else {
     234        # Specification of columns to write
     235        $columns = [
     236            # matching rownum from detectability original request
     237            { name => 'ROWNUM',   type => '20A', writetype => TSTRING},
     238            # any errors that occurred during processing
     239            { name => 'ERROR_CODE',   type => 'V', writetype => TULONG },
     240            # number of pixels used in hypothetical PSF for the query detection
     241            { name => 'DETECT_N', type => 'V',   writetype => TULONG },
     242            # detectibility, indicating the fraction of PSF pixels detetable by IPP
     243            { name => 'DETECT_F', type => 'D',   writetype => TDOUBLE },
     244            # flux of the target source
     245            { name => 'TARGET_FLUX', type => 'D', writetype => TDOUBLE },
     246            # error in the flux of the target source
     247            { name => 'TARGET_FLUX_SIG', type => 'D', writetype => TDOUBLE },
     248            # The FPA That would be in the header if it were to be there.
     249            { name => 'FPA_ID',   type => '20A', writetype => TSTRING },
     250            ];
     251       
     252        # Header translation table
     253        $headers = {
     254            'QUERY_ID' => { name => 'QUERY_ID', type => TSTRING,
     255                            comment => 'MOPS Query ID for this batch query' },
     256        };
     257    }   
     258
     259    # Parse the list of columns
     260    my @colNames;                   # Names of columns
     261    my @colTypes;                   # Types of columns
     262    my %colData;                    # Data for each column
     263    my @colWriteType;                 # type to use to write
     264    foreach my $colSpec ( @$columns) {
     265        push @colNames, $colSpec->{name};
     266        push @colTypes, $colSpec->{type};
     267        push @colWriteType, $colSpec->{writetype};
     268        $colData{$colSpec->{name}} = [];
     269    }
     270
     271    my $inHeader = { };
     272
     273    # Hack to force the data to match the detect_response_create formats
     274
     275    $inHeader->{QUERY_ID}->{value} = $query_id;
     276    if ($EXTVER_IS_1 == 1) {
     277        my $fpa_id = $results->{FPA_ID}->[0];
     278        $inHeader->{FPA_ID}->{value} = $fpa_id;
     279    }
     280   
     281    # Fill the table columns with the data, making sure the flux is defined
     282
     283    @{$colData{'ROWNUM'}} = @{ $results->{ROWNUM} };
     284    @{$colData{'ERROR_CODE'}} = @{ $results->{PROC_ERROR} };
     285    @{$colData{'DETECT_N'}} = @{ $results->{NPIX} };
     286    @{$colData{'DETECT_F'}} = @{ $results->{QFACTOR} };
     287    @{$colData{'TARGET_FLUX'}} = @{ $results->{FLUX} };
     288    @{$colData{'TARGET_FLUX_SIG'}} = @{ $results->{FLUX_SIG} };
     289    @{$colData{'FPA_ID'}} = @{ $results->{FPA_ID} };
     290
     291    my $numRows = 0;
     292    # Back to detect_response_create:
     293    $status = 0;
     294#    print "$output\n";
     295    if (-e $output) {
     296        unlink $output or die "failed to unlink existing response file $output\n";
     297    }
     298    my $outFits = Astro::FITS::CFITSIO::create_file( $output, $status );
     299    check_fitsio( $status );
     300    $outFits->create_img( 16, 0, undef, $status );
     301    check_fitsio( $status );
     302    my $EXTNAME = 'MOPS_DETECTABILITY_RESPONSE';
     303   
     304    $outFits->create_tbl( BINARY_TBL(), $numRows, scalar @colNames, \@colNames, \@colTypes, undef, $EXTNAME, $status);
     305    check_fitsio( $status );
     306
     307    # TODO: get the extension version number from somewhere common
     308    $outFits->write_key( TINT, 'EXTVER', 2, 'Version of this Extension', $status );
     309    check_fitsio( $status );
     310
     311    # Write the Extension keywords
     312    foreach my $keyword ( keys %$headers ) {
     313        my $value = $inHeader->{$keyword}->{value}; # Header keyword value
     314        unless (defined $value) {
     315            print "Can't find header keyword $keyword\n";
     316            next;
     317        }
     318        $value =~ s/\'//g;
     319        my $name    = $headers->{$keyword}->{name}; # New name
     320        my $type    = $headers->{$keyword}->{type}; # Type
     321        my $comment = $headers->{$keyword}->{comment}; # Comment
     322        $outFits->write_key( $type, $name, $value, $comment, $status );
     323        check_fitsio( $status );
     324    }
     325
     326    for (my $i = 0; $i < scalar @colNames; $i++) {
     327        my $colName = $colNames[$i];# Column name
     328        my $writeType = $colWriteType[$i];
     329        my $numRows = scalar(@{$colData{$colName}});
     330        unless(defined($writeType)) {
     331            print "write type undefined for $colName\n";
     332        }
     333        unless(defined($numRows)) {
     334            print "num Rows undefined for $colName\n";
     335        }
     336        unless(defined($status)) {
     337            print "status undefined for $colName\n";
     338        }
     339        unless(defined($colData{$colName})) {
     340            print "col data undefined for $colName\n";
     341        }
     342        unless(defined($colName)) {
     343            print "column name undefined for $i\n";
     344        }
     345        print STDERR "$writeType $i $numRows $colName $status @{ $colData{$colName} }\n";
     346        $outFits->write_col( $writeType, $i + 1, 1, 1, $numRows, $colData{$colName}, $status );
     347        print STDERR "$writeType $i $numRows $colName $status\n";
     348        check_fitsio( $status );
     349    }
     350    $outFits->close_file( $status );
     351    return($status);
     352}
     353
     354# From Astro::FITS::CFITSIO demo
     355sub check_fitsio
     356{
     357    my $status = shift;         # Status of FITSIO calls
     358
     359    if ($status != 0) {
     360        my $msg;                # Message to output
     361        Astro::FITS::CFITSIO::fits_get_errstatus( $status , $msg );
     362        carp("CFITSIO error: $status => $msg");
     363        die "CFITSIO error: $msg\n";
     364    }
     365}
     366sub update_request {
    164367    my $req_id = shift;
    165368    my $fault = shift;
    166369    my $verbose = shift;
    167370   
    168     my $command = "$pstamptool -updatereq -req_id $req_id -set_state stop";
    169     $command   .= " -set_fault $fault" if $fault;
     371    my $command = "$pstamptool -updatereq -req_id $req_id";
     372    if ($fault) {
     373        $command .= " -set_fault $fault";
     374    } else {
     375        $command .= " -set_state stop";
     376    }
    170377    $command   .= " -dbname $dbname" if $dbname;
    171378    $command   .= " -dbserver $dbserver" if $dbserver;
     
    176383    }
    177384}
     385
     386sub my_die {
     387    my $msg = shift;
     388    my $fault = shift;
     389
     390    print STDERR $msg;
     391
     392    update_request($req_id, $fault);
     393
     394    exit $fault;
     395}
  • branches/meh_branches/ppstack_test/pstamp/scripts/dqueryparse.pl

    r28818 r33415  
    1 #!/usr/bin/env perl
    2 #
    3 # parse a MOPS_DETCTABILITY_QUERY table and create a results file
     1#! /usr/bin/env perl
     2#
     3#
     4# Create a response to a MOPS_DETECTABILITY_QUERY
     5#
    46#
    57
    68use strict;
    79use warnings;
     10
     11use Sys::Hostname;
    812use Carp;
     13use File::Basename;
     14use File::Copy;
     15use IPC::Cmd 0.36 qw( can_run run );
    916use Getopt::Long qw( GetOptions );
    1017use Pod::Usage qw( pod2usage );
    11 use IPC::Cmd 0.36 qw( can_run run );
     18use File::Temp qw( tempfile tempdir);
     19use POSIX;  # for strftime
    1220
    1321use PS::IPP::PStamp::RequestFile qw( :standard );
    1422use PS::IPP::PStamp::Job qw( :standard );
    15 use PS::IPP::Config qw($PS_EXIT_SUCCESS
    16                        $PS_EXIT_UNKNOWN_ERROR
    17                        $PS_EXIT_SYS_ERROR
    18                        $PS_EXIT_CONFIG_ERROR
    19                        $PS_EXIT_PROG_ERROR
    20                        $PS_EXIT_DATA_ERROR
    21                        $PS_EXIT_TIMEOUT_ERROR
    22                        metadataLookupStr
    23                        metadataLookupBool
    24                        caturi
    25                        );
    26 
    27 my ($no_update, $imagedb, $label);
    28 my ($req_file, $req_id, $outdir, $product, $mode, $dbname, $dbserver, $verbose, $save_temps);
    29 my ($job_id,$rownum); # stuff from the post-update world
    30 #
    31 # parse args
    32 #
    33 
     23use PS::IPP::Config qw( :standard );
     24use PS::IPP::Metadata::List qw( parse_md_list );
     25
     26# use Astro::FITS::CFITSIO qw( :constants );
     27# Astro::FITS::CFITSIO::PerlyUnpacking(1);
     28
     29my $host = hostname();
     30
     31my $mode = 'queue_job';
     32
     33my ($req_id, $product, $need_magic, $missing_tools, $project, $label);
     34my ($request_file, $outdir, $dbname, $dbserver, $verbose, $save_temps, $no_update);
    3435GetOptions(
    35         'file=s'          =>      \$req_file,
    36         'req_id=s'        =>      \$req_id,
    37         'job_id=s'        =>      \$job_id,
    38         'rownum=s'        =>      \$rownum,
    39         'outdir=s'       =>      \$outdir,
    40         'label=s'         =>      \$label,
    41         'product=s'       =>      \$product,
    42         'mode=s'          =>      \$mode,
    43         'dbname=s'        =>      \$dbname,
    44         'dbserver=s'      =>      \$dbserver,
    45         'verbose'         =>      \$verbose,
    46         'save-temps'      =>      \$save_temps,
    47 ) or pod2usage(2);
    48 
    49 die "invalid mode '$mode'" unless ($mode eq "list_uri") or ($mode eq "queue_job");
    50 die "--file or --job_id is required" if !$req_file;
    51 
    52 if ($mode ne "list_uri") {
    53     die "req_id is required" if !$req_id;
    54     die "outdir is required" if !$outdir;
    55     die "product is required" if !$product;
    56 }
    57 my $missing_tools;
    58 my $pstamptool = can_run('pstamptool') or (warn "Can't find pstamptool" and $missing_tools =1);
    59 my $detectresponse = can_run('detectability_respond.pl') or
    60     (warn "Can't find detectability_respond.pl" and $missing_tools = 1);
    61 my $fields = can_run('fields') or (warn "Can't find fields" and $missing_tools =1);
    62 
     36    'file=s'          =>      \$request_file,
     37    'req_id=s'        =>      \$req_id,
     38    'outdir=s'        =>      \$outdir,
     39    'label=s'         =>      \$label,
     40    'product=s'       =>      \$product,
     41    'mode=s'          =>      \$mode,
     42    'dbname=s'        =>      \$dbname,
     43    'dbserver=s'      =>      \$dbserver,
     44    'verbose'         =>      \$verbose,
     45    'save-temps'      =>      \$save_temps,
     46    'no-update'       =>      \$no_update,
     47    ) or pod2usage(2);
     48
     49pod2usage( -msg => "Unknown option: @ARGV", -exitval => 2 ) if @ARGV;
     50pod2usage( -msg => "Required options: --file --req_id --outdir --dbname",
     51           -exitval => 3,
     52    ) unless
     53    defined $request_file and defined $outdir and defined $dbname and defined $req_id;
     54
     55my $detect_query_read = can_run('detect_query_read') or (warn "Can't find detect_query_read" and $missing_tools = 1);
     56my $pstamptool = can_run('pstamptool') or (warn "Can't find pstamptool" and $missing_tools = 1);
     57my $fields = can_run('fields') or (warn "Can't find fields" and $missing_tools = 1);
    6358if ($missing_tools) {
    6459    warn("Can't find required tools.");
    65     exit ($PS_EXIT_CONFIG_ERROR);
    66 }
     60    exit($PS_EXIT_CONFIG_ERROR);
     61}
     62
     63unless (defined $verbose) {
     64    $verbose = 0;
     65}
     66
     67my $ipprc = PS::IPP::Config->new();
     68my $mdcParser = PS::IPP::Metadata::Config->new; # Parser for metadata config files
     69
    6770
    6871if (!$dbserver) {
    69     my $ipprc = PS::IPP::Config->new();
    70     $dbserver =  metadataLookupStr($ipprc->{_siteConfig}, 'PS_DBSERVER');
    71 }
    72 
    73 # just deal with these arguments once and for all
    74 $pstamptool .= " -dbname $dbname" if $dbname;
    75 $pstamptool .= " -dbserver $dbserver" if $dbserver;
    76 $detectresponse .= " --dbname $dbname" if $dbname;
    77 
    78 $no_update = 1 if $mode eq "list_job";
    79 
    80 # Unless we're running as a job, write the parse arguments in case we need to rerun this parsing.
    81 if (!$job_id) {
    82     my $argslist = "$outdir/parse.args";
    83     open ARGSLIST, ">$argslist" or my_die("failed to open argslist file $argslist", $job_id, $PS_EXIT_UNKNOWN_ERROR);
    84     print ARGSLIST "--label $label --mode $mode --req_id $req_id --product $product --outdir $outdir --file $req_file\n";
    85     close ARGSLIST;
     72    $dbserver = metadataLookupStr($ipprc->{_siteConfig}, 'PS_DBSERVER');
     73}
     74
     75$pstamptool .= " -dbname $dbname -dbserver $dbserver";
     76
     77# Project name is hardcoded to gpc1 for the moment.
     78$project = resolve_project($ipprc,"gpc1",$dbname,$dbserver);
     79my $imagedb = $project->{dbname};
     80if (!$imagedb) {
     81    my_die("failed to find imagedb for project: $project", $PS_EXIT_CONFIG_ERROR);
    8682}
    8783
     
    8985my $fields_output;
    9086{
    91     my $command = "echo $req_file | $fields -x 0 EXTNAME EXTVER QUERY_ID";
     87    my $command = "echo $request_file | $fields -x 0 EXTNAME EXTVER QUERY_ID";
    9288    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    9389        run(command => $command, verbose => $verbose);
     
    9793my (undef, $extname, $extver, $req_name) = split " ", $fields_output;
    9894
    99 my_die("$req_file is missing one of EXTNAME EXTVER or QUERY_ID", $PS_EXIT_PROG_ERROR)
     95my_die("$request_file is missing one of EXTNAME EXTVER or QUERY_ID", $PS_EXIT_PROG_ERROR)
    10096    if !(defined($extname) and defined($extver) and defined($req_name));
    101 my_die("$req_file has EXTNAME $extname not MOPS_DETECTABILITY_QUERY table", $PS_EXIT_PROG_ERROR)
     97my_die("$request_file has EXTNAME $extname not MOPS_DETECTABILITY_QUERY table", $PS_EXIT_PROG_ERROR)
    10298    if $extname ne "MOPS_DETECTABILITY_QUERY";
    103 my_die("$req_file is version $extver expecting 1", $PS_EXIT_PROG_ERROR)
     99my_die("$request_file is version $extver expecting 1 or 2", $PS_EXIT_PROG_ERROR)
    104100    if ($extver ne 1) and ($extver ne 2);
    105101
    106 # Set up the workdir for this query.
    107 if (! -e $outdir ) {
    108     mkdir $outdir or my_die("cannot create output directory $outdir", $PS_EXIT_PROG_ERROR);
    109 } elsif (! -d $outdir ) {
    110     my_die ("output fileset directory $outdir exists but is not a directory", $PS_EXIT_PROG_ERROR);
    111 }
    112 
    113 
    114 # Pass along the request file to the response generator.
    115 my $response_file = "$outdir/${req_name}.dresponse.${req_id}.fits";
    116 my $fault;
    117 my $data_to_update = '';
     102if ($req_id) {
     103    my $command = "$pstamptool -listreq  -name $req_name -not_req_id $req_id";
     104    # set verbose to false so that error message about request not found doesn't appear in parse_error.txt
     105    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     106        run(command => $command, verbose => 0);
     107    if ($success) {
     108        # -listreq succeeded duplicate request name
     109        print STDERR "QUERY_ID $req_name has already been used\n";
     110        $command = "$pstamptool -addjob -job_type none -rownum 0 -state stop -fault $PSTAMP_DUP_REQUEST -req_id $req_id";
     111        unless ($no_update) {
     112            my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     113                run(command => $command, verbose => $verbose);
     114            if (!$success) {
     115                my_die("$command failed", $PS_EXIT_UNKNOWN_ERROR);
     116            }
     117        } else {
     118            print STDERR "skipping $command\n";
     119        }
     120       
     121        my $datestr = strftime "%Y%m%d%H%M%S.$req_id", gmtime;
     122        $req_name = "ERROR.$datestr";
     123    }
     124    $command = "$pstamptool -updatereq -req_id $req_id  -set_name $req_name -set_outProduct $product";
     125    unless ($no_update) {
     126        ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     127            run(command => $command, verbose => $verbose);
     128        unless ($success) {
     129            my_die("$command failed", $PS_EXIT_UNKNOWN_ERROR);
     130        }
     131    } else {
     132        print STDERR "skipping $command\n";
     133    }
     134    exit (0);
     135}
     136
     137
     138
     139#
     140# query is a hash which uses $fpa_id as the key
     141# The values are hash references which have the various parameter name as the key
     142#   The values of the parameter hashes are arrays which contain the values for individual rows
     143#   in the detectabilty query request
     144my %query = ();
     145
    118146{
    119     my $command = "$detectresponse --input $req_file --output $response_file --workdir $outdir";
    120     $command .= " --save-temps" if $save_temps;
    121     $command .= " --verbose" if $verbose;
    122 
     147    #
     148    # Parse input request file using detect_query_read
     149    # result is a simple text file
     150    #
     151    my $dqr_command = "$detect_query_read --dbname $imagedb --input $request_file";
    123152    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    124         run(command => $command, verbose => $verbose);
     153        run(command => $dqr_command, verbose => $verbose);
    125154    unless ($success) {
    126         warn("Warn! Unable to perform $command error code: $error_code");
    127     }
    128     # Use the fault code to see if we can regenerate the missing data.
    129     $fault = $error_code >> 8;
    130     if ($fault == $PSTAMP_NOT_AVAILABLE) {
    131         unless (-e "$outdir/update_request.dat") {
    132             my_die ("Update request indicated, but unable to find actual request!", $PS_EXIT_PROG_ERROR);
    133         }
    134     }   
    135    
    136 }
    137 
    138 my $result;
    139 # If we returned correctly with a valid response file, get a job ID
    140 # for the completed work, and move the response to a standardized name.
    141 if ($fault == 0) {
    142     my $command = "$pstamptool -addjob -req_id $req_id -outputBase $outdir";
    143     $command .= " -job_type detect_query -state stop -fault 0";
    144     $command .= " -rownum 1";
    145 
    146     my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    147         run(command => $command, verbose => $verbose);
    148     if ($success) {
    149         $job_id = join "", @$stdout_buf;
    150         chomp $job_id;
    151         if ($job_id && -e $response_file) {
    152             rename $response_file, "$outdir/response${job_id}.fits";
    153         }
    154         $result = 0;
     155        # This is a problem, because I'm not sure how we handle a failure to read something.
     156        # We need to return a $PSTAMP_INVALID_REQUEST, I think, but if we can't read it,
     157        # we can't send that response back.
     158        die("Unable to perform $dqr_command error code: $error_code");
     159    }
     160    my $Nrows = 0;
     161    {
     162        my @column_names = ();
     163        # split output into lines skip until the line which lists the column names is found
     164        # Parse subsequent lines
     165        foreach my $entry (split /\n/, (join "", @$stdout_buf)) {
     166            if ($entry =~ /^#/) {
     167                @column_names = split /\s+/, $entry;
     168                shift(@column_names);  # Dump the hash sign.
     169            }
     170            elsif (scalar @column_names) {
     171                # ROWNUM RA1_DEG DEC1_DEG RA2_DEG DEC2_DEG MAG QUERY_ID FPA_ID MJD-OBS FILTER OBSCODE STAGE
     172                my %row_data;
     173                @row_data{@column_names} = (split /\s+/, $entry);
     174                for (my $i = 0; $i <= $#column_names; $i++) {
     175                    push @{ $query{$row_data{"FPA_ID"}}{$column_names[$i]} }, $row_data{$column_names[$i]};
     176                    $Nrows = scalar(keys(%query));
     177                    # print "$row_data{'FPA_ID'} $Nrows $i $column_names[$i] $row_data{$column_names[$i]}\n";
     178                }
     179            }
     180        }
     181    }
     182    #
     183    # Identify target components.  This should properly collate targets on a single imfile.
     184    #
     185    my $query_id;
     186    foreach my $fpa_id (keys %query) {
     187        my %temp_hash;
     188        my $query_style = 'byexp';
     189        my $stage;
     190        my $filter;
     191        my $mjd;
     192        # Confirm that we only have one stage/filter/mjd
     193        if ($fpa_id ne 'Not_Set') {   # We only need to check things that aren't the known odd case.
     194            for (my $i = 0; $i <= $#{ $query{$fpa_id}{STAGE} }; $i++) {
     195                $temp_hash{STAGE}{$query{$fpa_id}{STAGE}[$i]} = 1;
     196                $temp_hash{FILTER}{$query{$fpa_id}{FILTER}[$i]} = 1;
     197                $temp_hash{'MJD-OBS'}{$query{$fpa_id}{'MJD-OBS'}[$i]} = 1;
     198            }
     199            if (scalar(keys(%{ $temp_hash{STAGE} })) == 1) {
     200                $stage = (keys(%{ $temp_hash{STAGE} }))[0];
     201            }
     202            else {
     203                exit_with_failure(21,"Too many STAGEs specified");
     204            }
     205            if (scalar(keys(%{ $temp_hash{FILTER} })) == 1) {
     206                $filter = (keys(%{ $temp_hash{FILTER} }))[0];
     207            }
     208            else {
     209                exit_with_failure(21,"Too many FILTERs specified");
     210            }
     211            if (scalar(keys(%{ $temp_hash{'MJD-OBS'} })) == 1) {
     212                $mjd = (keys(%{ $temp_hash{'MJD-OBS'} }))[0];
     213            }
     214            else {
     215                exit_with_failure(21,"Too many MJD-OBS specified");
     216            }
     217        }
     218
     219        # Set up a rowList with default values
     220        my @rowList;
     221        for (my $i = 0; $i <= $#{ $query{$fpa_id}{STAGE} }; $i++) {
     222            $rowList[$i]->{CENTER_X} = $query{$fpa_id}{RA1_DEG}[$i];
     223            $rowList[$i]->{CENTER_Y} = $query{$fpa_id}{DEC1_DEG}[$i];
     224            $rowList[$i]->{ID} = $query{$fpa_id}{ROWNUM}[$i];
     225            $rowList[$i]->{COORD_MASK} = 0;
     226            # Set default values
     227            $query{$fpa_id}{BAD_COMPONENT}[$i] = 1;
     228            $query{$fpa_id}{IMAGE}[$i] = 'no_image';
     229            $query{$fpa_id}{MASK}[$i] = 'no_mask';
     230            $query{$fpa_id}{WEIGHT}[$i] = 'no_weight';
     231            $query{$fpa_id}{PSF}[$i] = 'no_psf';
     232
     233            $query{$fpa_id}{STAGE_ID}[$i] = 'no_id';
     234            $query{$fpa_id}{IMAGE_DB}[$i] = 'no_imdb';
     235            $query{$fpa_id}{NEED_MAGIC}[$i] = 'no_magic';
     236            $query{$fpa_id}{MAGICKED}[$i] = 'no_magic';
     237            $query{$fpa_id}{CATALOG}[$i] = 'no_catalog';
     238            $query{$fpa_id}{COMPONENT_ID}[$i] = 'no_component';
     239            $query{$fpa_id}{CLASS_ID}[$i] = 'no_class';
     240
     241            $query{$fpa_id}{STATE}[$i] = 'no_state';
     242            $query{$fpa_id}{DATA_STATE}[$i] = 'no_dstate';
     243            $query{$fpa_id}{FAULT}[$i] = 'no_fault';
     244            $query{$fpa_id}{BURNTOOL_STATE}[$i] = 'no_btstate';
     245        }
     246
     247        # Determine the query style for this fpa_id
     248        if ($fpa_id =~ /o.*g.*o/) {
     249            $query_style = 'byexp';
     250        }
     251        elsif ($fpa_id =~ /\d+/) {
     252            $query_style = 'byid';
     253        }
     254        elsif ($fpa_id eq 'Not_Set') {
     255            # no matching file was found skip
     256            next;
     257        }
     258        else {
     259            exit_with_failure(21,"Parse error in request file");
     260        }
     261        # Set common request components
     262        my $option_mask |= 1;
     263        $option_mask |= $PSTAMP_SELECT_IMAGE;
     264        $option_mask |= $PSTAMP_SELECT_MASK;
     265        $option_mask |= $PSTAMP_SELECT_VARIANCE;
     266        $option_mask |= $PSTAMP_SELECT_PSF;
     267
     268        # magic is dead
     269        my $need_magic = 0;
     270        if ($stage eq 'stack') {
     271            $need_magic = 0;
     272        }
     273        my $mjd_min = int $mjd;
     274        my $mjd_max = $mjd + 1;
     275       
     276        my $req_filter;
     277        if ($filter ne 'Not_Set') {
     278            $req_filter = $filter . '%';
     279        }
     280       
     281        # Call the PStamp code to find the images that contain the target on the given MJD in the specified filter.
     282        my $pstamp_images_ref = locate_images($ipprc,$imagedb,
     283                                          \@rowList,
     284                                          $query_style,$stage,
     285                                          $fpa_id,undef,undef,
     286                                          $option_mask,$need_magic,
     287                                          $mjd_min,$mjd_max,$req_filter,undef,$verbose); 
     288       
     289        foreach my $this_image_ref (@{ $pstamp_images_ref }) {
     290
     291            # loop over the rows that this component matched
     292            foreach my $valid_index (@{ $this_image_ref->{row_index} }) {
     293                $query{$fpa_id}{IMAGE}[$valid_index] = $this_image_ref->{image};
     294                $query{$fpa_id}{MASK}[$valid_index] = $this_image_ref->{mask};
     295                $query{$fpa_id}{WEIGHT}[$valid_index] = $this_image_ref->{weight};
     296                $query{$fpa_id}{PSF}[$valid_index] = $this_image_ref->{psf};
     297                $query{$fpa_id}{STAGE_ID}[$valid_index] = $this_image_ref->{stage_id};
     298                $query{$fpa_id}{IMAGE_DB}[$valid_index] = $this_image_ref->{imagedb};
     299                $query{$fpa_id}{NEED_MAGIC}[$valid_index] = $need_magic;
     300                $query{$fpa_id}{BAD_COMPONENT}[$valid_index] = 0;
     301               
     302                if (exists($this_image_ref->{astrom})) {
     303                    $query{$fpa_id}{CATALOG}[$valid_index] = $this_image_ref->{astrom};
     304                }
     305                else {
     306                    $query{$fpa_id}{CATALOG}[$valid_index] = $this_image_ref->{cmf};
     307                }
     308                if (exists($this_image_ref->{class_id})) {
     309                    $query{$fpa_id}{COMPONENT_ID}[$valid_index] = $this_image_ref->{class_id};
     310                    $query{$fpa_id}{CLASS_ID}[$valid_index] = $this_image_ref->{class_id};
     311                   
     312                }
     313                else {
     314                    $query{$fpa_id}{COMPONENT_ID}[$valid_index] = $this_image_ref->{skycell_id};
     315                    $query{$fpa_id}{CLASS_ID}[$valid_index] = 'fpa';
     316                }
     317               
     318                $query{$fpa_id}{STATE}[$valid_index] = $this_image_ref->{state};
     319                if (exists($this_image_ref->{data_state})) {
     320                    $query{$fpa_id}{DATA_STATE}[$valid_index] = $this_image_ref->{data_state};
     321                }
     322                else {
     323                    $query{$fpa_id}{DATA_STATE}[$valid_index] = $this_image_ref->{state};
     324                }
     325                $query{$fpa_id}{FAULT}[$valid_index] = 0;
     326                    $query{$fpa_id}{MAGICKED}[$valid_index] = $this_image_ref->{magicked};
     327                if ($stage eq 'chip') {
     328                    $query{$fpa_id}{BURNTOOL_STATE}[$valid_index] = $this_image_ref->{burntool_state};
     329                }
     330               
     331                # Determine if the data exists.
     332                if (($query{$fpa_id}{STATE}[$valid_index] eq 'goto_purged') or
     333                    ($query{$fpa_id}{DATA_STATE}[$valid_index] eq 'purged') or
     334                    ($query{$fpa_id}{STATE}[$valid_index] eq 'drop') or
     335                    ($query{$fpa_id}{STATE}[$valid_index] eq 'error_cleaned') or
     336                    ($query{$fpa_id}{STATE}[$valid_index] eq 'goto_scrubbed') or
     337                    ($query{$fpa_id}{DATA_STATE}[$valid_index] eq 'scrubbed')) {
     338                   
     339                    # image is gone and it's not coming back
     340                    $query{$fpa_id}{FAULT}[$valid_index] = $PSTAMP_GONE;
     341                }
     342                elsif ($need_magic and ($query{$fpa_id}{MAGICKED}[$valid_index] eq 0)) {
     343                    $query{$fpa_id}{FAULT}[$valid_index] = $PSTAMP_NOT_DESTREAKED;
     344                }
     345                elsif (($query{$fpa_id}{DATA_STATE}[$valid_index] ne 'full')) {               
     346                    $query{$fpa_id}{FAULT}[$valid_index] = $PSTAMP_NOT_AVAILABLE;
     347                   
     348                    # updating stacks isn't implemented
     349                    if (($stage eq 'stack')) {
     350                        $query{$fpa_id}{FAULT}[$valid_index] = $PSTAMP_NOT_IMPLEMENTED;
     351                    }
     352                    # updating old burntool data isn't implemented
     353                    elsif ($stage eq 'chip') {
     354                        if ($query{$fpa_id}{BURNTOOL_STATE}[$valid_index] and
     355                            (abs($query{$fpa_id}{BURNTOOL_STATE}[$valid_index]) < 14)) {
     356                            $query{$fpa_id}{FAULT}[$valid_index] = $PSTAMP_NOT_IMPLEMENTED;
     357                            }
     358                    }
     359                } # End determining error faults.
     360            }
     361        }
     362    }
     363}
     364
     365my %update_request;
     366my %rows_for_component;
     367my %faulted_rows;
     368
     369# now build a hash using image name as key which contains the list of rows for that image
     370foreach my $fpa_id (keys %query) {
     371    for (my $i = 0; $i <= $#{ $query{$fpa_id}{ROWNUM} }; $i++) {
     372        if ($query{$fpa_id}{BAD_COMPONENT}[$i] == 0) {
     373            push @{ $rows_for_component{$fpa_id}{$query{$fpa_id}{IMAGE}[$i]} }, $i;
     374        } else {
     375            $faulted_rows{$query{$fpa_id}{ROWNUM}[$i]} = $query{$fpa_id}{FAULT}[$i];
     376        }
     377    }
     378}
     379
     380#
     381# Finally build the parameter lists and queue jobs for each component
     382#
     383
     384my $job_num = 1;
     385foreach my $fpa_id (keys %rows_for_component) {
     386    foreach my $component (keys % {$rows_for_component{$fpa_id} } ) {
     387        my $i = $rows_for_component{$fpa_id}{$component}[0];
     388        my $dep_id = 0;
     389        my $data_state = $query{$fpa_id}{DATA_STATE}[$i];
     390        if ($data_state ne 'full') {
     391            # Queue this data to be updated
     392            my $stage = $query{$fpa_id}{STAGE}[$i];
     393            my $stage_id = $query{$fpa_id}{STAGE_ID}[$i];
     394            my $component = $query{$fpa_id}{COMPONENT_ID}[$i];
     395            print "Need to UPDATE $stage $stage_id $component from $data_state\n";
     396            $dep_id = queue_update_run($req_id, $outdir, $label, $data_state, $stage, $stage_id, $component, 0, $imagedb);
     397        }
     398
     399        my $outputBase = "$outdir/$job_num" . "_";
     400
     401        # params_file is an mdc description containing the parameters for the job
     402        my $params_file = $outputBase . "params.mdc";
     403
     404        open PARAMS, ">$params_file" or my_die("failed to create $params_file", $PS_EXIT_UNKNOWN_ERROR);
     405
     406        # first the job params
     407        print PARAMS "dqueryJobParams METADATA\n";
     408        foreach my $key (keys %{ $query{$fpa_id} } ) {
     409            my $value = $query{$fpa_id}{$key}[0];
     410            print PARAMS "\t$key\t\tSTR\t$value\n";
     411        }
     412        print PARAMS "END\n\n";
     413
     414        # then one structure with the coordinates for each row
     415        print PARAMS "dqueryCoord MULTI\n";
     416
     417        my @coordkeys = qw(ROWNUM RA1_DEG DEC1_DEG RA2_DEG DEC2_DEG MAG);
     418        foreach my $row ( @{ $rows_for_component{$fpa_id}{$component} }) {
     419            print PARAMS "\ndqueryCoord METADATA\n";
     420            foreach my $key (@coordkeys) {
     421                my $value = $query{$fpa_id}{$key}[$row];
     422                print PARAMS "\t$key\t\tSTR\t$value\n";
     423            }
     424            print PARAMS "END\n";
     425        }
     426        close(PARAMS);
     427
     428        # use first rownum for this component as the rownum for the job
     429        my $rownum = $query{$fpa_id}{ROWNUM}[$rows_for_component{$fpa_id}{$component}[0]];
     430
     431        my $command = "$pstamptool -addjob -req_id $req_id -outputBase $outputBase -job_type detect_query -state run -rownum $rownum";
     432        $command .= " -dep_id $dep_id" if $dep_id;
     433        unless ($no_update) {
     434            my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     435                run(command => $command, verbose => $verbose);
     436            if ($success) {
     437                my $job_id = join "", @$stdout_buf;
     438                print "   Queued job: $job_id\n";
     439            } else {
     440                my $exit_status = $error_code >> 8;
     441                $exit_status = $PS_EXIT_UNKNOWN_ERROR unless $exit_status;
     442                my_die("Unable to perform $command error code: $error_code", $exit_status);
     443            }
     444        } else {
     445            print STDERR "skipping $command\n";
     446        }
     447        $job_num++;
     448    }
     449}
     450
     451foreach my $rownum (keys %faulted_rows ) {
     452    my $outputBase = "$outdir/$job_num" . "_";
     453    my $fault = $faulted_rows{$rownum};
     454    $fault = $PSTAMP_NO_IMAGE_MATCH if ($fault eq 'no_fault');
     455    print STDERR "insert faulted job for $rownum: $fault\n";
     456    my $command = "$pstamptool -addjob -req_id $req_id -outputBase $outputBase -job_type detect_query -state stop -rownum $rownum -fault $fault";
     457    unless ($no_update) {
     458        my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     459            run(command => $command, verbose => $verbose);
     460        if ($success) {
     461            my $job_id = join "", @$stdout_buf;
     462            print "   Queued job: $job_id\n";
     463        } else {
     464            my $exit_status = $error_code >> 8;
     465            $exit_status = $PS_EXIT_UNKNOWN_ERROR unless $exit_status;
     466            my_die("Unable to perform $command error code: $error_code", $exit_status);
     467        }
    155468    } else {
    156         warn("Unable to perform $command error code: $error_code");
    157         $result = $error_code >> 8;
    158     }
    159 }
    160 elsif ($fault == $PSTAMP_NOT_AVAILABLE) {
    161     # Failed to run correctly, which means that we need to queue a job and flag data for updating.
    162     # Get the dependency id for the data we're requesting be updated.
    163     open(UPDATE_REQUEST,"$outdir/update_request.dat") || my_die ("Update request indicated, but unable to find actual request!", $PS_EXIT_PROG_ERROR);
    164     while (<UPDATE_REQUEST>) {
    165         my $data_to_update = $_;
    166         chomp($data_to_update);
    167         my $dep_id = queue_update_run($req_id,$job_id,$outdir,$label,$data_to_update);
    168 
    169         # Link this request to a job and link that job to any dependency
    170         my $command = "$pstamptool -addjob -req_id $req_id -outputBase $outdir";
    171         $command .= " -job_type detect_query -state run -fault 0";
    172         $command .= " -rownum 1";
    173         $command .= " -dep_id $dep_id" if $dep_id;
    174 
    175         my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    176             run(command => $command, verbose => $verbose);
    177 
    178         if ($success) {
    179             $job_id = join "", @$stdout_buf;
    180             chomp $job_id;
    181             if ($job_id && -e $response_file) {
    182                 # We shouldn't have a response file at this stage.
    183                 rename $response_file, "$outdir/response${job_id}.fits";
    184             }
    185             $result = 0;
    186         } else {
    187             warn("Unable to perform $command error code: $error_code");
    188             $result = $error_code >> 8;
    189         }
    190     }
    191     close(UPDATE_REQUEST);
    192 }
    193 else {
    194     my_die ("Parse fault!!", $PS_EXIT_UNKNOWN_ERROR);
    195 }
    196 
    197 # This does not set the request state to stop.  That will happen with the request_finish.pl script,
    198 # which will notice that we've inserted the stopped job and decide we're finished. Easy enough.
     469        print STDERR "skipping $command\n";
     470    }
     471    $job_num++;
     472}
     473
    199474{
    200475    my $command = "$pstamptool -updatereq -req_id $req_id -set_name $req_name -set_outProduct $product";
    201     $command .= " -set_fault $result" if $result;
    202 
    203     my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    204         run(command => $command, verbose => $verbose);
    205     unless ($success) {
     476    # $command .= " -set_fault $result" if $result;
     477
     478    unless ($no_update) {
     479        my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     480            run(command => $command, verbose => $verbose);
     481        unless ($success) {
    206482        my_die("$command failed",$PS_EXIT_UNKNOWN_ERROR);
    207     }
    208 }
    209  
     483        }
     484    } else {
     485        print STDERR "Skipping $command\n";
     486    }
     487}
     488
    210489exit 0;
    211490
    212 
    213 # If we have to queue an update run, do so and create a new dependent
    214491sub queue_update_run {
    215     my ($req_id, $job_id, $outdir, $label, $data_to_update) = @_;
    216 
    217     my ($state, $stage, $stage_id, $component, $need_magic, $imagedb) = split /\s+/, $data_to_update;
     492    my ($req_id, $outdir, $label, $state, $stage, $stage_id, $component, $need_magic, $imagedb) = @_;
     493
     494#    my ($state, $stage, $stage_id, $component, $need_magic, $imagedb) = split /\s+/, $data_to_update;
    218495   
    219496    if (($state ne 'cleaned') and ($state ne 'update') and ($state ne 'goto_cleaned')) {
     
    248525    return($dep_id);
    249526}
    250        
    251    
     527
    252528
    253529sub my_die {
    254     my $msg = shift;
    255     my $fault = shift;
    256 
    257     carp $msg;
    258 
    259     # we don't fault the request here pstamp_parser_run.pl handles that if necessary
    260     exit $fault;
    261 }
     530    my $message = shift;
     531    my $exit_code = shift;
     532
     533    $exit_code = $PS_EXIT_PROG_ERROR unless defined $exit_code;
     534
     535    carp("$message");
     536    exit($exit_code);
     537}
     538
     539sub exit_with_failure {
     540    my $status = shift;
     541    my $message = shift;
     542    my_die($message, $status);
     543}
     544
  • branches/meh_branches/ppstack_test/pstamp/scripts/pstamp_checkdependent.pl

    r30879 r33415  
    117117    }
    118118}
     119
     120# magic is no longer rquired
     121$need_magic = 0;
     122$magic_ok =  1;
    119123my $status = 0;
    120 if ((($it->{state} eq 'full') or ($it->{state} eq 'update')) and ($it->{data_state} eq 'full')
    121         and (!$need_magic or $magic_ok or $it->{magicked} > 0)) {
     124if ((($it->{state} eq 'full') or ($it->{state} eq 'update')) and ($it->{data_state} eq 'full')) {
    122125
    123126    # This Dependency is satisfied. All done. Release the pstampJobs
     
    197200    }
    198201
     202if (0) {
    199203    if (!$job_fault and ($stage eq 'chip')) {
    200204        # what about "error_cleaned" ?
     
    210214        }
    211215    }
     216}
    212217
    213218    if ($job_fault >= $PSTAMP_FIRST_ERROR_CODE) {
     
    240245        my $state = $chip->{state};
    241246        my $data_state = $chip->{data_state};
     247        my $fault = $chip->{fault};
    242248        if (($state =~ /error/) or ($state =~ /purged/) or ($state =~ /scrubbed/) or ($state eq 'drop') or
    243             ($data_state =~ /error/) or ($data_state =~ /purged/) or ($data_state =~ /scrubbed/) or ($data_state eq 'drop')) {
    244 
    245             print "chipRun state is $chip->{chip_id} has state: $state data_state: $data_state cannot update\n";
     249            ($data_state =~ /error/) or ($data_state =~ /purged/) or ($data_state =~ /scrubbed/) or ($data_state eq 'drop') or
     250            ($fault eq $PSTAMP_GONE)) {
     251
     252            print "chipRun state is $chip->{chip_id} has state: $state data_state: $data_state fault: $fault cannot update\n";
    246253            my $error_code;
    247254            if (($state eq 'error_cleaned') or ($data_state ='error_cleaned')) {
     
    253260            # caller will fault the jobs
    254261            return $error_code;
    255         } elsif ($chip->{dsRun_state} eq 'failed_revert') {
    256             # XXX: revert failures are rarely fixed. give up but say it's just not available not GONE
    257             print "magicDSRun.state = $dsRun_state for chipRun $stage_id is in state failed_revert cannot update\n";
    258             return $PSTAMP_NOT_AVAILABLE;
    259262        } elsif (($chip->{data_state} ne 'update') and ($chip->{data_state} ne 'full')) {
    260263
     
    282285            } elsif ($fault_count > $max_fault_count) {
    283286                print "$stage $stage_id has faulted $fault_count times. Giving up\n";
    284                 $fault = $PSTAMP_GONE;
    285                 faultComponent('chip', $chip->{chip_id}, $chip->{class_id}, $PSTAMP_GONE);
    286                 return $PSTAMP_GONE;
     287                # XXX: stop faulting chips for now
     288#                $fault = $PSTAMP_GONE;
     289#                faultComponent('chip', $chip->{chip_id}, $chip->{class_id}, $PSTAMP_GONE);
     290                $fault = $PSTAMP_NOT_AVAILABLE;
     291                return $fault;
    287292            }
    288293            # fault the dependent
    289294            my_die("chip $chip->{chip_id} $chip->{class_id} faulted: $chip->{fault}", $chip->{fault});
    290         } elsif ($chip->{dsFile_fault} eq $PSTAMP_GONE) {
    291             print STDERR "magicDSFile $chip->{magic_ds_id} $chip->{chip_id} $chip->{class_id} is GONE";
    292             return $PSTAMP_GONE;
    293         } elsif ($chip->{dsFile_fault} and ($chip->{dsFile_data_state} eq 'update')) {
    294             # fault the dependent
    295             my_die("magicDSFile $chip->{magic_ds_id} $chip->{chip_id} $chip->{class_id} faulted: $chip->{dsFile_fault}", $chip->{dsFile_fault});
    296         }
    297     }
    298 
    299     my $status = 0;
    300     if (!$queued_update) {
    301         $status = check_states_magicDSRun('chip', $chip_id, \@chips, $rlabel, $need_magic, $raw_all_magicked, $magic_ds_id, $dsRun_state);
    302     }
    303 
    304     return $status;
     295        }
     296    }
     297
     298    return 0;
    305299}
    306300
     
    321315    # The update system currently requires that data that has been magicked be destreaked
    322316    # at chip stage so it needs magic even if the customer doesn't.
     317if (0) {
    323318    if ($metadata->{magicked} != 0) {
    324319        $need_magic = 1;
    325320    }
    326 
     321}
    327322    if (($state =~ /error/) or ($state =~ /purged/) or ($state =~ /scrubbed/) or ($state eq 'drop') or
    328323         ($data_state =~ /error/) or ($data_state =~ /purged/) or ($data_state =~ /scrubbed/) or ($data_state eq 'drop')) {
     
    369364        # if chip has been magicked before require it to be magicked again
    370365        # because the warp pending query requires it.
     366if (0) {
    371367        if ($chip->{magicked} < 0) {
    372368            print "Input has been destreaked so we must destreak before warping\n";
    373369            $need_magic = 1
    374370        }
     371}
    375372
    376373        if ($need_magic and ($chip->{magicked} eq 0)) {
     
    421418    my $metadata = shift;
    422419    my $rlabel = shift;     # if defined a new label for the chipRun
    423     my $need_magic = shift;
     420    my $need_magic = 0;
    424421
    425422    my $diff_id   = $metadata->{diff_id};
     
    427424    my $skycell = $metadata;
    428425    my $skycell_id = $skycell->{skycell_id};
    429 
    430     # The update system currently requires that data that has been magicked be destreaked
    431     # at chip stage so it needs magic even if the customer doesn't.
    432     if ($metadata->{magicked} != 0) {
    433         $need_magic = 1;
    434     }
    435426
    436427    if ($diff_mode == $IPP_DIFF_MODE_WARP_STACK ) {
  • branches/meh_branches/ppstack_test/pstamp/scripts/pstamp_cleanup.pl

    r27874 r33415  
    2323
    2424use PS::IPP::Config qw( :standard );
     25use PS::IPP::PStamp::Job qw( :standard );
    2526
    2627my $req_id;
     
    9596}
    9697
     98{
     99    my $command = "$pstamptool -listfile -req_id $req_id";
     100    $command   .= " -dbname $dbname" if $dbname;
     101    $command   .= " -dbserver $dbserver" if $dbserver;
     102    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     103        run(command => $command, verbose => $verbose);
     104    unless ($success) {
     105        die("Unable to perform $command error code: $error_code");
     106    }
     107    my $output = join "", @$stdout_buf;
     108    if ($output) {
     109        my $files = parse_md_fast($mdcParser, $output);
     110        foreach my $file (@$files) {
     111            $ipprc->file_delete($file->{path});
     112        }
     113    }
     114}
     115
    97116# now go find the workdir for this request
    98117# XXX: we finally *have* to store this in the database
  • branches/meh_branches/ppstack_test/pstamp/scripts/pstamp_get_image_job.pl

    r30663 r33415  
    2525
    2626my $output_base;
     27my $bundleroot;
    2728
    2829my $verbose;
    29 my $ipprc;
     30my $imagedbname;
    3031my $dbname;
    3132my $dbserver;
     
    4142        'rownum=s'        =>      \$rownum,
    4243        'output_base=s'   =>      \$output_base,
     44        'bundleroot=s'    =>      \$bundleroot,
     45        'imagedbname=s'   =>      \$imagedbname,
    4346        'dbname=s'        =>      \$dbname,
    4447        'dbserver=s'      =>      \$dbserver,
     
    5255
    5356my_die( $err, $PS_EXIT_PROG_ERROR) if $err;
     57
     58my $ipprc = PS::IPP::Config->new();
    5459
    5560my $params_file = $output_base . ".mdc";
     
    9196my $missing_tools;
    9297my $dist_bundle   = can_run('dist_bundle.pl') or (warn "Can't find dist_bundle.pl" and $missing_tools = 1);
     98my $pstamptool   = can_run('pstamptool') or (warn "Can't find pstamptool" and $missing_tools = 1);
    9399if ($missing_tools) {
    94100    warn("Can't find required tools.");
     
    96102}
    97103
     104$pstamptool .= " -dbname $dbname" if $dbname;
     105$pstamptool .= " -dbserver $dbserver" if $dbserver;
     106
    98107my $outdir = dirname($output_base);
    99108my $basename = basename($path_base);
    100 my $outroot = $output_base ."_" . $basename;
    101109my $results_file = $output_base . ".bundle_results";
     110my $outroot;
     111if ($bundleroot) {
     112    my (undef, undef, undef, $mday, $month, $year) = gmtime(time());
     113    $month += 1;
     114    $year += 1900;
     115
     116    # This will generate an outroot like:
     117    # neb://any/pstamp/bundles/2011/11/22/14026916_1_1_o5739g0358o.353654.wrp.215092.skycell.2083.025
     118
     119    $outroot = $bundleroot . sprintf("/%4d/%02d/%02d/${job_id}_", $year, $month, $mday) . basename($output_base) . "_". $basename;
     120} else {
     121    $outroot = $output_base ."_" . $basename;
     122}
    102123
    103124{
     
    105126    $command .= " --results_file $results_file";
    106127    $command .= " --component $component --path_base $path_base --outroot $outroot";
    107 #    XXX: we need to do some work if we want to support muggle bundles
    108 #    $command .= " --no_magic if $no_magic";
    109     $command .= " --magicked" if $magicked;
    110     $command .= " --dbname $dbname" if $dbname;
     128    # DING DONG ....
     129    $command .= " --no_magic";
     130    $command .= " --dbname $imagedbname" if $imagedbname;
    111131    $command .= " --verbose" if $verbose;
    112132    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     
    147167}
    148168
     169if ($bundleroot) {
     170    {
     171        # delete any existing pstampFile in case this job has faulted and
     172        # been reverted
     173        my $command = "$pstamptool -deletefile -job_id $job_id";
     174        my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     175            run(command => $command, verbose => $verbose);
     176        unless ($success) {
     177            my_die("Unable to perform $command: $error_code", $error_code >> 8);
     178        }
     179    }
     180    my $linkname = "$outdir/$file_name";
     181    if (-l $linkname or -e $linkname) {
     182        unlink $linkname or my_die("Failed to unlink existing symlink: $linkname", $PS_EXIT_UNKNOWN_ERROR);
     183    }
     184    my $bundle_name = dirname($outroot) . "/$file_name";
     185    my $resolved = $ipprc->file_resolve($bundle_name);
     186    if (!$resolved) {
     187        my_die("failed to resolve $bundle_name", $PS_EXIT_UNKNOWN_ERROR);
     188    }
     189    symlink $resolved, $linkname or my_die("failed to create symlink to $resolved in $outdir",
     190        $PS_EXIT_UNKNOWN_ERROR);
     191
     192    my $command = "$pstamptool -addfile -job_id $job_id -path $bundle_name";
     193    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
     194        run(command => $command, verbose => $verbose);
     195    unless ($success) {
     196        my_die("Unable to perform $command: $error_code", $error_code >> 8);
     197    }
     198}
     199
     200
    149201print REGLIST "$file_name|$bytes|$md5sum|tgz|\n";
    150202
  • branches/meh_branches/ppstack_test/pstamp/scripts/pstamp_job_run.pl

    r31508 r33415  
    5959$options = 1 if !$options;
    6060
     61# We don't need to muggle anymore. Ignore those options
     62$options &=  ~($PSTAMP_REQUEST_UNCENSORED | $PSTAMP_REQUIRE_UNCENSORED);
    6163
    6264my $ipprc = PS::IPP::Config->new(); # IPP Configuration
     
    7779my $ppstamp    = can_run('ppstamp') or (warn "Can't find ppstamp" and $missing_tools = 1);
    7880my $pstamp_get_image_job    = can_run('pstamp_get_image_job.pl') or (warn "Can't find pstamp_get_image_job.pl" and $missing_tools = 1);
    79 my $dqueryparse = can_run('dqueryparse.pl') or (warn "Can't find dqueryparse.pl" and $missing_tools = 1);
     81my $dquery_job_run = can_run('dquery_job_run.pl') or (warn "Can't find dquery_job_run.pl" and $missing_tools = 1);
    8082my $streaksreplace = can_run('streaksreplace')  or (warn "Can't find streaksreplace"  and $missing_tools = 1);
    8183my $magicdstool = can_run('magicdstool')  or (warn "Can't find magicdstool"  and $missing_tools = 1);
     
    8789
    8890my $mdcParser = PS::IPP::Metadata::Config->new; # Parser for metadata config files
     91
    8992
    9093my $jobStatus;
     
    107110        $nan_masked = 0;
    108111        $muggle = 1;
     112    }
     113
     114    if ($stage eq "raw") {
     115        $options &= ~($PSTAMP_SELECT_MASK | $PSTAMP_SELECT_VARIANCE);
    109116    }
    110117
     
    214221    }
    215222
     223    # MAGIC IS DEAD
     224    $nan_masked = 0;
     225
    216226    my $command = "$ppstamp $outputBase $argString $fileArgs";
     227    $command .= " -write_jpeg" if ($options & $PSTAMP_SELECT_JPEG);
    217228    $command .= " -dbname $dbname" if $dbname;
    218229    $command .= " -dbserver $dbserver" if $dbserver;
     
    239250
    240251        # Note: we are assuming the contents of the PSTAMP filerules here.
    241         my %extensions = ( $PSTAMP_SELECT_IMAGE  => "fits",
    242                            $PSTAMP_SELECT_MASK   => "mk.fits",
    243                            $PSTAMP_SELECT_VARIANCE => "wt.fits");
    244 
    245         my $output_mask = $options & ($PSTAMP_SELECT_IMAGE | $PSTAMP_SELECT_MASK | $PSTAMP_SELECT_VARIANCE);
     252        my %extensions = ( $PSTAMP_SELECT_IMAGE    => "fits",
     253                           $PSTAMP_SELECT_MASK     => "mk.fits",
     254                           $PSTAMP_SELECT_VARIANCE => "wt.fits",
     255                           $PSTAMP_SELECT_JPEG     => "jpg");
     256
     257        my $output_mask = $options & ($PSTAMP_SELECT_IMAGE | $PSTAMP_SELECT_MASK | $PSTAMP_SELECT_VARIANCE | $PSTAMP_SELECT_JPEG);
    246258
    247259        foreach my $key (keys (%extensions)) {
     
    272284} elsif ($jobType eq "get_image") {
    273285
    274     my $uri = "";
     286    my $pstamp_bundle_root = metadataLookupStr($ipprc->{_siteConfig}, "PSTAMP_BUNDLE_ROOT");
     287
     288    my $params = read_params_file($outputBase);
     289    my $imagedb = $params->{imagedb};
     290
    275291    my $command = "$pstamp_get_image_job --job_id $job_id --output_base $outputBase --rownum $rownum";
     292    $command .= " --bundleroot $pstamp_bundle_root" if $pstamp_bundle_root;
     293    $command .= " --imagedb $imagedb" if $imagedb;
    276294    $command .= " --dbname $dbname" if $dbname;
    277295    $command .= " --dbserver $dbserver" if $dbserver;
     
    287305    }
    288306} elsif ($jobType eq "detect_query") {
    289     # detect_query jobs are basically holders to note that we need a file updated before we can continue.
    290     # Load the argument list that dqueryparse should have created the first time it ran, so we know how to
    291     # run it again the same way.
    292     my $argslist = "$outputBase/parse.args";
    293     open ARGSLIST, "<$argslist" or my_die("failed to open argslist file $argslist", $job_id, $PS_EXIT_UNKNOWN_ERROR);
    294     my $argString = <ARGSLIST>;
    295     close ARGSLIST;
    296     chomp $argString;
     307    # my $outdir = dirname($outputBase);
     308    # my $argslist = "$outdir/parse.args";
     309    # open ARGSLIST, "<$argslist" or my_die("failed to open argslist file $argslist", $job_id, $PS_EXIT_UNKNOWN_ERROR);
     310    # my $argString = <ARGSLIST>;
     311    # close ARGSLIST;
     312    # chomp $argString;
    297313
    298314    # XXX: should we do any other sanity checking?
    299     my_die("arglist file $argslist is empty", $job_id, $PS_EXIT_DATA_ERROR) if !$argString;
    300 
    301     my $command = "$dqueryparse --job_id $job_id $argString";
     315    # my_die("arglist file $argslist is empty", $job_id, $PS_EXIT_DATA_ERROR) if !$argString;
     316
     317    my $command = "$dquery_job_run --job_id $job_id --output_base $outputBase";
    302318    $command .= " --dbname $dbname" if $dbname;
    303319    $command .= " --dbserver $dbserver" if $dbserver;
    304320    $command .= " --verbose" if $verbose;
     321    $command .= " --save-temps" if $save_temps;
    305322    my ( $success, $error_code, $full_buf, $stdout_buf, $stderr_buf ) =
    306323        run(command => $command, verbose => $verbose);
     
    311328    } else {
    312329        $jobStatus = $error_code >> 8;
    313         my_die("dqueryparse.pl failed with error code: $jobStatus", $job_id, $jobStatus);
    314     }
     330        my_die("dquery_job_run.pl failed with error code: $jobStatus", $job_id, $jobStatus);
     331    }
     332} elsif ($jobType eq "child") {
     333    # the only thing jobs of jobType child is to finish
     334    $jobStatus = 0;
    315335} else {
    316336    my_die("unknown jobType $jobType found", $job_id, $PS_EXIT_PROG_ERROR);
     
    597617
    598618    $exit_code = $PS_EXIT_PROG_ERROR unless $exit_code;
     619    if ($exit_code > 100) {
     620        carp ("invalid exit code: $exit_code changing to $PS_EXIT_UNKNOWN_ERROR");
     621        $exit_code = $PS_EXIT_UNKNOWN_ERROR;
     622    }
    599623    $job_state = 'run' unless $job_state;
    600624
  • branches/meh_branches/ppstack_test/pstamp/scripts/pstamp_parser_run.pl

    r30317 r33415  
    5555}
    5656
     57$need_magic = 0;
     58
    5759my $missing_tools;
    5860
     
    8991    # outdir is where all of the files generated for this request are placed
    9092    # NOTE: this location needs to be kept in sync with the web interface ( request.php )
    91     my $datestr = strftime "%Y%m%d", gmtime;
     93    my $datestr = strftime "%Y/%m/%d", gmtime;
    9294    my $datedir = "$pstamp_workdir/$datestr";
    9395    if (! -e $datedir ) {
    94         mkdir $datedir or my_die( "failed to create working directory $datedir for request id $req_id", $req_id,
    95             $PS_EXIT_CONFIG_ERROR);
     96        my $rc = system "mkdir -p $datedir";
     97        if ($rc) {
     98            my $status = $rc >> 8;
     99            $status = $PS_EXIT_CONFIG_ERROR if !$status;
     100            my_die( "failed to create working directory $datedir for request id $req_id", $req_id,
     101                $status);
     102        }
    96103    }
    97104
     
    287294    carp($msg);
    288295
     296    if (!$req_id) {
     297        exit $PS_EXIT_CONFIG_ERROR;
     298    }
     299
    289300    my $command = "$pstamptool -updatereq -req_id $req_id  -set_fault $fault";
    290301    $command   .= " -dbname $dbname" if $dbname;
  • branches/meh_branches/ppstack_test/pstamp/scripts/pstamp_server_status

    r30517 r33415  
    7171        $error_code = (($error_code >> 8) or 1);
    7272        if ($error_code == 12) {
    73             #print "Postage Stamp Server is not running\n";
    74             print "Postage Stamp Server will be down for maintenance it will back shortly.\n";
     73            print "Postage Stamp Server is not running\n";
     74            #print "Postage Stamp Server will be down for maintenance it will back shortly.\n";
    7575            exit 0;
    7676        } else {
  • branches/meh_branches/ppstack_test/pstamp/scripts/pstampparse.pl

    r31507 r33415  
    148148    } elsif ($lcname =~ /qub/) {
    149149        $label = "QUB";
     150        $label_changed = 1;
     151    } elsif ($lcname =~ /pypstamp/) {
     152        $label = "PY";
    150153        $label_changed = 1;
    151154    }
     
    251254    # If we encounter an error for a particular row add a job with the proper fault code.
    252255
     256    my $stage = $row->{IMG_TYPE};
     257
    253258    my $rownum   = $row->{ROWNUM};
    254259    if (!validID($rownum)) {
     
    272277    }
    273278    if ($job_type eq 'get_image') {
    274         unless ($req_type eq 'byid' or $req_type eq 'byexp') {
    275             print STDERR "REQ_TYPE must be 'byid' or 'byexp' for JOB_TYPE 'get_image'\n";
     279        unless ($req_type eq 'byid' or $req_type eq 'byexp' or ($req_type eq 'byskycell' and $stage eq 'stack')) {
     280            print STDERR "REQ_TYPE must be 'byid' or 'byexp' or byskcyell for stacks for JOB_TYPE 'get_image'\n";
    276281            insertFakeJobForRow($row, 1, $PSTAMP_INVALID_REQUEST);
    277282            return 0;
     
    334339    }
    335340
    336     my $stage = $row->{IMG_TYPE};
    337341    if (!check_image_type($stage)) {
    338342        print STDERR "invalid IMG_TYPE for row $rownum\n";
     
    460464    my $numRows = scalar @$rowList;
    461465
     466    if (($req_type eq 'byskycell') or ($req_type eq 'bycoord')) {
     467        # avoid error from print below if $id isn't needed
     468        $id = "" if !$id;
     469    }
    462470    print "Collected $numRows rows beginning with row $rownum. $req_type $stage $id $tess_id $component\n";
    463471   
Note: See TracChangeset for help on using the changeset viewer.