IPP Software Navigation Tools IPP Links Communication Pan-STARRS Links

Ignore:
Timestamp:
Jun 9, 2013, 3:31:46 PM (13 years ago)
Author:
eugene
Message:

thread add/sub noise, thread model background, pass chisq conv options to LMM fitting

Location:
branches/eam_branches/ipp-20130509/psphot/src
Files:
8 edited

Legend:

Unmodified
Added
Removed
  • branches/eam_branches/ipp-20130509/psphot/src/psphot.h

    r35630 r35640  
    6767bool            psphotModelBackground (pmConfig *config, const pmFPAview *view, const char *filerule);
    6868bool            psphotModelBackgroundReadoutFileIndex (pmConfig *config, const pmFPAview *view, const char *filerule, int index);
     69bool            psphotModelBackground_Threaded (psThreadJob *job);
    6970
    7071bool            psphotMaskBackground (pmConfig *config, const pmFPAview *view, const char *filerule);
     
    119120bool            psphotAddOrSubNoise (pmConfig *config, const pmFPAview *view, const char *filerule, bool add);
    120121bool            psphotAddOrSubNoiseReadout (pmConfig *config, const pmFPAview *view, const char *filerule, int index, psMetadata *recipe, bool add);
     122bool            psphotAddOrSubNoise_Threaded (psThreadJob *job);
    121123
    122124bool            psphotExtendedSourceAnalysis (pmConfig *config, const pmFPAview *view, const char *filerule);
     
    243245bool            psphotFitInit (int nThreads);
    244246bool            psphotFitSummary (void);
     247bool            psphotFitSummaryExtended (void);
     248bool            psphotFitInitExtended (void);
    245249
    246250bool            psphotLoadPSF (pmConfig *config, const pmFPAview *view, const char *filerule);
  • branches/eam_branches/ipp-20130509/psphot/src/psphotAddNoise.c

    r34492 r35640  
    11# include "psphotInternal.h"
    22
     3bool psphotAddOrSubNoise_Threaded (psThreadJob *job);
    34bool psphotMaskSource(pmSource *source, bool add, psImageMaskType maskVal);
    45
     
    3233}
    3334
    34 static int Nmasked = 0;
    35 
    3635// the return state indicates if any sources were actually replaced
    3736bool psphotAddOrSubNoiseReadout (pmConfig *config, const pmFPAview *view, const char *filerule, int index, psMetadata *recipe, bool add) {
    3837
    3938    bool status = false;
     39
     40    psTimerStart ("psphot.noise");
    4041
    4142    // find the currently selected readout
     
    5556    if (!sources) return false;
    5657
    57     psTimerStart ("psphot.noise");
     58    // determine the number of allowed threads
     59    int nThreads = psMetadataLookupS32(&status, config->arguments, "NTHREADS"); // Number of threads
     60    if (!status) {
     61        nThreads = 0;
     62    }
    5863
    5964    // user-defined masks to test for good/bad pixels (build from recipe list if not yet set)
     
    8489
    8590    psphotVisualShowImage (readout);
     91
     92    // choose Cx, Cy (see psphotThreadTools.c for overview of the concepts)
     93    int Cx = 1, Cy = 1;
     94    psphotChooseCellSizes (&Cx, &Cy, readout, nThreads);
     95
     96    psArray *cellGroups = psphotAssignSources (Cx, Cy, sources);
     97
     98    for (int i = 0; i < cellGroups->n; i++) {
     99
     100        psArray *cells = cellGroups->data[i];
     101
     102        for (int j = 0; j < cells->n; j++) {
     103
     104            // allocate a job -- if threads are not defined, this just runs the job
     105            psThreadJob *job = psThreadJobAlloc ("PSPHOT_ADD_NOISE");
     106            psArrayAdd(job->args, 1, cells->data[j]); // sources
     107            PS_ARRAY_ADD_SCALAR(job->args, maskVal,  PS_TYPE_IMAGE_MASK);
     108            PS_ARRAY_ADD_SCALAR(job->args, markVal,  PS_TYPE_IMAGE_MASK);
     109            PS_ARRAY_ADD_SCALAR(job->args, FACTOR,   PS_TYPE_F32);
     110            PS_ARRAY_ADD_SCALAR(job->args, SIZE,     PS_TYPE_F32);
     111            PS_ARRAY_ADD_SCALAR(job->args, add,      PS_TYPE_U8);
     112
     113# if (1)
     114            if (!psThreadJobAddPending(job)) {
     115                psError(PS_ERR_UNKNOWN, false, "Unable to add/sub noise.");
     116                return false;
     117            }
     118# else
     119            if (!psphotAddOrSubNoise_Threaded(job)) {
     120                psError(PS_ERR_UNKNOWN, false, "Unable to add/sub noise.");
     121                return false;
     122            }
     123            psFree(job);
     124# endif
     125        }
     126
     127        // wait for the threads to finish and manage results
     128        if (!psThreadPoolWait (false, true)) {
     129            psFree(cellGroups);
     130            psError(PS_ERR_UNKNOWN, false, "Unable to add/sub noise.");
     131            return false;
     132        }
     133
     134        // we have only supplied one type of job, so we can assume the types here
     135        psThreadJob *job = NULL;
     136        while ((job = psThreadJobGetDone()) != NULL) {
     137            // we have no returned data from this operation
     138            if (job->args->n < 1) {
     139                fprintf (stderr, "error with job\n");
     140            }
     141            psFree(job);
     142        }
     143    }
     144
     145    if (add) {
     146        psLogMsg ("psphot.noise", PS_LOG_WARN, "add noise for %ld objects: %f sec\n", sources->n, psTimerMark ("psphot.noise"));
     147    } else {
     148        psLogMsg ("psphot.noise", PS_LOG_WARN, "sub noise for %ld objects: %f sec\n", sources->n, psTimerMark ("psphot.noise"));
     149    }
     150
     151    psFree (cellGroups);
     152
     153    psphotVisualShowImage (readout);
     154
     155    return true;
     156}
     157
     158bool psphotAddOrSubNoise_Threaded (psThreadJob *job) {
     159
     160    psArray *sources = job->args->data[0];
     161    psImageMaskType maskVal = PS_SCALAR_VALUE(job->args->data[1], PS_TYPE_IMAGE_MASK_DATA);
     162    psImageMaskType markVal = PS_SCALAR_VALUE(job->args->data[2], PS_TYPE_IMAGE_MASK_DATA);
     163    psF32 FACTOR = PS_SCALAR_VALUE(job->args->data[3], F32);
     164    psF32 SIZE = PS_SCALAR_VALUE(job->args->data[4], F32);
     165    psBool add  = PS_SCALAR_VALUE(job->args->data[5], U8);
    86166
    87167    // loop over all source
     
    104184        psphotMaskSource (source, add, markVal);
    105185    }
    106     if (add) {
    107         psLogMsg ("psphot.noise", PS_LOG_WARN, "add noise for %ld objects: %f sec\n", sources->n, psTimerMark ("psphot.noise"));
    108     } else {
    109         psLogMsg ("psphot.noise", PS_LOG_WARN, "sub noise for %ld objects: %f sec\n", sources->n, psTimerMark ("psphot.noise"));
    110     }
    111     fprintf (stderr, "masked %d objects\n", Nmasked);
    112 
    113     psphotVisualShowImage (readout);
    114 
    115186    return true;
    116187}
     
    142213        }
    143214    }
    144     Nmasked ++;
    145 
    146     return true;
    147 }
    148 
     215    return true;
     216}
     217
  • branches/eam_branches/ipp-20130509/psphot/src/psphotBlendFit.c

    r34418 r35640  
    8686    if (!status || !isfinite(fitMaxTol) || fitMaxTol <= 0) {
    8787        fitMaxTol = 1.0;
     88    }
     89
     90    bool chisqConvergence = psMetadataLookupBool (&status, recipe, "LMM_FIT_CHISQ_CONVERGENCE"); // Fit tolerance
     91    if (!status) {
     92        // default to the old method (chisqConvergence)
     93        chisqConvergence = true;
     94    }
     95
     96    int gainFactorMode = psMetadataLookupS32 (&status, recipe, "LMM_FIT_GAIN_FACTOR_MODE"); // Fit tolerance
     97    if (!status) {
     98        // default to the old method (chisqConvergence)
     99        gainFactorMode = 0;
    88100    }
    89101
     
    119131    fitOptions->mode          = PM_SOURCE_FIT_PSF;
    120132    fitOptions->covarFactor   = psImageCovarianceFactorForAperture(readout->covariance, 10.0); // Covariance matrix
     133
     134    fitOptions->gainFactorMode = gainFactorMode;
     135    fitOptions->chisqConvergence = chisqConvergence;
    121136
    122137    psphotInitLimitsPSF (recipe, readout);
     
    211226
    212227    psLogMsg ("psphot.psphotBlendFit", PS_LOG_WARN, "fit models: %f sec for %d objects (%d psf, %d ext, %d failed, %ld skipped)\n", psTimerMark ("psphot.fit.nonlinear"), Nfit, Npsf, Next, Nfail, sources->n - Nfit);
     228    psphotFitSummary ();
    213229
    214230    psphotVisualShowResidualImage (readout, false);
     
    271287
    272288        // skip non-astronomical objects (very likely defects)
    273         if (source->mode &  PM_SOURCE_MODE_BLEND) continue;
    274         if (source->mode &  PM_SOURCE_MODE_CR_LIMIT) continue;
    275         if (source->type == PM_SOURCE_TYPE_DEFECT) continue;
    276         if (source->type == PM_SOURCE_TYPE_SATURATED) continue;
     289        if (source->mode &  PM_SOURCE_MODE_BLEND) goto skip_blend;
     290        if (source->mode &  PM_SOURCE_MODE_CR_LIMIT) goto skip_cr;
     291        if (source->type == PM_SOURCE_TYPE_DEFECT) goto skip_defect;
     292        if (source->type == PM_SOURCE_TYPE_SATURATED) goto skip_sat;
    277293
    278294        // skip saturated stars modeled with a radial profile
    279         if (source->mode2 & PM_SOURCE_MODE2_SATSTAR_PROFILE) continue;
     295        if (source->mode2 & PM_SOURCE_MODE2_SATSTAR_PROFILE) goto skip_sat;
    280296
    281297        // skip DBL second sources (ie, added by psphotFitBlob
    282         if (source->mode &  PM_SOURCE_MODE_PAIR) continue;
     298        if (source->mode &  PM_SOURCE_MODE_PAIR) goto skip_blend;
    283299
    284300        // do not include MOMENTS_FAILURES in the fit
    285         if (source->mode & PM_SOURCE_MODE_MOMENTS_FAILURE) continue;
     301        if (source->mode & PM_SOURCE_MODE_MOMENTS_FAILURE) goto skip_generic;
    286302
    287303        // limit selection to some SN limit
    288304        if (source->mode & PM_SOURCE_MODE_EXT_LIMIT) {
    289             if (source->moments->KronFlux < FIT_SN_LIM * source->moments->KronFluxErr) continue;
     305            if (source->moments->KronFlux < FIT_SN_LIM * source->moments->KronFluxErr) goto skip_generic;
    290306        } else {
    291             if (sqrt(source->peak->detValue) < FIT_SN_LIM) continue;
     307            if (sqrt(source->peak->detValue) < FIT_SN_LIM) goto skip_generic;
    292308        }
    293309        // exclude sources outside optional analysis region
    294         if (source->peak->xf < AnalysisRegion.x0) continue;
    295         if (source->peak->yf < AnalysisRegion.y0) continue;
    296         if (source->peak->xf > AnalysisRegion.x1) continue;
    297         if (source->peak->yf > AnalysisRegion.y1) continue;
     310        if (source->peak->xf < AnalysisRegion.x0) goto skip_generic;
     311        if (source->peak->yf < AnalysisRegion.y0) goto skip_generic;
     312        if (source->peak->xf > AnalysisRegion.x1) goto skip_generic;
     313        if (source->peak->yf > AnalysisRegion.y1) goto skip_generic;
    298314
    299315        // if model is NULL, we don't have a starting guess
    300         if (source->modelPSF == NULL) continue;
     316        if (source->modelPSF == NULL) goto skip_generic;
    301317
    302318        // skip sources which are insignificant flux?
     
    307323                     source->modelPSF->params->data.F32[2],
    308324                     source->modelPSF->params->data.F32[3]);
    309             continue;
     325            goto skip_generic;
    310326        }
    311327
     
    357373        pmSourceCacheModel (source, maskVal);
    358374        pmSourceSub (source, PM_MODEL_OP_FULL, maskVal);
     375        continue;
     376
     377    skip_blend:
     378        psTrace ("psphot", 5, "source at %7.1f, %7.1f skipped", source->peak->xf, source->peak->yf);
     379        continue;
     380    skip_cr:
     381        psTrace ("psphot", 5, "source at %7.1f, %7.1f skipped", source->peak->xf, source->peak->yf);
     382        continue;
     383    skip_defect:
     384        psTrace ("psphot", 5, "source at %7.1f, %7.1f skipped", source->peak->xf, source->peak->yf);
     385        continue;
     386    skip_sat:
     387        psTrace ("psphot", 5, "source at %7.1f, %7.1f skipped", source->peak->xf, source->peak->yf);
     388        continue;
     389    skip_generic:
     390        psTrace ("psphot", 5, "source at %7.1f, %7.1f skipped", source->peak->xf, source->peak->yf);
     391        continue;
    359392    }
    360393
  • branches/eam_branches/ipp-20130509/psphot/src/psphotChoosePSF.c

    r34317 r35640  
    158158    }
    159159    float maxChisqDOF = psMetadataLookupF32 (&status, recipe, "PSF_FIT_MAX_CHISQ"); // Fit tolerance
     160
     161    bool chisqConvergence = psMetadataLookupBool (&status, recipe, "LMM_FIT_CHISQ_CONVERGENCE"); // Fit tolerance
     162    if (!status) {
     163        // default to the old method (chisqConvergence)
     164        chisqConvergence = true;
     165    }
     166
     167    int gainFactorMode = psMetadataLookupS32 (&status, recipe, "LMM_FIT_GAIN_FACTOR_MODE"); // Fit tolerance
     168    if (!status) {
     169        // default to the old method (chisqConvergence)
     170        gainFactorMode = 0;
     171    }
    160172
    161173    // options which modify the behavior of the model fitting
     
    169181    options->fitOptions->mode          = PM_SOURCE_FIT_PSF;
    170182    options->fitOptions->covarFactor   = psImageCovarianceFactorForAperture(readout->covariance, 10.0); // Covariance matrix
    171 
    172183   
     184    options->fitOptions->gainFactorMode   = gainFactorMode;
     185    options->fitOptions->chisqConvergence = chisqConvergence;
     186
    173187    psArray *stars = psArrayAllocEmpty (sources->n);
    174188
  • branches/eam_branches/ipp-20130509/psphot/src/psphotExtendedSourceFits.c

    r35634 r35640  
    5353    psTimerStart ("psphot.extended");
    5454
     55    psphotFitInitExtended();
     56
    5557    // find the currently selected readout
    5658    pmFPAfile *file = pmFPAfileSelectSingle(config->files, filerule, index); // File of interest
     
    107109        fitMaxTol = 1.0;
    108110    }
     111
     112    bool chisqConvergence = psMetadataLookupBool (&status, recipe, "LMM_FIT_CHISQ_CONVERGENCE"); // Fit tolerance
     113    if (!status) {
     114        // default to the old method (chisqConvergence)
     115        chisqConvergence = true;
     116    }
     117
     118    int gainFactorMode = psMetadataLookupS32 (&status, recipe, "LMM_FIT_GAIN_FACTOR_MODE"); // Fit tolerance
     119    if (!status) {
     120        // default to the old method (chisqConvergence)
     121        gainFactorMode = 0;
     122    }
     123
     124    // Define source fitting parameters for extended source fits
     125    pmSourceFitOptions *fitOptions = pmSourceFitOptionsAlloc();
     126    fitOptions->mode           = PM_SOURCE_FIT_EXT;
     127    fitOptions->saveCovariance = true;  // XXX make this a user option?
     128    fitOptions->covarFactor    = psImageCovarianceFactorForAperture(readout->covariance, 10.0); // Covariance matrix
     129    fitOptions->nIter          = fitIter;
     130    fitOptions->minTol         = fitMinTol;
     131    fitOptions->maxTol         = fitMaxTol;
     132
     133    fitOptions->gainFactorMode   = gainFactorMode;
     134    fitOptions->chisqConvergence = chisqConvergence;
    109135
    110136    // maskVal is used to test for rejected pixels, and must include markVal
     
    196222            psMetadataIterator *iter = psMetadataIteratorAlloc (models, PS_LIST_HEAD, NULL);
    197223            psArrayAdd(job->args, 1, iter);
    198             psArrayAdd(job->args, 1, AnalysisRegion); // XXX make a pointer
     224            psArrayAdd(job->args, 1, AnalysisRegion);
     225            psArrayAdd(job->args, 1, fitOptions);
    199226
    200227            PS_ARRAY_ADD_SCALAR(job->args, psfSize, PS_TYPE_S32);
    201             PS_ARRAY_ADD_SCALAR(job->args, fitIter, PS_TYPE_S32);
    202             PS_ARRAY_ADD_SCALAR(job->args, fitMinTol, PS_TYPE_F32);
    203             PS_ARRAY_ADD_SCALAR(job->args, fitMaxTol, PS_TYPE_F32);
    204 
    205228            PS_ARRAY_ADD_SCALAR(job->args, maskVal, PS_TYPE_IMAGE_MASK);
    206229            PS_ARRAY_ADD_SCALAR(job->args, markVal, PS_TYPE_IMAGE_MASK);
     
    291314    psLogMsg ("psphot", PS_LOG_INFO, "  %d plain models (%d passed)\n", Nplain, NplainPass);
    292315    psLogMsg ("psphot", PS_LOG_INFO, "  %d too faint to fit, %d failed\n", Nfaint, Nfail);
     316
     317    psphotFitSummaryExtended();
     318
    293319    return true;
    294320}
     
    314340    psMetadataIterator *iter = job->args->data[3];
    315341    psRegion *region        = job->args->data[4];
    316     int psfSize             = PS_SCALAR_VALUE(job->args->data[5],S32);
    317     int fitIter             = PS_SCALAR_VALUE(job->args->data[6],S32);
    318     float fitMinTol         = PS_SCALAR_VALUE(job->args->data[7],F32);
    319     float fitMaxTol         = PS_SCALAR_VALUE(job->args->data[8],F32);
    320     psImageMaskType maskVal = PS_SCALAR_VALUE(job->args->data[9],PS_TYPE_IMAGE_MASK_DATA);
    321     psImageMaskType markVal = PS_SCALAR_VALUE(job->args->data[10],PS_TYPE_IMAGE_MASK_DATA);
    322 
    323     // Define source fitting parameters for extended source fits
    324     pmSourceFitOptions *fitOptions = pmSourceFitOptionsAlloc();
    325     fitOptions->mode           = PM_SOURCE_FIT_EXT;
    326     fitOptions->saveCovariance = true;  // XXX make this a user option?
    327     fitOptions->covarFactor    = psImageCovarianceFactorForAperture(readout->covariance, 10.0); // Covariance matrix
    328     fitOptions->nIter          = fitIter;
    329     fitOptions->minTol         = fitMinTol;
    330     fitOptions->maxTol         = fitMaxTol;
     342    pmSourceFitOptions *fitOptions = job->args->data[5];
     343
     344    int psfSize             = PS_SCALAR_VALUE(job->args->data[6],S32);
     345    psImageMaskType maskVal = PS_SCALAR_VALUE(job->args->data[7],PS_TYPE_IMAGE_MASK_DATA);
     346    psImageMaskType markVal = PS_SCALAR_VALUE(job->args->data[8],PS_TYPE_IMAGE_MASK_DATA);
    331347
    332348    // psTraceSetLevel ("psLib.math.psMinimizeLMChi2_Alt", 5);
     
    540556        psTrace ("psphot", 5, "extended source model for source at %7.1f, %7.1f", source->moments->Mx, source->moments->My);
    541557    }
    542     psFree (fitOptions);
    543558
    544559    // change the value of a scalar on the array (wrap this and put it in psArray.h)
     560    scalar = job->args->data[9];
     561    scalar->data.S32 = Next;
     562
     563    scalar = job->args->data[10];
     564    scalar->data.S32 = Nconvolve;
     565
    545566    scalar = job->args->data[11];
    546     scalar->data.S32 = Next;
     567    scalar->data.S32 = NconvolvePass;
    547568
    548569    scalar = job->args->data[12];
    549     scalar->data.S32 = Nconvolve;
     570    scalar->data.S32 = Nplain;
    550571
    551572    scalar = job->args->data[13];
    552     scalar->data.S32 = NconvolvePass;
     573    scalar->data.S32 = NplainPass;
    553574
    554575    scalar = job->args->data[14];
    555     scalar->data.S32 = Nplain;
     576    scalar->data.S32 = Nfaint;
    556577
    557578    scalar = job->args->data[15];
    558     scalar->data.S32 = NplainPass;
    559 
    560     scalar = job->args->data[16];
    561     scalar->data.S32 = Nfaint;
    562 
    563     scalar = job->args->data[17];
    564579    scalar->data.S32 = Nfail;
    565580
  • branches/eam_branches/ipp-20130509/psphot/src/psphotModelBackground.c

    r34528 r35640  
    2828}
    2929
     30// track background cell failures for log reporting purposes
     31static int nFailures = 0;
    3032
    3133// Generate the background model
     
    3335// linear interpolation to generate full-scale model
    3436//
    35 // NOTE that the 'analysis' metedata pass in here is used to store the binning information.
     37// NOTE that the 'analysis' metedata passed in here is used to store the binning information.
    3638// This may be the analysis for this readout, but it may be the analysis for the pmFPAfile
    3739// corresponding to the model.  Other information about the background model is saved on the
     
    109111
    110112    const psStatsOptions statsOption = statsOptionLocation | statsOptionWidth;
    111     psStats *stats = psStatsAlloc (statsOption);
     113    psStats *statsDefaults = psStatsAlloc (statsOption);
    112114
    113115    // set range for old-version of sky statistic
    114116    if (statsOptionLocation & PS_STAT_ROBUST_QUARTILE) {
    115         stats->min = 0.25;
    116         stats->max = 0.75;
     117        statsDefaults->min = 0.25;
     118        statsDefaults->max = 0.75;
    117119    }
    118120
    119121    // set user-option for number of pixels per region
    120     stats->nSubsample = psMetadataLookupF32 (&status, recipe, "IMSTATS_NPIX");
     122    statsDefaults->nSubsample = psMetadataLookupF32 (&status, recipe, "IMSTATS_NPIX");
    121123    if (!status) {
    122         stats->nSubsample = 1000;
     124        statsDefaults->nSubsample = 1000;
    123125    }
    124126
    125127    // optionally set the binsize
    126     stats->binsize = psMetadataLookupF32 (&status, recipe, "SKY_HISTOGRAM_BINS");
     128    statsDefaults->binsize = psMetadataLookupF32 (&status, recipe, "SKY_HISTOGRAM_BINS");
    127129    if (status) {
    128         stats->options |= PS_STAT_USE_BINSIZE;
     130        statsDefaults->options |= PS_STAT_USE_BINSIZE;
    129131    }
    130132
    131133    // optionally set the sigma clipping
    132     stats->clipSigma = psMetadataLookupF32 (&status, recipe, "SKY_CLIP_SIGMA");
     134    statsDefaults->clipSigma = psMetadataLookupF32 (&status, recipe, "SKY_CLIP_SIGMA");
    133135    if (!status) {
    134         if (stats->options & PS_STAT_FITTED_MEAN) {
    135             stats->clipSigma = 1.0;
     136        if (statsDefaults->options & PS_STAT_FITTED_MEAN) {
     137            statsDefaults->clipSigma = 1.0;
    136138        } else {
    137             stats->clipSigma = 3.0;
     139            statsDefaults->clipSigma = 3.0;
    138140        }
    139141    }
    140 
    141     // stats is not initialized by psStats???  use this to save the input options
    142     // XXX re-work this to use the new psStatsInit function
    143     psStats *statsDefaults = psStatsAlloc (statsOption);
    144     *statsDefaults = *stats;
    145142
    146143    // we save the binning structure for use in psphotMagnitudes
     
    154151
    155152    // XXXX we can thread this here by running blocks in parallel
    156 
    157     int nFailures = 0;
    158153    psImageBackgroundInit();
     154    nFailures = 0; // reset for this pass
    159155
    160156    // we have Nx * Ny model points, but we can use a window which is larger (or smaller) than
     
    163159
    164160    // measure clipped median for subimages
    165     psRegion ruffRegion = psRegionSet (0,0,0,0);
    166     psRegion fineRegion = psRegionSet (0,0,0,0);
    167161    for (int iy = 0; iy < model->numRows; iy++) {
    168162        for (int ix = 0; ix < model->numCols; ix++) {
    169 
    170             // convert the ruff grid cell to the equivalent fine grid cell
    171             ruffRegion = psRegionSet (ix + 0.5 - 0.5*dXsample, ix + 0.5 + 0.5*dXsample,
    172                                       iy + 0.5 - 0.5*dYsample, iy + 0.5 + 0.5*dYsample);
    173             fineRegion = psImageBinningSetFineRegion (binning, ruffRegion);
    174             fineRegion = psRegionForImage (image, fineRegion);
    175 
    176             psImage *subset  = psImageSubset (image, fineRegion);
    177             if (!subset->numCols || !subset->numRows) {
    178                 psFree (subset);
    179                 continue;
     163           
     164            // allocate a job -- if threads are not defined, this just runs the job
     165            psThreadJob *job = psThreadJobAlloc ("PSPHOT_MODEL_BACKGROUND");
     166
     167            psArrayAdd(job->args, 1, image);
     168            psArrayAdd(job->args, 1, mask);
     169            psArrayAdd(job->args, 1, binning);
     170            psArrayAdd(job->args, 1, rng);
     171            psArrayAdd(job->args, 1, statsDefaults);
     172
     173            psArrayAdd(job->args, 1, modelData);
     174            psArrayAdd(job->args, 1, modelStdevData);
     175
     176            PS_ARRAY_ADD_SCALAR(job->args, maskVal,  PS_TYPE_IMAGE_MASK);
     177
     178            PS_ARRAY_ADD_SCALAR(job->args, ix, PS_TYPE_S32);
     179            PS_ARRAY_ADD_SCALAR(job->args, iy, PS_TYPE_S32);
     180
     181            PS_ARRAY_ADD_SCALAR(job->args, dXsample, PS_TYPE_F32);
     182            PS_ARRAY_ADD_SCALAR(job->args, dYsample, PS_TYPE_F32);
     183
     184            PS_ARRAY_ADD_SCALAR(job->args, statsOptionLocation, PS_TYPE_S32);
     185            PS_ARRAY_ADD_SCALAR(job->args, statsOptionWidth, PS_TYPE_S32);
     186
     187            PS_ARRAY_ADD_SCALAR(job->args, NAN, PS_TYPE_F32); // this is used as a return value for dQvalue
     188
     189# if (1)
     190            if (!psThreadJobAddPending(job)) {
     191                psError(PS_ERR_UNKNOWN, false, "Unable to guess model.");
     192                return NULL;
    180193            }
    181             psImage *submask = psImageSubset (mask, fineRegion);
    182 
    183             // reset the default values
    184             *stats = *statsDefaults;
    185 
    186             // Use the selected background statistic for the first pass
    187             // If it fails, fall back on the "ROBUST_MEDIAN" version
    188             // If both fail, set the pixel to NAN and (below) interpolate
    189             // XXX psImageBackground will probably be renamed psImageStats
    190             // XXX don't bother trying if there are no valid pixels...
    191 
    192             psVector *sample = NULL;
    193 
    194             // turn on stats tracing in desired cells
    195             # if (0)
    196             psMetadata *plots = psMetadataLookupPtr (&status, recipe, "DIAGNOSTIC.PLOTS");
    197             assert (plots);
    198 
    199             int xPlot = psMetadataLookupS32 (&status, plots, "IMAGE.BACKGROUND.CELL.HISTOGRAM.X");
    200             assert (status);
    201             int yPlot = psMetadataLookupS32 (&status, plots, "IMAGE.BACKGROUND.CELL.HISTOGRAM.Y");
    202             assert (status);
    203 
    204             bool gotX = (xPlot < 0) || (xPlot == ix);
    205             bool gotY = (yPlot < 0) || (yPlot == iy);
    206 
    207             if (gotX && gotY) {
    208                 (void) psTraceSetLevel ("psLib.math.vectorFittedStats", 6);
    209                 (void) psTraceSetLevel ("psLib.math.vectorRobustStats", 6);
    210             } else {
    211                 (void) psTraceSetLevel ("psLib.math.vectorFittedStats", 0);
    212                 (void) psTraceSetLevel ("psLib.math.vectorRobustStats", 0);
     194# else
     195            if (!psphotModelBackground_Threaded(job)) {
     196                psError(PS_ERR_UNKNOWN, false, "Failure to model background.");
     197                return NULL;
    213198            }
    214             # endif
    215 
    216             if (psImageBackground(stats, &sample, subset, submask, maskVal, rng)) {
    217                 if (stats->options & PS_STAT_ROBUST_QUARTILE) {
    218                     modelData[iy][ix] = stats->robustMedian;
    219                 } else {
    220                     modelData[iy][ix] = psStatsGetValue(stats, statsOptionLocation);
    221                 }
    222                 modelStdevData[iy][ix] = psStatsGetValue(stats, statsOptionWidth);
    223                 // fprintf (stderr, "dQ : %f - %f - %f = %f\n", stats->robustLQ, stats->robustMedian, stats->robustUQ, stats->robustUQ + stats->robustLQ - 2*stats->robustMedian);
    224                 psVectorAppend (dQ, stats->robustUQ + stats->robustLQ - 2*stats->robustMedian);
    225 
    226                 // supply sample to plotting routing
    227                 psphotDiagnosticPlots (config, "IMAGE.BACKGROUND.CELL.HISTOGRAM", ix, iy, modelData[iy][ix], modelStdevData[iy][ix], sample);
    228             } else {
    229                 psStatsOptions currentOptions = stats->options;
    230                 stats->options = PS_STAT_ROBUST_MEDIAN | PS_STAT_ROBUST_STDEV;
    231                 if (!psImageBackground(stats, &sample, subset, submask, maskVal, rng)) {
    232                     if ((nFailures < 3) || (nFailures % 100 == 0)) {
    233                         psLogMsg ("psphot", PS_LOG_WARN, "Failed to estimate background using ROBUST_MEDIAN for "
    234                                   "(%dx%d, (row0,col0) = (%d,%d)",
    235                                   subset->numRows, subset->numCols, subset->row0, subset->col0);
    236                     }
    237                     nFailures ++;
    238                     modelData[iy][ix] = modelStdevData[iy][ix] = NAN;
    239                 } else {
    240                     modelData[iy][ix] = psStatsGetValue (stats, PS_STAT_ROBUST_MEDIAN);
    241                     modelStdevData[iy][ix] = psStatsGetValue(stats, PS_STAT_ROBUST_STDEV);
    242 
    243                     // supply sample to plotting routing
    244                     psphotDiagnosticPlots (config, "IMAGE.BACKGROUND.CELL.HISTOGRAM", ix, iy, modelData[iy][ix], modelStdevData[iy][ix], sample);
    245                 }
    246                 // drop errors caused by psImageBackground failures
    247                 // XXX we probably should trap and exit on serious failures
    248                 psErrorClear();
    249                 stats->options = currentOptions;
    250             }
    251             psFree(sample);
    252             modelData[iy][ix] += SKY_BIAS;
    253             psFree (subset);
    254             psFree (submask);
     199            if (job->args->n < 1) {
     200                fprintf (stderr, "error with job\n");
     201            } else {
     202                psScalar *scalar = job->args->data[14];
     203                float dQvalue = scalar->data.F32;
     204                psVectorAppend (dQ, dQvalue);
     205            }
     206            psFree(job);
     207# endif
    255208        }
     209    }
     210
     211    // wait for the threads to finish and manage results
     212    if (!psThreadPoolWait (false, true)) {
     213        psError(PS_ERR_UNKNOWN, false, "Unable to guess model.");
     214        return NULL;
     215    }
     216
     217    // we have only supplied one type of job, so we can assume the types here
     218    psThreadJob *job = NULL;
     219    while ((job = psThreadJobGetDone()) != NULL) {
     220        if (job->args->n < 1) {
     221            fprintf (stderr, "error with job\n");
     222        } else {
     223            psScalar *scalar = job->args->data[14];
     224            float dQvalue = scalar->data.F32;
     225            psVectorAppend (dQ, dQvalue);
     226        }
     227        psFree(job);
    256228    }
    257229
     
    302274    if (Count == 0) {
    303275        psError (PSPHOT_ERR_DATA, true, "failed to build background image");
    304         psFree(stats);
    305276        psFree(statsDefaults);
    306277        psFree(binning);
     
    318289            modelData[iy][ix] = Value;
    319290            modelStdevData[iy][ix] = ValueStdev;
     291        }
     292    }
     293
     294    // apply artificial offset if desired
     295    for (int iy = 0; iy < model->numRows; iy++) {
     296        for (int ix = 0; ix < model->numCols; ix++) {
     297            modelData[iy][ix] += SKY_BIAS;
    320298        }
    321299    }
     
    364342    psFree(dQ);
    365343
    366     psFree(stats);
    367344    psFree(statsDefaults);
    368345    psFree(binning);
     
    433410    return true;
    434411}
     412
     413bool psphotModelBackground_Threaded (psThreadJob *job) {
     414
     415    psImage *image          = job->args->data[0];
     416    psImage *mask           = job->args->data[1];
     417
     418    psImageBinning *binning = job->args->data[2];
     419
     420    psRandom *rng           = job->args->data[3];
     421    psStats *statsDefaults  = job->args->data[4];
     422
     423    psF32 **modelData       = job->args->data[5];
     424    psF32 **modelStdevData  = job->args->data[6];
     425
     426    psImageMaskType maskVal = PS_SCALAR_VALUE(job->args->data[7],PS_TYPE_IMAGE_MASK_DATA);
     427
     428    int ix                  = PS_SCALAR_VALUE(job->args->data[8],S32);
     429    int iy                  = PS_SCALAR_VALUE(job->args->data[9],S32);
     430
     431    float dXsample          = PS_SCALAR_VALUE(job->args->data[10],F32);
     432    float dYsample          = PS_SCALAR_VALUE(job->args->data[11],F32);
     433
     434    psStatsOptions statsOptionLocation = PS_SCALAR_VALUE(job->args->data[12],S32);
     435    psStatsOptions statsOptionWidth    = PS_SCALAR_VALUE(job->args->data[13],S32);
     436
     437    // convert the ruff grid cell to the equivalent fine grid cell
     438    psRegion ruffRegion = psRegionSet (ix + 0.5 - 0.5*dXsample, ix + 0.5 + 0.5*dXsample, iy + 0.5 - 0.5*dYsample, iy + 0.5 + 0.5*dYsample);
     439    psRegion fineRegion = psImageBinningSetFineRegion (binning, ruffRegion);
     440    fineRegion = psRegionForImage (image, fineRegion);
     441
     442    psImage *subset  = psImageSubset (image, fineRegion);
     443    if (!subset->numCols || !subset->numRows) {
     444        psFree (subset);
     445        return false; // XXX do we / should we fail on this?
     446    }
     447    psImage *submask = psImageSubset (mask, fineRegion);
     448
     449    psStats *stats = psStatsAlloc (PS_STAT_NONE);
     450    *stats = *statsDefaults;
     451
     452    // Use the selected background statistic for the first pass
     453    // If it fails, fall back on the "ROBUST_MEDIAN" version
     454    // If both fail, set the pixel to NAN and (later) interpolate
     455
     456    psVector *sample = NULL;
     457    float dQvalue = NAN;
     458
     459    if (psImageBackground(stats, &sample, subset, submask, maskVal, rng)) {
     460        if (stats->options & PS_STAT_ROBUST_QUARTILE) {
     461            modelData[iy][ix] = stats->robustMedian;
     462        } else {
     463            modelData[iy][ix] = psStatsGetValue(stats, statsOptionLocation);
     464        }
     465        modelStdevData[iy][ix] = psStatsGetValue(stats, statsOptionWidth);
     466
     467        // fprintf (stderr, "dQ : %f - %f - %f = %f\n", stats->robustLQ, stats->robustMedian, stats->robustUQ, stats->robustUQ + stats->robustLQ - 2*stats->robustMedian);
     468        // XXX this operation is not thread safe -- move out somehow...
     469        // psVectorAppend (dQ, stats->robustUQ + stats->robustLQ - 2*stats->robustMedian);
     470        dQvalue = stats->robustUQ + stats->robustLQ - 2*stats->robustMedian;
     471        // return dQvalue to main thread
     472
     473        // supply sample to plotting routing
     474        // only allow in a non-threaded context -- can plot more than one cell
     475        // psphotDiagnosticPlots (config, "IMAGE.BACKGROUND.CELL.HISTOGRAM", ix, iy, modelData[iy][ix], modelStdevData[iy][ix], sample);
     476    } else {
     477        // psStatsOptions currentOptions = stats->options;
     478        stats->options = PS_STAT_ROBUST_MEDIAN | PS_STAT_ROBUST_STDEV;
     479        if (!psImageBackground(stats, &sample, subset, submask, maskVal, rng)) {
     480            if ((nFailures < 3) || (nFailures % 100 == 0)) {
     481                psLogMsg ("psphot", PS_LOG_WARN, "Failed to estimate background using ROBUST_MEDIAN for "
     482                          "(%dx%d, (row0,col0) = (%d,%d)",
     483                          subset->numRows, subset->numCols, subset->row0, subset->col0);
     484            }
     485            nFailures ++; // static
     486            modelData[iy][ix] = modelStdevData[iy][ix] = NAN;
     487        } else {
     488            modelData[iy][ix] = psStatsGetValue (stats, PS_STAT_ROBUST_MEDIAN);
     489            modelStdevData[iy][ix] = psStatsGetValue(stats, PS_STAT_ROBUST_STDEV);
     490
     491            // supply sample to plotting routing
     492            // only allow in a non-threaded context -- can plot more than one cell
     493            // psphotDiagnosticPlots (config, "IMAGE.BACKGROUND.CELL.HISTOGRAM", ix, iy, modelData[iy][ix], modelStdevData[iy][ix], sample);
     494        }
     495        // drop errors caused by psImageBackground failures
     496        // NOTE : psStats raises errors when it cannot find a solution; this
     497        // probably should not be errors but exit stats info only, but c'est la code
     498        // XXX we probably should trap and exit on serious failures
     499        psErrorClear();
     500        // stats->options = currentOptions; // this is not needed (set by init above)
     501    }
     502    psFree (stats);
     503    psFree (sample);
     504    psFree (subset);
     505    psFree (submask);
     506
     507    // return the dQvalue to the calling thread
     508    psScalar *scalar = job->args->data[14];
     509    scalar->data.F32 = dQvalue;
     510
     511    return true;
     512}
     513
     514// code for in-line plotting from above
     515// turn on stats tracing in desired cells
     516// XXX this code may need to be re-worked for a threaded context
     517# if (0)
     518    psMetadata *plots = psMetadataLookupPtr (&status, recipe, "DIAGNOSTIC.PLOTS");
     519    assert (plots);
     520
     521    int xPlot = psMetadataLookupS32 (&status, plots, "IMAGE.BACKGROUND.CELL.HISTOGRAM.X");
     522    assert (status);
     523    int yPlot = psMetadataLookupS32 (&status, plots, "IMAGE.BACKGROUND.CELL.HISTOGRAM.Y");
     524    assert (status);
     525
     526    bool gotX = (xPlot < 0) || (xPlot == ix);
     527    bool gotY = (yPlot < 0) || (yPlot == iy);
     528
     529    if (gotX && gotY) {
     530        (void) psTraceSetLevel ("psLib.math.vectorFittedStats", 6);
     531        (void) psTraceSetLevel ("psLib.math.vectorRobustStats", 6);
     532    } else {
     533        (void) psTraceSetLevel ("psLib.math.vectorFittedStats", 0);
     534        (void) psTraceSetLevel ("psLib.math.vectorRobustStats", 0);
     535    }
     536# endif
  • branches/eam_branches/ipp-20130509/psphot/src/psphotSetThreads.c

    r35559 r35640  
    55    psThreadTask *task = NULL;
    66
     7    pmPSFThreads ();
     8
     9    task = psThreadTaskAlloc("PSPHOT_MODEL_BACKGROUND", 15);
     10    task->function = &psphotModelBackground_Threaded;
     11    psThreadTaskAdd(task);
     12    psFree(task);
     13
    714    task = psThreadTaskAlloc("PSPHOT_GUESS_MODEL", 5);
    815    task->function = &psphotGuessModel_Threaded;
     16    psThreadTaskAdd(task);
     17    psFree(task);
     18
     19    task = psThreadTaskAlloc("PSPHOT_ADD_NOISE", 6);
     20    task->function = &psphotAddOrSubNoise_Threaded;
    921    psThreadTaskAdd(task);
    1022    psFree(task);
     
    4052    psFree(task);
    4153
    42     task = psThreadTaskAlloc("PSPHOT_EXTENDED_FIT", 18);
     54    task = psThreadTaskAlloc("PSPHOT_EXTENDED_FIT", 16);
    4355    task->function = &psphotExtendedSourceFits_Threaded;
    4456    psThreadTaskAdd(task);
  • branches/eam_branches/ipp-20130509/psphot/src/psphotSourceFits.c

    r35630 r35640  
    33// given a source with an existing modelPSF, attempt a full PSF fit, subtract if successful
    44
     5static int NfitBlend = 0;
     6
    57static int NfitPSF = 0;
    6 static int NfitBlend = 0;
     8static int NfitIterPSF = 0;
     9
    710static int NfitDBL = 0;
     11static int NfitIterDBL = 0;
     12static int NfitPixDBL = 0;
     13
    814static int NfitEXT = 0;
     15static int NfitIterEXT = 0;
     16static int NfitPixEXT = 0;
     17
    918static int NfitPCM = 0;
     19static int NfitIterPCM = 0;
     20static int NfitPixPCM = 0;
    1021
    1122bool psphotFitInit (int nThreads) {
     
    1728bool psphotFitSummary () {
    1829
    19     psLogMsg ("psphot.pspsf", PS_LOG_INFO, "fitted %5d psf, %5d blend, %5d ext, %5d dbl : %6.2f sec\n",
    20               NfitPSF, NfitBlend, NfitEXT, NfitDBL, psTimerMark ("psphot.fits"));
     30    psLogMsg ("psphot.pspsf", PS_LOG_INFO, "fitted %5d psf (%d iter), %5d blend: %5d ext (%d iter, %d pix), %5d dbl (%d iter, %d pix) : %6.2f sec\n",
     31              NfitPSF, NfitIterPSF, NfitBlend, NfitEXT, NfitIterEXT, NfitPixEXT, NfitDBL, NfitIterDBL, NfitPixDBL, psTimerMark ("psphot.fits"));
     32    return true;
     33}
     34
     35bool psphotFitSummaryExtended () {
     36
     37    psLogMsg ("psphot.pspsf", PS_LOG_INFO, "fitted %5d ext (%d iter, %d pix), %5d pcm (%d iter, %d pix)\n",
     38              NfitEXT, NfitIterEXT, NfitPixEXT, NfitPCM, NfitIterPCM, NfitPixPCM);
     39    return true;
     40}
     41
     42bool psphotFitInitExtended () {
     43    NfitEXT = 0;
     44    NfitIterEXT = 0;
     45    NfitPixEXT = 0;
     46    NfitPCM = 0;
     47    NfitIterPCM = 0;
     48    NfitPixPCM = 0;
    2149    return true;
    2250}
     
    169197    options.mode = PM_SOURCE_FIT_PSF;
    170198    pmSourceFitModel (source, PSF, &options, maskVal);
     199    NfitIterPSF += PSF->nIter;
    171200
    172201    if (!isfinite(PSF->params->data.F32[PM_PAR_I0])) psAbort("nan in fit");
     
    440469    options.mode = PM_SOURCE_FIT_PSF;
    441470    pmSourceFitSet (source, modelSet, &options, maskVal);
     471    NfitIterDBL += DBL->nIter;
     472    NfitPixDBL += DBL->nDOF;
     473
    442474    return (modelSet);
    443475}
     
    507539
    508540    pmSourceFitModel (source, model, &options, maskVal);
     541    NfitIterEXT += model->nIter;
     542    NfitPixEXT += model->nDOF;
    509543
    510544# if (PS_TRACE_ON)
     
    587621    // psTraceSetLevel("psLib.math.psMinimizeLMChi2", 5);
    588622    pmSourceFitPCM (pcm, source, &options, maskVal, markVal, psfSize);  // NOTE : 1687 allocs in here
     623    NfitIterPCM += pcm->modelConv->nIter;
     624    NfitPixPCM += pcm->modelConv->nDOF;
    589625    if (TIMING) { t5 = psTimerMark ("psphotFitPCM"); }
    590626
Note: See TracChangeset for help on using the changeset viewer.