IPP Software Navigation Tools IPP Links Communication Pan-STARRS Links

Changeset 41649


Ignore:
Timestamp:
Jun 8, 2021, 3:32:17 PM (5 years ago)
Author:
eugene
Message:

merge changes from trunk: relphot updates, optimization build fix, pantasks status option consistency, trange fix

Location:
tags/ipp-ps1-20210510/Ohana
Files:
3 deleted
41 edited
5 copied

Legend:

Unmodified
Added
Removed
  • tags/ipp-ps1-20210510/Ohana

  • tags/ipp-ps1-20210510/Ohana/src/dvomerge/src/myIndex.c

    r39323 r41649  
    1919int myIndexFree (myIndexType *myIndex) {
    2020
     21  if (!myIndex) return TRUE;
    2122  free (myIndex->index);
    2223  free (myIndex);
  • tags/ipp-ps1-20210510/Ohana/src/kapa2/src/bDrawObjects.c

    r41341 r41649  
    211211
    212212  int scaleColor = (object[0].color < 0);
    213   unsigned char *pixel1, *pixel2, *pixel3;
     213  unsigned char *pixel1 = NULL, *pixel2 = NULL, *pixel3 = NULL;
    214214  float *z = object[0].z;
    215215
  • tags/ipp-ps1-20210510/Ohana/src/libdvo/include/dvo.h

    r41469 r41649  
    122122typedef enum {
    123123  ID_MEAS_NOCAL            = 0x00000001,  // detection ignored for this analysis (photcode, time range) -- internal only
    124   ID_MEAS_POOR_PHOTOM      = 0x00000002,  // detection is photometry outlier                                             
    125   ID_MEAS_SKIP_PHOTOM      = 0x00000004,  // detection was ignored for photometry measurement                             
    126   ID_MEAS_AREA             = 0x00000008,  // detection near image edge                                             
     124  ID_MEAS_POOR_PHOTOM      = 0x00000002,  // detection is photometry outlier (DEPRECATED)
     125  ID_MEAS_SKIP_PHOTOM      = 0x00000004,  // detection was ignored for photometry measurement (DEPRECATED)
     126  ID_MEAS_AREA             = 0x00000008,  // detection near image edge -- internal only
    127127  ID_MEAS_POOR_ASTROM      = 0x00000010,  // detection is astrometry outlier                                             
    128128  ID_MEAS_SKIP_ASTROM      = 0x00000020,  // detection was ignored for astrometry measurement                             
     
    185185/* Average.flags values -- these values are 32 bit (as of PS1_V1) */
    186186typedef enum {
    187   ID_OBJ_FEW             = 0x00000001, // used within relphot: skip star
    188   ID_OBJ_POOR            = 0x00000002, // used within relphot: skip star
     187  ID_OBJ_FEW             = 0x00000001, // deprecated (was internal to relphot)
     188  ID_OBJ_POOR            = 0x00000002, // deprecated (was internal to relphot)
    189189
    190190  // NOTE: bits used for object classification:
  • tags/ipp-ps1-20210510/Ohana/src/libdvo/src/convert.c

    r40549 r41649  
    8585  struct tm time;
    8686
     87  time.tm_hour = 0;
     88  time.tm_min  = 0;
     89  time.tm_sec  = 0;
     90
    8791  p = strptime (string, "%H:%M:%S", &time);
    8892  if (p != NULL) goto valid;
  • tags/ipp-ps1-20210510/Ohana/src/opihi/pantasks/status.c

    r15754 r41649  
    1515  }
    1616
    17   if ((N = get_argument (argc, argv, "-taskinfo"))) {
     17  if ((N = get_argument (argc, argv, "-taskinfo")) ||
     18      (N = get_argument (argc, argv, "-info")) ||
     19      (N = get_argument (argc, argv, "-v")) ||
     20      (N = get_argument (argc, argv, "-verbose")) ||
     21      (N = get_argument (argc, argv, "-details"))) {
    1822    remove_argument (N, &argc, argv);
    1923    ListTasks (TRUE);
  • tags/ipp-ps1-20210510/Ohana/src/opihi/pantasks/status_server.c

    r31666 r41649  
    6565    showDetails = TRUE;
    6666  }
     67  if ((N = get_argument (argc, argv, "-taskinfo"))) {
     68    remove_argument (N, &argc, argv);
     69    showDetails = TRUE;
     70  }
    6771  if ((N = get_argument (argc, argv, "-v"))) {
    6872    remove_argument (N, &argc, argv);
  • tags/ipp-ps1-20210510/Ohana/src/relphot

  • tags/ipp-ps1-20210510/Ohana/src/relphot/Makefile

    r41556 r41649  
    3030$(SRC)/ConfigInit.$(ARCH).o      \
    3131$(SRC)/GridOps.$(ARCH).o         \
     32$(SRC)/GridIO.$(ARCH).o  \
     33$(SRC)/ResetOps.$(ARCH).o        \
    3234$(SRC)/ImageOps.$(ARCH).o        \
    3335$(SRC)/ImageSubset.$(ARCH).o     \
     
    3941$(SRC)/Shutdown.$(ARCH).o        \
    4042$(SRC)/StarOps.$(ARCH).o         \
    41 $(SRC)/WarpImageMaps.$(ARCH).o   \
    42 $(SRC)/StackImageMaps.$(ARCH).o  \
    43 $(SRC)/RepairWarpMeasures.$(ARCH).o      \
    44 $(SRC)/myIndex.$(ARCH).o         \
    4543$(SRC)/psps_ids.$(ARCH).o        \
    4644$(SRC)/args.$(ARCH).o            \
     
    9391$(SRC)/ConfigInit.$(ARCH).o      \
    9492$(SRC)/GridOps.$(ARCH).o         \
     93$(SRC)/GridIO.$(ARCH).o  \
     94$(SRC)/ResetOps.$(ARCH).o        \
    9595$(SRC)/ImageOps.$(ARCH).o        \
    9696$(SRC)/ImageSubset.$(ARCH).o     \
     
    102102$(SRC)/Shutdown.$(ARCH).o        \
    103103$(SRC)/StarOps.$(ARCH).o         \
    104 $(SRC)/WarpImageMaps.$(ARCH).o   \
    105 $(SRC)/StackImageMaps.$(ARCH).o  \
    106 $(SRC)/RepairWarpMeasures.$(ARCH).o      \
    107 $(SRC)/myIndex.$(ARCH).o         \
    108104$(SRC)/psps_ids.$(ARCH).o        \
    109105$(SRC)/bcatalog.$(ARCH).o        \
  • tags/ipp-ps1-20210510/Ohana/src/relphot/include/relphot.h

    r41557 r41649  
    55# include <pthread.h>
    66
    7 /* # define GRID_V1 */
    8 # define GRID_V2
    9 # define NO_IMAGE -100
    10 
    117# define ID_SECF_STACK_PRIMARY 0x00004000
    128
    139# define NBOOTSTRAP 100
     10
     11// MEAS_BAD is used in ImageOps.c, MosaicOps.c, TGroupOps.c to skip specific measurements.
     12// ID_MEAS_AREA is raised for measurements outside the user-specified region of the chips
     13// ID_MEAS_NOCAL is raised for measurements outside the valid time range or for inactive photcodes
     14// Note: these bits are only raised on the temporary MeasureTiny elements and are not saved
     15// to the database files.
     16# define MEAS_BAD (ID_MEAS_AREA | ID_MEAS_NOCAL)
    1417
    1518# ifndef MAX_INT
     
    5356
    5457typedef enum {
    55     MODE_NONE   = 0,
    56     MODE_LOAD   = 1,
    57     MODE_UPDATE = 2,
     58    MODE_NONE           = 0,
     59    MODE_LOAD           = 1,
     60    MODE_UPDATE         = 2,
    5861    MODE_UPDATE_OBJECTS = 3,
    59     MODE_SYNTH_PHOT = 4,
     62    MODE_SYNTH_PHOT     = 4,
    6063} ModeType;
    6164
     
    7073  PS1_w = 6,
    7174} PS1filters;
     75
     76typedef enum {
     77  GRID_MEAN = 0,
     78  GRID_STDEV = 1,
     79  GRID_NPTS = 2,
     80} GridOutputMode;
    7281
    7382typedef struct {
     
    99108  char skipCal;               // if TRUE, this mosaic is incomplete and should not be calibrated
    100109  char inTGroup;
    101   Coords coords;
     110  Coords coords;              // this is only used to set the mosaic center for assign_images used by region hosts
    102111} Mosaic;
    103112
     
    140149  int      nCode;
    141150} TGTimes;
     151
     152typedef struct {
     153  unsigned short photcode;
     154  float **Mgrid; // grid of average corrections
     155  float **dMgrid; // grid of stdev of corrections
     156    int **nMgrid; // grid of number of stars for corrections
     157  int Nx; // bin = int(Xchip * (Nx / NxChip))
     158  int Ny; // bin = int(Ychip * (Ny / NyChip))
     159  float dX; // bin = int(Xchip * dX), dX = Nx / NxChip
     160  float dY; // bin = int(Ychip * dY), dY = Ny / NyChip
     161  // NxChip, NyChip = 4900,4900 for now
     162} GridCorrectionType;
    142163
    143164typedef enum {
     
    366387int    SKY_DEPTH;  /** XXX EAM : depth of catalog tables, fix usage */
    367388char  *SYNTH_ZERO_POINTS;
     389char  *GRID_MEANFILE;
    368390
    369391// globals for parallel region operations
     
    389411double IMAGE_OFFSET;
    390412double NIGHT_SCATTER;
    391 double NIGHT_OFFSET;
     413double NIGHT_CHISQ;
     414double MOSAIC_SCATTER;
     415double MOSAIC_CHISQ;
    392416double STAR_SCATTER;
    393417double STAR_CHISQ;
     
    413437int    MOSAIC_ZEROPT;
    414438int    TGROUP_ZEROPT;
     439int    GRID_ZEROPT;
     440
     441int    GRID_BIN_HSC;
     442int    GRID_BIN_CFH;
     443int    GRID_BIN_GPC1;
     444int    GRID_BIN_GPC2;
    415445
    416446int    FREEZE_IMAGES;
     
    424454int    MANUAL_ITERATION;
    425455int    NLOOP;
    426 int    NGRID;
    427456int    RESET;
    428457int    RESET_ZEROPTS;
     458int    RESET_FLATCORR;
    429459int    REPAIR_WARPS;
    430460int    PRESERVE_PS1;
     461int    REQUIRE_PSFFIT;
    431462int    UPDATE;
    432463int    SAVE_IMAGE_UPDATES;
     
    436467char   MOSAICNAME[256];
    437468char   STATMODE[32];
    438 int    STAR_BAD;
    439 int    MEAS_BAD;
    440469int    STAR_TOOFEW;
    441470int    GRID_TOOFEW;
    442471int    IMAGE_TOOFEW;
    443472double IMAGE_GOOD_FRACTION;
    444 int    IMAGE_BAD;
    445473int    CALIBRATE_STACKS_AND_WARPS;
    446 int    USE_GRID;
     474
    447475int    KEEP_UBERCAL;
    448476char  *OUTROOT;
     
    457485char  *PhotcodeList;
    458486
    459 int    RELPHOT_GRID_X;
    460 int    RELPHOT_GRID_Y;
    461 int    RELPHOT_GRID_BINNING;
    462 
    463487int      *photseclist;
    464488int      Nphotcodes;
     
    490514char *UserCatalog;
    491515
     516enum {GRID_ZPT_MODE_NONE, GRID_ZPT_MODE_ALL, };
     517int GRID_ZPT_MODE;
     518
    492519enum {TGROUP_ZPT_MODE_NONE, TGROUP_ZPT_MODE_GOOD_NIGHT, TGROUP_ZPT_MODE_ALL, };
    493520int TGROUP_ZPT_MODE;
     
    504531
    505532RelphotStages STAGES;
    506 
    507 # ifdef GRID_V1
    508 int setGridMeasure (off_t meas, int cat, double X, double Y);
    509 # endif
    510 
    511 # ifdef GRID_V2
    512 int setGridMeasure (off_t meas, int cat, double X, double Y, int ccdnum);
    513 # endif
    514533
    515534/*** relphot prototypes ***/
     
    523542int           bcatalog            PROTO((Catalog *subcatalog, Catalog *catalog, int Ncat));
    524543void          clean_images        PROTO((void));
    525 void          clean_measures      PROTO((Catalog *catalog, int Ncatalog, int final, FlatCorrectionTable *flatcorr));
     544void          clean_measures      PROTO((Catalog *catalog, int Ncatalog, int final));
    526545void          clean_mosaics       PROTO((void));
    527546void          clean_tgroups       PROTO((void));
     
    549568int SetSignals (void);
    550569
    551 void          freeGridBins        PROTO((int Ncatalog));
     570void          freeGridBins        PROTO((void));
    552571void          freeImageBins       PROTO((int Ncatalog, int doImageList));
    553572void          freeMosaicBins      PROTO((int Ncatalog, int doMosaicList));
     
    560579
    561580float         getMcal             PROTO((off_t meas, int cat, dvoMagClassType class));
    562 float         getMflat            PROTO((off_t meas, int cat, FlatCorrectionTable *flatcorr, Catalog *catalog));
    563 float         getMgrid            PROTO((off_t meas, int cat));
     581float         getMflat            PROTO((off_t meas, int cat, Catalog *catalog));
     582float         getMgridTiny        PROTO((MeasureTiny *measure));
     583float         getMgrid            PROTO((Measure *measure));
    564584float         getMmos             PROTO((off_t meas, int cat));
    565585float         getMgrp             PROTO((off_t meas, int cat, float airmass, float *dZpt));
     
    570590Image        *getimages           PROTO((off_t *N, off_t **LineNumber));
    571591ImageSubset  *getimages_subset    PROTO((off_t *N));
    572 void          global_stats        PROTO((Catalog *catalog, int Ncatalog, FlatCorrectionTable *flatcorr, int nloop));
    573 void          initGrid            PROTO((int dX, int dY));
    574 void          initGridBins        PROTO((Catalog *catalog, int Ncatalog));
     592void          global_stats        PROTO((Catalog *catalog, int Ncatalog, int nloop));
     593void          initGrid            PROTO((void));
     594void          setMflatFromGrid    PROTO((Catalog *catalog));
     595void          initGridBins        PROTO((void));
     596GridCorrectionType *getGridCorrByCode PROTO((int code));
     597GridCorrectionType *getGridCorrNext   PROTO((int *Nlast));
     598int           GridCorrectionSave  PROTO((void));
     599int           GridCorrectionSaveFile  PROTO((char *filename, GridOutputMode mode));
     600void          GridCorrectionLoad  PROTO((char *filename));
    575601void          initImageBins       PROTO((Catalog *catalog, int Ncatalog, int doImageList));
    576602void          initImagesSubset    PROTO((ImageSubset *input, off_t *line_number, off_t N));
    577603void          initImages          PROTO((Image *input, off_t *LineNumber, off_t N));
    578604void          initMosaicBins      PROTO((Catalog *catalog, int Ncatalog, int doMosaicList));
    579 void          initMosaicGrid      PROTO((Image *image, off_t Nimage));
     605void          initMosaicMcal      PROTO((Image *image, off_t Nimage));
    580606void          initMosaics         PROTO((Image *subset, off_t Nsubset, Image *image, char *inSubset, off_t Nimage));
    581607void          initTGroups         PROTO((Image *subset, off_t Nsubset));
     
    621647void          plot_chisq          PROTO((Catalog *catalog, int Ncatalog));
    622648void          plot_defaults       PROTO((Graphdata *graphdata));
    623 void          plot_grid           PROTO((Catalog *catalog, FlatCorrectionTable *flatcorr));
    624649void          plot_images         PROTO((void));
    625650void          plot_list           PROTO((Graphdata *graphdata, double *xlist, double *ylist, int N, char *label, char *format, ...) OHANA_FORMAT(printf, 6, 7) );
    626651void          plot_mosaic_fields  PROTO((Catalog *catalog));
    627652void          plot_mosaics        PROTO((void));
    628 void          plot_scatter        PROTO((Catalog *catalog, int Ncatalog, FlatCorrectionTable *flatcorr));
     653void          plot_scatter        PROTO((Catalog *catalog, int Ncatalog));
    629654void          plot_star_coords    PROTO((Catalog *catalog, int Ncatalog));
    630655void          plot_stars          PROTO((Catalog *catalog, int Ncatalog));
     
    635660int           open_graph          PROTO((int N));
    636661
    637 void          reload_catalogs     PROTO((SkyList *skylist, FlatCorrectionTable *flatcorr, int hostID, char *hostpath));
     662void          reload_catalogs     PROTO((SkyList *skylist, int hostID, char *hostpath));
    638663int           reload_catalogs_parallel PROTO((SkyList *sky));
    639664int           reload_images       PROTO((FITS_DB *db));
    640665int           setExclusions       PROTO((Catalog *catalog, int Ncatalog, int verbose));
    641 void          setMgrid            PROTO((Catalog *catalog, FlatCorrectionTable *flatcorr));
     666void          setMgrid            PROTO((Catalog *catalog, int Ncatalog));
     667void          resetMgrid          PROTO((void));
     668
    642669void          setMcalFromMosaics  PROTO((void));
    643670void          setMcalFromTGroups  PROTO((void));
    644 int           setMcalOutput       PROTO((Catalog *catalog, int Ncatalog, FlatCorrectionTable *flatcorr));
    645 
    646 void          setMcal             PROTO((Catalog *catalog, FlatCorrectionTable *flatcorr));
    647 int           setMmos             PROTO((Catalog *catalog, FlatCorrectionTable *flatcorr));
    648 int           setMgrp             PROTO((Catalog *catalog, FlatCorrectionTable *flatcorr));
    649 
    650 int           setMrel             PROTO((Catalog *catalog, int Ncatalog, FlatCorrectionTable *flatcorr));
    651 void          setMrelFinal        PROTO((Catalog *catalog, FlatCorrectionTable *flatcorr, int simpleAverage));
    652 int           setMrelOutput       PROTO((Catalog *catalog, int Ncatalog, FlatCorrectionTable *flatcorr));
    653 
    654 void          setMcalTest         PROTO((Catalog *catalog, FlatCorrectionTable *flatcorr));
     671int           setMcalOutput       PROTO((Catalog *catalog, int Ncatalog));
     672
     673void          setMcal             PROTO((Catalog *catalog));
     674int           setMmos             PROTO((Catalog *catalog));
     675int           setMgrp             PROTO((Catalog *catalog));
     676
     677int           setMrel             PROTO((Catalog *catalog, int Ncatalog));
     678void          setMrelFinal        PROTO((Catalog *catalog, int simpleAverage));
     679int           setMrelOutput       PROTO((Catalog *catalog, int Ncatalog));
     680
     681void          setMcalTest         PROTO((Catalog *catalog));
    655682
    656683int           setMave             PROTO((Catalog *catalog, int Ncatalog));
    657684void          set_ZP              PROTO((double ZERO));
    658685int           setrefcode          PROTO((Image *image, off_t Nimage));
    659 void          skip_measurements   PROTO((Catalog *catalog, int pass, FlatCorrectionTable *flatcorr));
     686void          skip_measurements   PROTO((Catalog *catalog, int pass));
    660687void          sortA               PROTO((double *X, int N));
    661688void          sortB               PROTO((double *X, double *Y, int N));
     
    663690void          sortD               PROTO((double *X, double *Y, double *Z, int N));
    664691StatType      statsImageM         PROTO((Catalog *catalog));
    665 StatType      statsImageN         PROTO((Catalog *catalog, FlatCorrectionTable *flatcorr));
     692StatType      statsImageN         PROTO((Catalog *catalog));
    666693StatType      statsImageX         PROTO((Catalog *catalog));
    667694StatType      statsImagedM        PROTO((Catalog *catalog));
    668695StatType      statsMosaicM        PROTO((Catalog *catalog));
    669 StatType      statsMosaicN        PROTO((Catalog *catalog, FlatCorrectionTable *flatcorr));
     696StatType      statsMosaicN        PROTO((Catalog *catalog));
    670697StatType      statsMosaicX        PROTO((Catalog *catalog));
    671698StatType      statsMosaicdM       PROTO((Catalog *catalog));
     
    674701StatType      statsTGroupdM       PROTO((Catalog *catalog));
    675702
    676 StatType      statsStarN          PROTO((Catalog *catalog, int Ncatalog, int Nsec, int seccode, FlatCorrectionTable *flatcorr));
     703StatType      statsStarN          PROTO((Catalog *catalog, int Ncatalog, int Nsec, int seccode));
    677704StatType      statsStarS          PROTO((Catalog *catalog, int Ncatalog, int Nsec));
    678705StatType      statsStarX          PROTO((Catalog *catalog, int Ncatalog, int Nsec));
     
    720747
    721748int print_measure_set_alt (Average *average, SecFilt *secfilt, Measure *measure);
    722 int setMrel_catalog_alt (Catalog *catalog, int Nc, int isSetMrelFinal, FlatCorrectionTable *flatcorr, SetMrelInfo *results, int Nsecfilt);
    723 int setMrelAverageExposure (Catalog *catalog, int cat, off_t ave, int Nsecfilt, int isSetMrelFinal, FlatCorrectionTable *flatcorr, SetMrelInfo *results);
    724 int setMrelAverageStack (Catalog *catalog, int cat, off_t ave, int Nsecfilt, FlatCorrectionTable *flatcorr);
    725 int setMrelAverageForcedWarp (Catalog *catalog, int cat, off_t ave, int Nsecfilt, FlatCorrectionTable *flatcorr, SetMrelInfo *results);
     749
     750// in setMrelCatalog.c:
     751int setMrelCatalog (Catalog *catalog, int Nc, int isSetMrelFinal, SetMrelInfo *results, int Nsecfilt);
     752int setMrelAverageExposure (Catalog *catalog, int cat, off_t ave, int Nsecfilt, int isSetMrelFinal, SetMrelInfo *results);
     753int setMrelAverageStack (Catalog *catalog, int cat, off_t ave, int Nsecfilt);
     754int setMrelAverageForcedWarp (Catalog *catalog, int cat, off_t ave, int Nsecfilt, SetMrelInfo *results);
    726755
    727756int setGlobalObjStats (Average *average, Measure *measure);
     
    735764StatDataSet *StatDataSetAlloc (int Nsecfilt, int Nmax);
    736765
    737 int init_synthetic_mags ();
     766int init_synthetic_mags (void);
    738767int add_synthetic_mags (AverageTiny *average, SecFilt *secfilt, MeasureTiny *measure, off_t *Nmeasure, off_t *Nm);
    739768
     
    796825
    797826int SynthZeroPointsLoad (char *filename);
    798 SynthZeroPoints *SynthZeroPointsGet ();
     827SynthZeroPoints *SynthZeroPointsGet (void);
    799828
    800829int relphot_synthphot (SkyList *sky, int hostID, char *hostpath);
     
    815844
    816845void put_astrom_table (AstromOffsetTable *myTable);
    817 void free_astrom_table ();
    818 
    819 int RepairWarpMeasures (Catalog *catalog);
    820 
    821 int FindWarpGroups (void);
    822 int GetWarpSeq (Image *image, int obstime, unsigned short photcode, double Rave, double Dave, float X, float Y);
    823 void FreeWarpGroups (void);
    824 
    825 myIndexType *myIndexInit ();
    826 int myIndexFree (myIndexType *myIndex);
    827 int myIndexUpdateLimits (myIndexType *myIndex, int value);
    828 int myIndexSetRange (myIndexType *myIndex);
    829 int myIndexSetEntry (myIndexType *myIndex, int value, int entry);
    830 int myIndexGetEntry (myIndexType *myIndex, int value);
     846void free_astrom_table (void);
    831847
    832848uint64_t CreatePSPSObjectID(double ra, double dec);
     
    834850uint64_t CreatePSPSDetectionID(double tobs, int ccdid, int detID);
    835851
    836 int MakeStackIndex (void);
    837 void FreeStackGroups (void);
    838 int GetStackSeq (Image *image, double Rstk, double Dstk, unsigned short photcode, float X, float Y);
    839852void sort_by_ra (double *R, double *D, int *I, int *S, int N);
    840 
    841 void RepairWarpMeasuresOpenLogfile ();
    842 void RepairWarpMeasuresCloseLogfile ();
    843853
    844854void dump_tgroups (Catalog *catalog, int Npass);
     
    849859int GetZptIteration (void);
    850860
    851 void SetZeroPointModes (void);
     861void SetZeroPointModes (Catalog *catalog, int Ncatalog);
    852862int UseStandardOLS (ZptFitModeType mode);
    853863int GetActivePhotcodeIndex (int photcode);
     
    857867
    858868int MagResidSave(char *filename, Catalog *catalog);
     869
     870void ResetAverageAndMeasure (Catalog *catalog);
     871void ResetAverageObjects (Catalog *catalog);
     872void ResetImages (Image *subset, off_t Nsubset);
     873void ResetMeasureZeroPoints (MeasureTiny *measure, off_t Nmeasure, off_t Ncat);
     874void ResetAverageActivePhotcodes (SecFilt *secfilt);
     875
     876
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/BrightCatalog.c

    r40291 r41649  
    1212  myAssert (!strcmp(type, #TYPE), "wrong column type");
    1313
    14 // XXX double check the header extname values for each table
    15 // XXX make sure we free things as we can
    16 // XXX make sure we close files as we can
    17 // XXX handle free and close on error return as well
    1814BrightCatalog *BrightCatalogLoad(char *filename) {
    1915
     
    622618int BrightCatalogSplitFree (CatalogSplitter *catalogs) {
    623619
    624   // XXX don't free the catalogs :
    625   // for (i = 0; i < NCATALOG; i++) {
    626   //   free (catalogs->catalog[i].averageT);
    627   //   free (catalogs->catalog[i].measureT);
    628   //   free (catalogs->catalog[i].secfilt);
    629   // }
    630   // free (catalogs->catalog);
    631 
     620  // don't free the catalogs : free elsewhere
    632621  free (catalogs->catIDs);
    633622  free (catalogs->NAVERAGE);
     
    652641    catIDmax = MAX(catIDmax, bcatalog->average[i].catID);
    653642  }
    654   // XXX validate the measure ID range here
    655643   
    656644  int maxIDold = catalogs->maxID;
     
    746734
    747735  // assign the measures to the corresponding catalog
    748   // XXX what about averef and related links?  Do I need them?
    749736  for (i = 0; i < bcatalog->Nmeasure; i++) {
    750737    int ID = bcatalog->measure[i].catID;
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/ConfigInit.c

    r41453 r41649  
    2626  GetConfig (config, "SIGMA_LIM",              "%lf", 0, &SIGMA_LIM);
    2727
     28  DefConfig ("STAR_SCATTER",                    "%lf",  0.1, STAR_SCATTER);
     29  DefConfig ("STAR_CHISQ",                      "%lf", 10.0, STAR_CHISQ);
    2830
    29   GetConfig (config, "STAR_SCATTER",           "%lf", 0, &STAR_SCATTER);
     31  DefConfig ("NIGHT_SCATTER",                   "%lf",  0.1, NIGHT_SCATTER);
     32  DefConfig ("NIGHT_CHISQ",                     "%lf", 10.0, NIGHT_CHISQ);
     33
     34  DefConfig ("MOSAIC_SCATTER",                  "%lf",  0.1, MOSAIC_SCATTER);
     35  DefConfig ("MOSAIC_CHISQ",                    "%lf", 10.0, MOSAIC_CHISQ);
    3036
    3137  GetConfig (config, "IMAGE_SCATTER",          "%lf", 0, &IMAGE_SCATTER);
    3238  GetConfig (config, "IMAGE_OFFSET",           "%lf", 0, &IMAGE_OFFSET);
    3339
    34   GetConfig (config, "STAR_CHISQ",             "%lf", 0, &STAR_CHISQ);
    3540  GetConfig (config, "GRID_TOOFEW",            "%d",  0, &GRID_TOOFEW);
    3641  GetConfig (config, "STAR_TOOFEW",            "%d",  0, &STAR_TOOFEW);
     
    5459
    5560  DefConfig ("RELPHOT_IMFIT_SYS_SIGMA_LIM", "%lf", 0.01, IMFIT_SYS_SIGMA_LIM);
    56   DefConfig ("NIGHT_SCATTER",               "%lf", 0.05, NIGHT_SCATTER);
    57   DefConfig ("NIGHT_OFFSET",                "%lf", 0.50, NIGHT_OFFSET);
    5861  DefConfig ("SKY_DEPTH",                   "%d",     2, SKY_DEPTH);
    5962
     
    6366
    6467  GetConfig (config, "ZERO_PT",                "%lf", 0, &ZERO_POINT);
    65 
    66   GetConfig (config, "RELPHOT_GRID_X",         "%d",  0, &RELPHOT_GRID_X);
    67   GetConfig (config, "RELPHOT_GRID_Y",         "%d",  0, &RELPHOT_GRID_Y);
    68   GetConfig (config, "RELPHOT_GRID_BINNING",   "%d",  0, &RELPHOT_GRID_BINNING);
    6968  GetConfig (config, "CAMERA_CONFIG",          "%s",  0, CameraConfig);
    7069  GetConfig (config, "MOSAICNAME",             "%s",  0, MOSAICNAME);
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/GridOps.c

    r41462 r41649  
    11# include "relphot.h"
    22
    3 enum {
    4     GRID_FITTED,
    5     GRID_FROZEN,
    6     GRID_REFERENCE,
    7 };
    8 
    9 static int     Ngrid;  // number of grid elements (gridX * gridY)
    10 static float   *gridM; // magnitude offset for this grid cell
    11 static float   *gridS; // stdev of the magnitude offset for this grid cell
    12 static int     *gridN; // number of stars used to measure the magnitude offset for this grid cell
    13 static int     *gridV; // data mode for this cell: fitted, frozen, reference
    14 static int      gridX; // number of grid elements in X direction
    15 static int      gridY; // number of grid elements in Y direction
    16 
    17 static int    **bin;   // link from catalog, measure to grid element
    18 static int    **Xmeas; // grid x-coordinate for a measurement
    19 static int    **Ymeas; // grid y-coordinate for a measurement
    20 
    21 static int    **clist; // link from measurement on a cell to catalog containing measurement
    22 static off_t  **mlist; // link from measurement on a cell to measurement in a catalog
    23 static off_t   *Nlist; // number of measurements for each grid cell
    24 static off_t   *NLIST; // allocated number of measurements for each grid cell
    25 
    26 static struct {
    27   int Nchip;
    28   int Mx, My;  /* mosaic size in chips */
    29   int Nx, Ny;  /* chip size in pixels */
    30   int *Fx, *Fy;  /* chip flip */
    31   int *Ox, *Oy;  /* chip offset */
    32   int *valid;
    33   char **ccdname;
    34 } camera;   
    35 
    36 static int *ccdnum;
    37 static char *config;
    38 
    39 void initGrid (int dX, int dY) {
    40   OHANA_UNUSED_PARAM(dX);
    41   OHANA_UNUSED_PARAM(dY);
    42 
    43   int i, N, ccdnum_max, refX, refY, refBin;
    44   char *p, field[64], line[256];
    45   int *Fx, *Fy;  /* chip flip */
    46   int *Ox, *Oy;  /* chip offset */
    47   char **ccdname;
    48 
    49   /* load camera config file */
    50   config = LoadConfigFile (CameraConfig);
    51   if (config == (char *) NULL) {
    52     fprintf (stderr, "ERROR: can't find camera config file %s\n", CameraConfig);
    53     exit (1);
    54   }
    55 
    56   /* load basic mosaic parameters */
    57   ScanConfig (config, "NCCD", "%d", 1, &camera.Nchip);
    58   ScanConfig (config, "MOSAIC_X", "%d", 1, &camera.Mx);
    59   ScanConfig (config, "MOSAIC_Y", "%d", 1, &camera.My);
    60   ScanConfig (config, "NAXIS1", "%d", 1, &camera.Nx);
    61   ScanConfig (config, "NAXIS2", "%d", 1, &camera.Ny);
    62 
    63   ScanConfig (config, "REFCELL.X", "%d", 1, &refX);
    64   ScanConfig (config, "REFCELL.Y", "%d", 1, &refY);
    65 
    66   // temporary storage
    67   ALLOCATE (Fx,      int,    camera.Nchip);
    68   ALLOCATE (Fy,      int,    camera.Nchip);
    69   ALLOCATE (Ox,      int,    camera.Nchip);
    70   ALLOCATE (Oy,      int,    camera.Nchip);
    71   ALLOCATE (ccdname, char *, camera.Nchip);
    72   ALLOCATE (ccdnum,  int,    camera.Nchip);
    73 
    74   /* load per-chip parameters */
    75   for (i = 0; i < camera.Nchip; i++) {
    76     ALLOCATE (ccdname[i], char, 256);
    77     sprintf (field, "CCD.%d", i);
    78     ScanConfig (config, field, "%s", 1, line);
    79     // XXX get error status!
    80 
    81     sscanf (line, "%s %d %d %d %d", ccdname[i], &Ox[i], &Oy[i], &Fx[i], &Fy[i]);
     3/*
     4   We define a 'grid correction', essentially the flat-field correction, as a correction per
     5   photcode subdivided into an NxN array.  The dimensions of the chips corresponding to a
     6   photcode will need to be added to the photcode table.  This means a schema update,
     7   which I detest.  For now (2021.05.16), I will hard-wire the GPC1 / GPC2 chip size and
     8   worry about HSC & Megacam in the future.
     9
     10   We have a collection of photcodes, with photcodeID limited by design to 64k (unsigned short).
     11   
     12   Thus we can generate an array of pointers to the grid correction structures and access them
     13   by photcode.
     14
     15
     16 */
     17
     18static GridCorrectionType **GridCorr = NULL;
     19static int                 NGridCorr = 0;
     20
     21# if (0)
     22/* PS1 / PS2 values */
     23# define NX_CHIP 4900
     24# define NY_CHIP 4900
     25# define NX_BIN 16
     26# define NY_BIN 16
     27# endif
     28
     29/* test values */
     30# define NX_CHIP_DEFAULT 1000
     31# define NY_CHIP_DEFAULT 1000
     32# define NX_BIN_DEFAULT 2
     33# define NY_BIN_DEFAULT 2
     34
     35void initGridBins (void) {
     36
     37  // allocate the full possible range of GridCorrectionType pointers, Nphotcode
     38  // loop over all images to find actual existing photcodes
     39  // generate initial grid values for each existing photcode
     40
     41  if (!GRID_ZEROPT) return; // skip if we are ignoring the grid correction
     42
     43  if (GridCorr) return;
     44
     45  PhotCodeData *photcodes = GetPhotcodeTable();
     46  if (!photcodes) return;
     47
     48  // we have photcodes->Ncodes actually loaded.  loop over them and allocate
     49  // array only as large as the max photcodes->code[i].code
     50
     51  int maxCode = 0;
     52  for (int i = 0; i < photcodes->Ncode; i++) {
     53    maxCode = MAX(maxCode, photcodes->code[i].code);
     54    myAssert (maxCode < 0x10000, "oops");
     55  }
     56
     57  NGridCorr = maxCode + 1;
     58  ALLOCATE (GridCorr, GridCorrectionType *, NGridCorr);
     59  for (int i = 0; i < NGridCorr; i++) {
     60    GridCorr[i] = NULL;
     61  }
     62
     63  fprintf (stderr, "Generating grid corrections for %d photcodes\n", NGridCorr);
     64  return;
     65}
     66
     67void freeGridBins() {
     68
     69  if (!GridCorr) return;
     70
     71  for (int code = 0; code < NGridCorr; code++) {
     72    if (!GridCorr[code]) continue;
     73
     74    for (int ix = 0; ix < GridCorr[code]->Nx; ix++) {
     75      FREE (GridCorr[code]-> Mgrid[ix]);
     76      if (GridCorr[code]->dMgrid) FREE (GridCorr[code]->dMgrid[ix]);
     77      if (GridCorr[code]->nMgrid) FREE (GridCorr[code]->nMgrid[ix]);
     78    }     
     79
     80    FREE (GridCorr[code]-> Mgrid);
     81    FREE (GridCorr[code]->dMgrid);
     82    FREE (GridCorr[code]->nMgrid);
     83
     84    FREE(GridCorr[code]);
     85  }
     86
     87  FREE (GridCorr);
     88  GridCorr = NULL;
     89
     90  return;
     91}
     92
     93GridCorrectionType *getGridCorrNext (int *Nlast) {
     94
     95  if (GridCorr == NULL) return NULL;
     96
     97  if (*Nlast >= NGridCorr) return NULL;
     98
     99  if (*Nlast < 0) *Nlast = -1;
     100
     101  GridCorrectionType *result = NULL;
     102  for (int i = *Nlast + 1; i < NGridCorr; i++) {
     103    if (GridCorr[i] == NULL) continue;
     104    result = GridCorr[i];
     105    *Nlast = i;
     106    break;
     107  }
     108  return result;
     109}
     110
     111GridCorrectionType *getGridCorrByCode (int code) {
     112
     113  if (GridCorr == NULL) return NULL;
     114
     115  if (code >= NGridCorr) return NULL;
     116  if (code <          0) return NULL;
     117
     118  ALLOCATE(GridCorr[code], GridCorrectionType, 1)
     119  GridCorrectionType *result = GridCorr[code];
     120  return result;
     121}
     122
     123/* for GPC1, we have 60 chips, 5 filters, 16x16 grid cells = 2MB of memory for this stuff
     124   if we go to 64x64 grid cells (~75 pixels), then it is still only 29MB */
     125void initGrid (void) {
     126
     127  if (!GRID_ZEROPT) return;
     128
     129  off_t Nimages = 0;
     130  Image *images = getimages (&Nimages, NULL);
     131
     132  int NGridReal = 0;
     133
     134  for (int i = 0; i < Nimages; i++) {
     135    int code = images[i].photcode;
     136    myAssert (code >= 0, "oops");
     137    myAssert (code < NGridCorr, "oops");
    82138   
    83     p = ccdname[i];
    84     while (!isdigit(*p) && *p) p++;
    85     if (*p == 0) continue;
    86     ccdnum[i] = atoi (p);
    87   }
    88 
    89   /* we now have the parameters loaded into a minimal length list; reshuffle to the a list of length 0 - MAX(ccdnum) */
    90   ccdnum_max = 0;
    91   for (i = 0; i < camera.Nchip; i++) {
    92     ccdnum_max = MAX(ccdnum_max, ccdnum[i]);
    93   }
    94   ccdnum_max ++;
    95 
    96   if (ccdnum_max < camera.Nchip) {
    97     fprintf (stderr, "problem with camera config: duplicate ccd IDs\n");
    98     exit (1);
    99   }
    100  
    101   if (ccdnum_max > 0x1000) {
    102     fprintf (stderr, "problem with camera config: absurd max ccd ID number %d\n", ccdnum_max);
    103     exit (1);
    104   }
    105 
    106   ALLOCATE (camera.Fx,      int,    ccdnum_max);
    107   ALLOCATE (camera.Fy,      int,    ccdnum_max);
    108   ALLOCATE (camera.Ox,      int,    ccdnum_max);
    109   ALLOCATE (camera.Oy,      int,    ccdnum_max);
    110   ALLOCATE (camera.valid,   int,    ccdnum_max);
    111   ALLOCATE (camera.ccdname, char *, ccdnum_max);
    112 
    113   for (i = 0; i < ccdnum_max; i++) {
    114     camera.valid[i] = FALSE;
    115   }
    116 
    117   for (i = 0; i < camera.Nchip; i++) {
    118     N = ccdnum[i];
    119     camera.Fx[N] = Fx[i];
    120     camera.Fy[N] = Fy[i];
    121     camera.Ox[N] = Ox[i];
    122     camera.Oy[N] = Oy[i];
    123     camera.ccdname[N] = ccdname[i];
    124     camera.valid[N] = TRUE;
    125   }
    126 
    127   /* define mosaic 2d correction grid:
    128    * GRID_X is the number of grid pixels per chip in the X direction */
    129   gridX = RELPHOT_GRID_X * camera.Mx;
    130   gridY = RELPHOT_GRID_Y * camera.My;
    131   Ngrid = gridX * gridY;
    132 
    133   ALLOCATE (gridM, float, Ngrid);
    134   ALLOCATE (gridS, float, Ngrid);
    135   ALLOCATE (gridN, int,   Ngrid);
    136   ALLOCATE (gridV, int,   Ngrid);
    137 
    138   // the grid bins may have one of three possible states: fitted, frozen, reference
    139   // set the initial values to indicate that the bins are frozen
    140   for (i = 0; i < Ngrid; i++) {
    141     gridM[i] = 0.0;
    142     gridS[i] = 0.0;
    143     gridN[i] = 0;
    144     gridV[i] = GRID_FROZEN;
    145   }
    146 
    147   // refBin is the index of the grid cell which is kept at 0.0 (all others are relative to this)
    148   refBin = refX + refY*gridX;
    149   gridV[refBin] = GRID_REFERENCE;
    150 }
    151 
    152 void initGridBins (Catalog *catalog, int Ncatalog) {
    153 
    154   int i, j;
    155 
    156   if (!USE_GRID) return;
    157 
    158   /* define cat,meas -> grid pointers */
    159   ALLOCATE (bin, int *, Ncatalog);
    160   ALLOCATE (Xmeas, int *, Ncatalog);
    161   ALLOCATE (Ymeas, int *, Ncatalog);
    162   for (i = 0; i < Ncatalog; i++) {
    163     ALLOCATE (bin[i],   int, MAX (catalog[i].Nmeasure, 1));
    164     ALLOCATE (Xmeas[i], int, MAX (catalog[i].Nmeasure, 1));
    165     ALLOCATE (Ymeas[i], int, MAX (catalog[i].Nmeasure, 1));
    166     for (j = 0; j < catalog[i].Nmeasure; j++) bin[i][j] = -1;
    167   }
    168 
    169   /* define grid -> cat,meas pointers */
    170   ALLOCATE (Nlist, off_t,   Ngrid);
    171   ALLOCATE (NLIST, off_t,   Ngrid);
    172   ALLOCATE (clist, int *,   Ngrid);
    173   ALLOCATE (mlist, off_t *, Ngrid);
    174 
    175   for (i = 0; i < Ngrid; i++) {
    176     Nlist[i] = 0;
    177     NLIST[i] = 100;
    178     ALLOCATE (clist[i], int,   NLIST[i]);
    179     ALLOCATE (mlist[i], off_t, NLIST[i]);
    180   }
    181 }
    182 
    183 void freeGridBins (int Ncatalog) {
    184 
    185   int i;
    186 
    187   if (!USE_GRID) return;
    188 
    189   /* define cat,meas -> grid pointers */
    190   for (i = 0; i < Ncatalog; i++) {
    191     free (bin[i]);
    192     free (Xmeas[i]);
    193     free (Ymeas[i]);
    194   }
    195   free (bin);
    196   free (Xmeas);
    197   free (Ymeas);
    198 
    199   /* define grid -> cat,meas pointers */
    200   for (i = 0; i < Ngrid; i++) {
    201     free (clist[i]);
    202     free (mlist[i]);
    203   }
    204   free (Nlist);
    205   free (NLIST);
    206   free (clist);
    207   free (mlist);
    208 }
    209 
    210 int setGridMeasure (off_t meas, int cat, double X, double Y, int ccdnum) {
    211 
    212   int ix, iy, Cx, Cy, i;
    213   double x, y;
    214 
    215   /* X, Y are chip coords on chip ccdnum */
    216 
    217   /* normalize X & Y */
    218   x = X;
    219   if (camera.Fx[ccdnum]) x = camera.Nx - X;
    220   y = Y;
    221   if (camera.Fy[ccdnum]) y = camera.Ny - Y;
    222 
    223   /* grid coords on the chip */
    224   Cx = MIN (MAX ((x / camera.Nx) * RELPHOT_GRID_X, 0), RELPHOT_GRID_X - 1);
    225   Cy = MIN (MAX ((y / camera.Ny) * RELPHOT_GRID_Y, 0), RELPHOT_GRID_Y - 1);
    226  
    227   /* coordinates in the grid */
    228   ix = Cx + camera.Ox[ccdnum]*RELPHOT_GRID_X;
    229   iy = Cy + camera.Oy[ccdnum]*RELPHOT_GRID_Y;
    230 
    231   i = ix + iy*gridX;
    232 
    233   bin[cat][meas] = i;
    234   Xmeas[cat][meas] = x + camera.Ox[ccdnum]*camera.Nx;
    235   Ymeas[cat][meas] = y + camera.Oy[ccdnum]*camera.Ny;
    236   clist[i][Nlist[i]] = cat;
    237   mlist[i][Nlist[i]] = meas;
    238 
    239   // for the moment, add up the total grid count
    240   gridN[i]++;
    241 
    242   Nlist[i] ++;
    243   if (Nlist[i] == NLIST[i]) {
    244     NLIST[i] += 100;
    245     REALLOCATE (clist[i], int,   NLIST[i]);
    246     REALLOCATE (mlist[i], off_t, NLIST[i]);
    247   }     
    248   return (TRUE);
    249 
    250   fprintf (stderr, "error: star out of grid\n");
    251   exit (1);
    252 }
    253 
    254 int showGridCount() {
    255 
    256     int ix, iy, i;
    257 
    258     for (iy = 0; iy < gridY; iy++) {
    259         for (ix = 0; ix < gridX; ix++) {
    260             i = ix + iy*gridX;
    261             fprintf (stderr, "%3d  ", gridN[i]);
    262         }
    263         fprintf (stderr, "\n");
     139    // valid photcodes values (code) are in range 1 <= code < 0x10000
     140    // photcode == 0 are e.g., PHU (mosaic) images, and should be ignored here
     141    if (!code) continue;
     142
     143    int NX_CHIP = NX_CHIP_DEFAULT;
     144    int NY_CHIP = NY_CHIP_DEFAULT;
     145    int NX_BIN  = NX_BIN_DEFAULT;
     146    int NY_BIN  = NY_BIN_DEFAULT;
     147    if (isGPC1chip(code)) { NX_CHIP = 4900; NY_CHIP = 4900; NX_BIN = NY_BIN = GRID_BIN_GPC1; }
     148    if (isGPC2chip(code)) { NX_CHIP = 4900; NY_CHIP = 4900; NX_BIN = NY_BIN = GRID_BIN_GPC2; }
     149    if (isHSCchip(code))  { NX_CHIP = 2100; NY_CHIP = 4200; NX_BIN = NY_BIN = GRID_BIN_HSC;  }
     150    if (isCFHchip(code))  { NX_CHIP = 2100; NY_CHIP = 4200; NX_BIN = NY_BIN = GRID_BIN_CFH;  }
     151
     152    if (GridCorr[code]) continue; // already created this one
     153
     154    NGridReal ++;
     155
     156    ALLOCATE(GridCorr[code], GridCorrectionType, 1);
     157    GridCorr[code]->photcode = code;
     158    GridCorr[code]->Nx = NX_BIN;
     159    GridCorr[code]->Ny = NY_BIN;
     160    GridCorr[code]->dX = NX_BIN / (float) NX_CHIP;
     161    GridCorr[code]->dY = NY_BIN / (float) NY_CHIP;
     162
     163    // we are normally accessing this array randomly, so there is no advantage to
     164    // doing Mgrid[y][x] vs Mgrid[x][y]
     165    ALLOCATE (GridCorr[code]-> Mgrid, float *, NX_BIN);
     166    ALLOCATE (GridCorr[code]->dMgrid, float *, NX_BIN);
     167    ALLOCATE (GridCorr[code]->nMgrid,   int *, NX_BIN);
     168    for (int ix = 0; ix < NX_BIN; ix++) {
     169      ALLOCATE (GridCorr[code]-> Mgrid[ix], float, NY_BIN);
     170      ALLOCATE (GridCorr[code]->dMgrid[ix], float, NY_BIN);
     171      ALLOCATE (GridCorr[code]->nMgrid[ix],   int, NY_BIN);
     172    }     
     173  }
     174  resetMgrid(); // start with values of 0
     175  fprintf (stderr, "Init grid corrections for %d photcodes\n", NGridReal);
     176}
     177
     178// reset the values in the arrays to 0
     179void resetMgrid () {
     180
     181  if (!GRID_ZEROPT) return;
     182  if (!GridCorr) return;
     183
     184  for (int code = 0; code < NGridCorr; code++) {
     185    if (!GridCorr[code]) continue;
     186
     187    for (int ix = 0; ix < GridCorr[code]->Nx; ix++) {
     188      for (int iy = 0; iy < GridCorr[code]->Ny; iy++) {
     189        GridCorr[code]-> Mgrid[ix][iy] = 0.0;
     190        GridCorr[code]->dMgrid[ix][iy] = 0.0;
     191        GridCorr[code]->nMgrid[ix][iy] =   0;
     192      }
     193    }     
     194  }
     195}
     196
     197void setMgrid (Catalog *catalog, int Ncatalog) {
     198
     199  // check if we are actually doing this step
     200  if (!GRID_ZEROPT) return;
     201  if (GRID_ZPT_MODE == GRID_ZPT_MODE_NONE) return;
     202
     203  resetMgrid(); // start with values of 0
     204
     205  // loop over all measurements, accumulate Sum (in Mgrid), Sum2 (in dMgrid), and Npts
     206
     207  int Nsecfilt = GetPhotcodeNsecfilt ();
     208
     209  for (int nc = 0; nc < Ncatalog; nc++) {
     210    for (int na = 0; na < catalog[nc].Naverage; na++) {
     211
     212      int nm = catalog[nc].averageT[na].measureOffset;
     213      for (int k = 0; k < catalog[nc].averageT[na].Nmeasure; k++, nm++) {
     214
     215        // skip measurements marked by AREA or TIME
     216        if (catalog[nc].measureT[nm].dbFlags & MEAS_BAD) continue;
     217
     218        float Mcal = getMcal  (nm, nc, MAG_CLASS_PSF);
     219        if (isnan(Mcal)) continue;
     220
     221        float Mgrp = getMgrp  (nm, nc, catalog[nc].measureT[nm].airmass, NULL);
     222        if (isnan(Mgrp)) continue;
     223
     224        float Mmos  = getMmos  (nm, nc);
     225        if (isnan(Mmos)) continue;
     226
     227        float Mflat = getMflat (nm, nc, catalog);
     228        if (isnan(Mflat)) continue;
     229
     230        // Mrel* is the average magnitude for this star.  For PS1 stacks, we have too much
     231        // PSF variability.  We need to calibrate the PSF magnitudes separately from the
     232        // Aperture-like magnitues.  (We have an option to use the kron magnitudes or the
     233        // other apertures here).  I basically need to do this analysis separately for each
     234        // magnitude type
     235   
     236        float MrelPSF = getMrel  (catalog, nm, nc, MAG_CLASS_PSF, MAG_SRC_CHP);
     237        if (isnan(MrelPSF)) continue;
     238     
     239        float MsysPSF = PhotSysTiny (&catalog[nc].measureT[nm], &catalog[nc].averageT[na], &catalog[nc].secfilt[na*Nsecfilt], MAG_CLASS_PSF);
     240        if (isnan(MsysPSF)) continue;
     241
     242        float Moff =  Mcal + Mgrp + Mmos + Mflat;
     243
     244        // Msys = Mrel + Moff + Mgrid
     245        // thus Mgrid = Msys - Mrel - Moff
     246
     247        int code = catalog[nc].measureT[nm].photcode;
     248        if (code <= 0) continue;
     249        if (code >= NGridCorr) continue; // does not match one of our image, skip
     250       
     251        GridCorrectionType *grid = GridCorr[code];
     252        if (!grid) continue; // does not match one of our images, skip
     253
     254        // edge effects could cause some positions to be slightly out of range
     255        // probably should trap extreme outliers
     256        int ix = MIN(MAX(0, (int)(catalog[nc].measureT[nm].Xccd * grid->dX)), grid->Nx - 1);
     257        int iy = MIN(MAX(0, (int)(catalog[nc].measureT[nm].Yccd * grid->dY)), grid->Ny - 1);
     258
     259        float dM = MsysPSF - MrelPSF - Moff;
     260       
     261        // XXX by the time we get here, we should have already mostly fixed up the zero
     262        // points.  reject measurements which are way off
     263        if (fabs(dM) > 0.5) continue;
     264
     265        grid-> Mgrid[ix][iy] += dM;
     266        grid->dMgrid[ix][iy] += dM*dM;
     267        grid->nMgrid[ix][iy] ++;
     268      }
    264269    }
    265     return (TRUE);
    266 }
    267 
    268 float getMgrid (off_t meas, int cat) {
    269 
    270   int i;
    271   float value;
    272 
    273   if (!USE_GRID) return (0);
    274   i = bin[cat][meas];
    275   if (i == -1) return (NAN);
    276 
    277   // during the grid annealing process, we skip over grid cells until they have enough
    278   // valid stars to be fitted
    279   if (gridV[i] == GRID_FROZEN) {
    280     return (NAN);
    281   }
    282 
    283   value = gridM[i];
    284   return (value);
    285 }
    286 
    287 /* direct (non-iterative) solution for Mgrid values for all grid bins */
    288 void setMgridDirect (Catalog *catalog, int Ncatalog, FlatCorrectionTable *flatcorr) {
    289 
    290   int **gotstar, **gridmeas;
    291   int i, j, k, Ngood, Nbad, Nmos, Ncal, Nrel, Nsys, Ngrp;
    292   double **A, **B, *Mjx, *Wjx;
    293   float Msys, Mcal, Mmos, Mgrp, Merr, Wsys;
    294   double Mj, Wj;
    295  
    296   if (!USE_GRID) return;
    297 
    298   ALLOCATE (A, double *, Ngrid);
    299   ALLOCATE (B, double *, Ngrid);
    300   for (i = 0; i < Ngrid; i++) {
    301     ALLOCATE (A[i], double, Ngrid);
    302     ALLOCATE (B[i], double, 1);
    303     memset (A[i], 0, Ngrid*sizeof(double));
    304     memset (B[i], 0, sizeof(double));
    305   }
    306 
    307   Ngood = Nbad = Ncal = Nmos = Nrel = Nsys = Ngrp = 0;
    308 
    309   ALLOCATE (gotstar, int *, Ncatalog);
    310   for (i = 0; i < Ncatalog; i++) {
    311     ALLOCATE (gotstar[i], int, catalog[i].Naverage);
    312   } 
    313 
    314   // set up gridmeas table : grid index for each measurement
    315   ALLOCATE (gridmeas, int *, Ncatalog);
    316   for (i = 0; i < Ncatalog; i++) {
    317     ALLOCATE (gridmeas[i], int, catalog[i].Nmeasure);
    318     for (j = 0; j < catalog[i].Nmeasure; j++) {
    319       gridmeas[i][j] = -1;
    320     }
    321   } 
    322   for (i = 0; i < Ngrid; i++) {
    323     for (j = 0; j < Nlist[i]; j++) {
    324       int m, c;
    325       m = mlist[i][j];
    326       c = clist[i][j];
    327       gridmeas[c][m] = i;
    328     }
    329   }
    330 
    331   // as we loop over the grid cells, we need to accumulate the values of Wjx for each star
    332   ALLOCATE (Wjx, double, Ngrid);
    333   ALLOCATE (Mjx, double, Ngrid);
    334 
    335   // accumulate the elements of the matrix equation.  We have an equation of the form: Ax = B
    336   // where x is the vector of grid cell values G_x (x = 0 - Ngrid), A is an Ngrid x Ngrid matrix,
    337   // and B is an Ngrid vector.  For a cell A(x,y), we need the following elements from each
    338   // star which touches grid cell (x):
    339   //
    340   // Mj  : sum over all measurements of Msys / dMsys^2
    341   // Wj  : sum over all measurements of 1.0 / dMsys^2
    342   // Mjx : sum over all measurements which touch cell (x) of Msys / dMsys^2
    343   // Wjx : sum over all measurements which touch cell (x) of 1.0 / dMsys^2
    344 
    345   // Mjx and Wjx can be calculated by summing over all measurements which touch the cell
    346   // Mj requires looping over stars which touch (x)
    347 
    348   // this is tricky because we need to know both the measurements which touch a cell
    349   // and the stars for which any measurement touches a cell.  we need to accumulate
    350   // sums for each star which touches as cell on both bases.
    351 
    352   int Nsecfilt = GetPhotcodeNsecfilt ();
    353   int thisCode = photcodes[0][0].code;
    354   int Nsec = GetPhotcodeNsec(thisCode);
    355 
    356   for (i = 0; i < Ngrid; i++) {
    357    
    358     for (j = 0; j < Ncatalog; j++) {
    359       memset (gotstar[j], 0, catalog[j].Naverage*sizeof(int));
    360     } 
    361 
    362     // we are looping over the stars, but doing so by looping over the set of measurements:
    363     // every star which touches this grid cell has a measurement in Nlist[i]
    364     for (j = 0; j < Nlist[i]; j++) {
    365      
    366       int mx, c, n, m0, Npts;
    367 
    368       mx = mlist[i][j];
    369       c  = clist[i][j];
    370       n  = catalog[c].measureT[mx].averef;
    371      
    372       // if we have already visited this star, skip the stuff below
    373       if (gotstar[c][n]) continue;
    374       gotstar[c][n] = TRUE;
    375 
    376       // skip stars marked as BAD
    377       if (catalog[c].secfilt[n*Nsecfilt+Nsec].flags & STAR_BAD) {
    378         Nrel ++;
    379         continue;
    380       }
    381 
    382       m0 = catalog[c].average[n].measureOffset;
    383 
    384       // we accumuate an entry for each cell
    385       memset (Wjx, 0, Ngrid*sizeof(double));
    386       memset (Mjx, 0, Ngrid*sizeof(double));
    387       Npts = Mj = Wj = 0.0;
    388 
    389       // if we have not yet visited this star, accumulate the Mj, Wj entries
    390       for (k = 0; k < catalog[c].average[n].Nmeasure; k++) {
    391 
    392         int m, Ng;
    393 
    394         m = m0 + k;
    395 
    396         // skip measurements marked as BAD
    397         if (catalog[c].measureT[m].dbFlags & MEAS_BAD) {
    398           Nbad ++;
     270  }
     271
     272  // now calculate Mgrid, dMgrid, nMgrid from Sum, Sum, Npt
     273  for (int code = 0; code < NGridCorr; code++) {
     274    if (!GridCorr[code]) continue;
     275
     276    for (int ix = 0; ix < GridCorr[code]->Nx; ix++) {
     277      for (int iy = 0; iy < GridCorr[code]->Ny; iy++) {
     278
     279        // cells without sufficient coverage stay at 0.0
     280        if (GridCorr[code]->nMgrid[ix][iy] < 5) {
     281          GridCorr[code]-> Mgrid[ix][iy] = 0.0;
     282          GridCorr[code]->dMgrid[ix][iy] = 0.0;
    399283          continue;
    400284        }
    401285
    402         // skip images marked as BAD
    403         Mcal = getMcal  (m, c, MAG_CLASS_PSF);
    404         if (isnan(Mcal)) {
    405           Ncal ++;
    406           continue;
    407         }
    408 
    409         // skip mosaics marked as BAD
    410         Mmos = getMmos  (m, c);
    411         if (isnan(Mmos)) {
    412           Nmos ++;
    413           continue;
    414         }
    415 
    416         // skip mosaics marked as BAD
    417         Mgrp = getMgrp  (m, c, catalog[c].measureT[m].airmass, NULL);
    418         if (isnan(Mgrp)) {
    419           Ngrp ++;
    420           continue;
    421         }
    422 
    423         // select the color- and airmass-corrected observed magnitude for this star
    424         // XXX need to be able to turn off the color-correction until initial average mags are found
    425         Msys = PhotCatTiny (&catalog[c].measureT[m], MAG_CLASS_PSF);
    426         if (isnan(Msys)) {
    427           Nsys++;
    428           continue;
    429         }
    430 
    431         // mag-error for this measurement
    432         Merr =  MAX (catalog[c].measureT[m].dM, MIN_ERROR);
    433 
    434         // disable Wsys for now
    435         Wsys = TRUE ? 1.0 : 1.0 / SQ(Merr);
    436 
    437         Ng = gridmeas[c][m];
    438         if (Ng == -1) continue;  // skip measurements which do not touch any cell
    439 
    440         Mj += Msys * Wsys;  // we are only including measurements touching this cell
    441         Wj += Wsys;  // we are only including measurements touching this cell
    442         Npts ++;
    443         Ngood ++;
    444 
    445         Mjx[Ng] += Msys * Wsys;  // we are only including measurements touching cell (x)
    446         Wjx[Ng] += Wsys;  // we are only including measurements touching cell (x)
    447       }
    448 
    449       // some stars will not have any valid measurements, skip these
    450       if (Npts == 0) continue;
    451 
    452       B[i][0] += Mj*Wjx[i]/Wj - Mjx[i];
    453       A[i][i] -= Wjx[i];
    454       for (k = 0; k < Ngrid; k++) {
    455         A[i][k] += Wjx[i]*Wjx[k]/Wj;
    456         // fprintf (stderr, "%3.0f ", Wjx[k]);
     286        float Mgrid  = GridCorr[code]-> Mgrid[ix][iy] / GridCorr[code]->nMgrid[ix][iy]; // average Mgrid
     287        float Mgrid2 = GridCorr[code]-> dMgrid[ix][iy] / GridCorr[code]->nMgrid[ix][iy]; // average Mgrid^2
     288
     289        float r = GridCorr[code]->nMgrid[ix][iy] / (float) (GridCorr[code]->nMgrid[ix][iy] - 1.0); // pop -> sample stdev
     290
     291        GridCorr[code]-> Mgrid[ix][iy] = Mgrid;
     292        GridCorr[code]->dMgrid[ix][iy] = sqrt(r*(Mgrid2 - Mgrid*Mgrid)); // sample stdev
     293        // fprintf (stderr, "grid code %d, %d x %d : %f +/- %f : %d\n", code, ix, iy, GridCorr[code]-> Mgrid[ix][iy], GridCorr[code]->dMgrid[ix][iy], GridCorr[code]->nMgrid[ix][iy]);
    457294      }
    458295    }
    459296  }
    460 
    461   if (1) {
    462 
    463     FILE *f;
    464     Header theader;
    465     Matrix matrix;
    466 
    467     /* we are writing to this file */
    468     f = fopen ("matrix.fits", "w");
    469     if (f == (FILE *) NULL) {
    470       fprintf (stderr, "cannot open matrix.fits for output\n");
    471       return;
    472     }
    473 
    474     /* save grid mag values */
    475     gfits_init_header (&theader);
    476     theader.Naxes = 2;
    477     theader.Naxis[0] = Ngrid;
    478     theader.Naxis[1] = Ngrid;
    479     theader.bitpix   = -32;
    480     gfits_create_Theader (&theader, "IMAGE");
    481     gfits_modify (&theader, "EXTNAME", "%s", 1, "MATRIX");
    482     gfits_create_matrix  (&theader, &matrix);
    483     for (i = 0; i < Ngrid; i++) {
    484       for (j = 0; j < Ngrid; j++) {
    485         gfits_set_matrix_value (&matrix, i, j, (double) A[i][j]);
    486       }
    487     }
    488     gfits_fwrite_header (f, &theader);
    489     gfits_fwrite_matrix (f, &matrix);
    490     gfits_free_matrix (&matrix);
    491 
    492     gfits_modify (&theader, "EXTNAME", "%s", 1, "TRPOSE");
    493     gfits_create_matrix  (&theader, &matrix);
    494     for (i = 0; i < Ngrid; i++) {
    495       for (j = 0; j < Ngrid; j++) {
    496         gfits_set_matrix_value (&matrix, i, j, (double) A[j][i]);
    497       }
    498     }
    499     gfits_fwrite_header (f, &theader);
    500     gfits_fwrite_matrix (f, &matrix);
    501     gfits_free_matrix (&matrix);
    502     fclose (f);
    503   }
    504 
    505   dgaussjordan (A, B, Ngrid, 1);
    506 
    507   fprintf (stderr, "grid cells fitted (Ngood: %d, Nbad: %d, Nmos: %d, Ncal: %d, Nrel: %d, Nsys: %d)\n", Ngood, Nbad, Nmos, Ncal, Nrel, Nsys);
    508 
    509   for (i = 0; i < Ngrid; i++) {
    510     gridM[i] = B[i][0];
    511     gridS[i] = sqrt(A[i][i]);
    512     gridN[i] = Ngood;
    513   }
    514 
    515   free (Wjx);
    516   free (Mjx);
    517 
    518   for (i = 0; i < Ngrid; i++) {
    519     free (A[i]);
    520   }
    521   free (A);
    522   free (B);
    523 
    524   for (i = 0; i < Ncatalog; i++) {
    525     free (gotstar[i]);
    526     free (gridmeas[i]);
    527   } 
    528   free (gotstar);
    529   free (gridmeas);
    530 }
    531 
    532 /* determine Mgrid values for all grid bins */
    533 void setMgrid (Catalog *catalog, FlatCorrectionTable *flatcorr) {
    534 
    535   int i, j, m, c, n, N, Nmax, Nbad, Nmos, Ngrp, Ncal, Nrel, Nsys, Nfit;
    536   double *list, *dlist;
    537   float Msys, Mrel, Mcal, Mmos, Mgrp;
    538 
    539   StatType stats;
    540   liststats_setmode (&stats, "INNER_WTMEAN");
     297  return;
     298}
     299
     300float getMgrid (Measure *measure) {
     301
     302  if (!GRID_ZEROPT) return 0.0;
     303  if (GRID_ZPT_MODE == GRID_ZPT_MODE_NONE) return 0.0;
     304
     305  int code = measure->photcode;
     306  if (code <= 0) return 0.0;
     307  if (code >= NGridCorr) return 0.0; // does not match one of our image, skip
     308       
     309  GridCorrectionType *grid = GridCorr[code];
     310  if (!grid) return 0.0; // does not match one of our images, skip
    541311 
    542   if (!USE_GRID) return;
    543 
    544   int Nsecfilt = GetPhotcodeNsecfilt ();
    545 
    546   Nmax = Nlist[0];
    547   for (i = 0; i < Ngrid; i++) {
    548     Nmax = MAX (Nmax, Nlist[i]);
    549   }
    550   ALLOCATE (list, double, Nmax);
    551   ALLOCATE (dlist, double, Nmax);
    552 
    553   Nbad = Ncal = Nmos = Ngrp = Nrel = Nsys = Nfit = 0;
    554 
    555   for (i = 0; i < Ngrid; i++) {
    556 
    557     N = 0;
    558     for (j = 0; j < Nlist[i]; j++) {
    559      
    560       m = mlist[i][j];
    561       c = clist[i][j];
    562      
    563       if (catalog[c].measureT[m].dbFlags & MEAS_BAD) {
    564         Nbad ++;
    565         continue;
    566       }
    567       Mcal = getMcal  (m, c, MAG_CLASS_PSF);
    568       if (isnan(Mcal)) {
    569         Ncal ++;
    570         continue;
    571       }
    572       Mmos = getMmos  (m, c);
    573       if (isnan(Mmos)) {
    574         Nmos ++;
    575         continue;
    576       }
    577       Mgrp = getMgrp  (m, c, catalog[c].measureT[m].airmass, NULL);
    578       if (isnan(Mgrp)) {
    579         Ngrp ++;
    580         continue;
    581       }
    582       Mrel  = getMrel  (catalog, m, c, MAG_CLASS_PSF, MAG_SRC_CHP);
    583       if (isnan(Mrel)) {
    584         Nrel ++;
    585         continue;
    586       }
    587      
    588       n = catalog[c].measureT[m].averef;
    589       Msys = PhotSysTiny (&catalog[c].measureT[m], &catalog[c].averageT[n], &catalog[c].secfilt[n*Nsecfilt], MAG_CLASS_PSF);
    590       if (isnan(Msys)) {
    591         Nsys++;
    592         continue;
    593       }
    594       list[N] = Msys - Mrel - Mcal - Mmos - Mgrp;
    595       dlist[N] = MAX (catalog[c].measureT[m].dM, MIN_ERROR);
    596       N++;
    597     }
    598 
    599     // the reference Cell is forced to have a value of 0.0, and is never changed to GRID_FITTED
    600     if (gridV[i] == GRID_REFERENCE) {
    601       gridM[i] = 0.0;
    602       gridS[i] = 0.0;
    603       gridN[i] = N;
    604       continue;
    605     }
    606 
    607     // until we have enough valid measurements on this grid cell, skip it
    608     if (N < GRID_TOOFEW) {
    609       gridV[i] = GRID_FROZEN;
    610       continue;
    611     }
    612 
    613     liststats (list, dlist, NULL, N, &stats);
    614     gridM[i] = stats.mean;
    615     gridS[i] = stats.sigma;
    616     gridN[i] = N;
    617     gridV[i] = GRID_FITTED;
    618     Nfit++;
    619   }
    620 
    621   fprintf (stderr, "%d of %d grid cells fitted (+ reference cell) (Nbad: %d, Nmos: %d, Ncal: %d, Nrel: %d, Nsys: %d)\n", Nfit, Ngrid, Nbad, Nmos, Ncal, Nrel, Nsys);
    622 
    623   free (list);
    624   free (dlist);
    625 }
    626 
    627 void plot_grid (Catalog *catalog, FlatCorrectionTable *flatcorr) {
    628 
    629   int i, j, m, c, n, N, Narea;
    630   float Msys, Mrel, Mcal, Mmos, Mgrp;
    631   double *xlist, *Mlist, *dlist, *ylist;
    632   Graphdata graphdata;
    633 
    634   if (!USE_GRID) return;
    635 
    636   int Nsecfilt = GetPhotcodeNsecfilt ();
    637 
    638   N = 0;
    639   for (i = 0; i < Ngrid; i++)
    640     N += Nlist[i];
    641 
    642   ALLOCATE (xlist, double, N);
    643   ALLOCATE (ylist, double, N);
    644   ALLOCATE (Mlist, double, N);
    645   ALLOCATE (dlist, double, N);
    646 
    647   Narea = 0;
    648   N = 0;
    649   for (i = 0; i < Ngrid; i++) {
    650     for (j = 0; j < Nlist[i]; j++) {
    651      
    652       m = mlist[i][j];
    653       c = clist[i][j];
    654      
    655       if (catalog[c].measureT[m].dbFlags & MEAS_BAD) {
    656         Narea ++;
    657         continue;
    658       }
    659       Mcal  = getMcal  (m, c, MAG_CLASS_PSF);
    660       if (isnan(Mcal)) continue;
    661       Mmos  = getMmos  (m, c);
    662       if (isnan(Mmos)) continue;
    663       Mgrp  = getMgrp  (m, c, catalog[c].measureT[m].airmass, NULL);
    664       if (isnan(Mgrp)) continue;
    665       Mrel  = getMrel  (catalog, m, c, MAG_CLASS_PSF, MAG_SRC_CHP);
    666       if (isnan(Mrel)) continue;
    667 
    668       n = catalog[c].measureT[m].averef;
    669       Msys = PhotSysTiny (&catalog[c].measureT[m], &catalog[c].averageT[n], &catalog[c].secfilt[n*Nsecfilt], MAG_CLASS_PSF);
    670 
    671       xlist[N] = Xmeas[c][m];
    672       ylist[N] = Ymeas[c][m];
    673       Mlist[N] = Msys - Mrel - Mcal - Mmos - Mgrp;
    674       dlist[N] = Msys - Mrel - Mcal - Mmos - Mgrp - gridM[i];
    675       N++;
    676     }
    677   }
    678 
    679   fprintf (stderr, "skipped %d meas for area\n", Narea);
    680 
    681   plot_defaults (&graphdata);
    682   graphdata.ymin = PlotdMmin;
    683   graphdata.ymax = PlotdMmax;
    684   plot_list (&graphdata, xlist, Mlist, N, "X vs dM raw", "%s.XdM.png", OUTROOT);
    685   plot_list (&graphdata, xlist, dlist, N, "X vs dM corrected", "%s.XdMf.png", OUTROOT);
    686   plot_list (&graphdata, ylist, dlist, N, "Y vs dM corrected", "%s.YdMf.png", OUTROOT);
    687 
    688   plot_defaults (&graphdata);
    689   plot_list (&graphdata, xlist, ylist, N, "X vs Y", "%s.XY.png", OUTROOT);
    690 
    691   free (ylist);
    692   free (xlist);
    693   free (Mlist);
    694   free (dlist);
    695 
    696 }
    697 
    698 void dump_grid () {
    699 
    700   off_t i, Nimage;
    701   int j, Nbytes, Nformat;
    702   FILE *f;
    703   Header header, theader;
    704   Matrix matrix;
    705   Mosaic *refmosaic;
    706   char *filename;
    707   char formatline[32], key[32], value[64];
    708    
    709   Nbytes = strlen (OUTROOT) + 6;
    710   ALLOCATE (filename, char, Nbytes);
    711   snprintf (filename, Nbytes, "%s.fits", OUTROOT);
    712 
    713   /* select reference mosaic image */
    714   // off_t *imlist = SelectRefMosaic (&refmosaic, &Nimage); return value ignored
    715   SelectRefMosaic (&refmosaic, &Nimage);
    716 
    717   /* we are writing to this file */
    718   f = fopen (filename, "w");
    719   if (f == (FILE *) NULL) {
    720     fprintf (stderr, "cannot open %s for output\n", filename);
    721     free (filename);
    722     return;
    723   }
    724 
    725   /* create empty phu */
    726   gfits_init_header (&header);
    727   header.extend = TRUE;
    728   gfits_create_header (&header);
    729   gfits_create_matrix (&header, &matrix);
    730   gfits_modify (&header, "NEXTEND", OFF_T_FMT, 1,  Nimage + 3);
    731   gfits_modify (&header, "FILTER", "%s", 1, photcodes[0][0].name);  // XXXX note that this expects a single photcode, enforced in initialize.d
    732   gfits_modify_alt (&header, "COMMENT", "%S", 1, "Mosaic Photometry Grid Analysis");
    733 
    734   // we need to add lines to the PHU to identify the camera and format; these are used by the ipp config system
    735   // Note that config must have been loaded (and not freed) above.
    736   ScanConfig (config, "NFORMAT", "%d", 1, &Nformat);
    737   for (i = 1; i <= Nformat; i++) {
    738       ScanConfig (config, "FORMAT", "%s", i, formatline);
    739       sscanf (formatline, "%s %s", key, value);
    740       gfits_modify (&header, key, "%s", 1, value);
    741   }
    742 
    743   gfits_fwrite_header (f, &header);
    744   gfits_fwrite_matrix (f, &matrix);
    745   gfits_free_matrix (&matrix);
    746 
    747   /* save grid mag values */
    748   gfits_init_header (&theader);
    749   theader.Naxes = 2;
    750   theader.Naxis[0] = gridX;
    751   theader.Naxis[1] = gridY;
    752   theader.bitpix   = -32;
    753   gfits_create_Theader (&theader, "IMAGE");
    754   gfits_modify (&theader, "FILTER", "%s", 1, photcodes[0][0].name);
    755   gfits_modify (&theader, "EXTNAME", "%s", 1, "MAG_OFFSET");
    756   gfits_create_matrix  (&theader, &matrix);
    757   for (i = 0; i < gridX; i++) {
    758     for (j = 0; j < gridY; j++) {
    759       gfits_set_matrix_value (&matrix, i, j, (double) gridM[i + j*gridX]);
    760     }
    761   }
    762   write_coords (&theader, &refmosaic[0].coords);
    763   gfits_fwrite_header (f, &theader);
    764   gfits_fwrite_matrix (f, &matrix);
    765   gfits_free_matrix (&matrix);
    766 
    767   /* save grid Nmeas values */
    768   gfits_modify (&theader, "EXTNAME", "%s", 1, "NMEAS");
    769   gfits_modify (&theader, "FILTER", "%s", 1, photcodes[0][0].name);
    770   gfits_create_matrix  (&theader, &matrix);
    771   for (i = 0; i < gridX; i++) {
    772     for (j = 0; j < gridY; j++) {
    773       gfits_set_matrix_value (&matrix, i, j, (double) gridN[i + j*gridX]);
    774     }
    775   }
    776   write_coords (&theader, &refmosaic[0].coords);
    777   gfits_fwrite_header (f, &theader);
    778   gfits_fwrite_matrix (f, &matrix);
    779   gfits_free_matrix (&matrix);
    780 
    781   /* save grid sigma values */
    782   gfits_modify (&theader, "EXTNAME", "%s", 1, "SIGMA");
    783   gfits_modify (&theader, "FILTER", "%s", 1, photcodes[0][0].name);
    784   gfits_create_matrix  (&theader, &matrix);
    785   for (i = 0; i < gridX; i++) {
    786     for (j = 0; j < gridY; j++) {
    787       gfits_set_matrix_value (&matrix, i, j, (double) gridS[i + j*gridX]);
    788     }
    789   }
    790   write_coords (&theader, &refmosaic[0].coords);
    791   gfits_fwrite_header (f, &theader);
    792   gfits_fwrite_matrix (f, &matrix);
    793   gfits_free_matrix (&matrix);
    794 
    795   /* calculate value for each CCD pixel, write out CCD images */
    796   /* grid pixels are tied to detector pixels, but are flipped to match focal plane */
    797   for (i = 0; i < camera.Nchip; i++) {
    798     int N, ix, iy, x, y, X, Y, bin;
    799 
    800     N = ccdnum[i];
    801 
    802     gfits_modify (&theader, "EXTNAME", "%s", 1, camera.ccdname[N]);
    803     gfits_modify (&theader, "FILTER", "%s", 1, photcodes[0][0].name);
    804     gfits_modify (&theader, "NX", "%d", 1, camera.Nx);
    805     gfits_modify (&theader, "NY", "%d", 1, camera.Ny);
    806      
    807     theader.Naxis[0] = RELPHOT_GRID_X;
    808     theader.Naxis[1] = RELPHOT_GRID_Y;
    809     gfits_modify (&theader, "NAXIS1", "%d", 1, RELPHOT_GRID_X);
    810     gfits_modify (&theader, "NAXIS2", "%d", 1, RELPHOT_GRID_Y);
    811     gfits_create_matrix  (&theader, &matrix);
    812 
    813     for (Y = 0; Y < RELPHOT_GRID_Y; Y++) {
    814       for (X = 0; X < RELPHOT_GRID_X; X++) {
    815              
    816         /* normalize X & Y */
    817         x = X;
    818         if (camera.Fx[N]) x = RELPHOT_GRID_X - X - 1;
    819         y = Y;
    820         if (camera.Fy[N]) y = RELPHOT_GRID_Y - Y - 1;
    821              
    822         /* coordinates in the grid */
    823         ix = x + camera.Ox[N]*RELPHOT_GRID_X;
    824         iy = y + camera.Oy[N]*RELPHOT_GRID_Y;
    825              
    826         bin = ix + iy*gridX;
    827         gfits_set_matrix_value (&matrix, X, Y, (double) gridM[bin]);
    828       }
    829     }
    830     gfits_fwrite_header (f, &theader);
    831     gfits_fwrite_matrix (f, &matrix);
    832     gfits_free_matrix (&matrix);
    833   }
    834 
    835   free (filename);
    836 }
    837 
    838 void InterpolateGrid (float *buffer, int Nx, int Ny, Coords *ccd, Coords *gcoords) {
    839 
    840   int i, j;
    841   double x, y, r, d, X, Y, dx, dy;
    842   double V00, V01, V10, V11;
    843   double wV00, wV01, wV10, wV11;
    844   double dV00, dV01, dV10, dV11;
    845   double v1, v2, value;
    846   int ix, iy, N;
    847 
    848   for (i = 0; i < Nx; i++) {
    849     for (j = 0; j < Ny; j++) {
    850       x = i * RELPHOT_GRID_BINNING / 2;
    851       y = j * RELPHOT_GRID_BINNING / 2;
    852       XY_to_RD (&r, &d, x, y, ccd);
    853       RD_to_XY (&X, &Y, r, d, gcoords);
    854 
    855       X = X / RELPHOT_GRID_BINNING;
    856       Y = Y / RELPHOT_GRID_BINNING;
    857 
    858       ix = (int) X;
    859       dx = X - ix;
    860       iy = (int) Y;
    861       dy = Y - iy;
    862 
    863       if (ix < 0) continue;
    864       if (iy < 0) continue;
    865       if (ix >= gridX) continue;
    866       if (iy >= gridY) continue;
    867 
    868       N = ix + iy*gridX;
    869       V00 = gridM[N];
    870       V10 = gridM[N + 1];
    871       V01 = gridM[N + gridX];
    872       V11 = gridM[N + gridX + 1];
    873 
    874       dV00 = gridS[N];
    875       dV10 = gridS[N + 1];
    876       dV01 = gridS[N + gridX];
    877       dV11 = gridS[N + gridX + 1];
    878 
    879       wV00 = (dV00 == 0) ? 0.0 : 1 / SQ(dV00);
    880       wV01 = (dV01 == 0) ? 0.0 : 1 / SQ(dV01);
    881       wV10 = (dV10 == 0) ? 0.0 : 1 / SQ(dV10);
    882       wV11 = (dV11 == 0) ? 0.0 : 1 / SQ(dV11);
    883 
    884       v1 = wV00*V00*(1 + dx*dy - dx - dy) +
    885         wV10*V10*(dx - dx*dy) +
    886         wV01*V01*(dy - dx*dy) +
    887         wV11*V11*(dx*dy);
    888 
    889       v2 = wV00*(1 + dx*dy - dx - dy) +
    890         wV10*(dx - dx*dy) +
    891         wV01*(dy - dx*dy) +
    892         wV11*(dx*dy);
    893 
    894       value = v1 / v2;
    895       buffer[j*Nx + i] = value;
    896     }
    897   }
    898 }
     312  // edge effects could cause some positions to be slightly out of range
     313  // probably should trap extreme outliers
     314  int ix = MIN(MAX(0, (int)(measure->Xccd * grid->dX)), grid->Nx - 1);
     315  int iy = MIN(MAX(0, (int)(measure->Yccd * grid->dY)), grid->Ny - 1);
     316
     317  float Mgrid = grid-> Mgrid[ix][iy];
     318  return Mgrid;
     319}
     320
     321float getMgridTiny (MeasureTiny *measure) {
     322
     323  if (!GRID_ZEROPT) return 0.0;
     324  if (GRID_ZPT_MODE == GRID_ZPT_MODE_NONE) return 0.0;
     325
     326  int code = measure->photcode;
     327  if (code <= 0) return 0.0;
     328  if (code >= NGridCorr) return 0.0; // does not match one of our image, skip
     329       
     330  GridCorrectionType *grid = GridCorr[code];
     331  if (!grid) return 0.0; // does not match one of our images, skip
     332 
     333  // edge effects could cause some positions to be slightly out of range
     334  // probably should trap extreme outliers
     335  int ix = MIN(MAX(0, (int)(measure->Xccd * grid->dX)), grid->Nx - 1);
     336  int iy = MIN(MAX(0, (int)(measure->Yccd * grid->dY)), grid->Ny - 1);
     337
     338  float Mgrid = grid-> Mgrid[ix][iy];
     339  return Mgrid;
     340}
     341
     342// for historical reasons, Mflat and Mgrid have opposite signs
     343void setMflatFromGrid (Catalog *catalog) {
     344  if (!GRID_ZEROPT) return;
     345  for (off_t j = 0; j < catalog->Nmeasure; j++) {
     346    float Mgrid = getMgrid (&catalog->measure[j]);
     347    catalog->measure[j].Mflat += Mgrid;
     348  }
     349}
     350
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/ImageOps.c

    r41557 r41649  
    319319}
    320320
    321 int findCCD (off_t idx, off_t meas, int cat, MeasureTiny *measure) {
    322 
    323   int ccdnum;
    324   double X, Y;
    325   char *pname, *filter, *p, base[256];
    326 
    327   /* identify the ccd on the basis of the photcode name */
    328   pname = GetPhotcodeNamebyCode (image[idx].photcode);
    329 
    330   // skip measurements which do not match one of the requested photcodes (
    331   // (do we not already exclude in bcatalog -- maybe needed for reload_objects?
    332   int Ns = GetActivePhotcodeIndex (measure[0].photcode);
    333   if (Ns < 0) return FALSE;
    334 
    335   filter = photcodes[Ns][0].name;
    336   sprintf (base, "%s.%s.", MOSAICNAME, filter);
    337   if (strncmp (pname, base, strlen (base))) return (FALSE);
    338   p = pname + strlen(base);
    339 
    340   /* p is pointing at the DETECTOR ID part of the photcode: CAMERA.FILTER.DETECTOR
    341      for now, we will let this be of the form SSSSnn where SSS is an arbitrary string
    342      and nn is an integer -> ccdnum */
    343      
    344   /// XXX we have an inconsistency here wrt dvo.layout and dvo.photcode
    345 
    346   while (!isdigit(*p) && *p) p++;
    347   if (*p == 0) return (FALSE);
    348   ccdnum = atoi (p);
    349 
    350   /* ccdnum is an integer, but not necessarily a sequence number.  when the camera layout is
    351      constructed, there will be null values for undefined ccdnums */
    352 
    353   // old code to add this measurement to the grid cell for this chip
    354   // ave = measureT[0].averef;
    355   // ra  = catalog[cat].averageT[ave].R - measureT[0].dR / 3600.0;
    356   // dec = catalog[cat].averageT[ave].D - measureT[0].dD / 3600.0;
    357   // RD_to_XY (&X, &Y, ra, dec, &image[i].coords);
    358 
    359   // XXX we can now use these values (but need to be careful about old formats)
    360   X = measure[0].Xccd;
    361   Y = measure[0].Yccd;
    362   setGridMeasure (meas, cat, X, Y, ccdnum);
    363 
    364   return (TRUE);
    365 }
    366 
    367321void matchImage (Catalog *catalog, off_t meas, int cat, int doImageList) {
    368322
    369323  off_t idx, ID;
    370   int status;
    371324  MeasureTiny *measure;
    372325 
     
    381334  catalog[cat].measureT[meas].myDet = TRUE;
    382335
    383   if (USE_GRID) {
    384     status = findCCD (idx, meas, cat, measure);
    385     if (!status) {
    386       if (VERBOSE2) fprintf (stderr, "failed to determine CCD for "OFF_T_FMT", %d\n",  meas, cat);
    387       return;
    388     }
    389   }
    390 
    391336  // index for (catalog, measure) -> image
    392337  MeasureToImage[cat][meas] = idx;
     
    440385  if (i == -1) return NAN;
    441386
    442   if (image[i].flags & IMAGE_BAD) return NAN; 
     387  // allow context dependence?: in relphot_images, we want to exclude detections from poor images
     388  // but in the final pass, we want to allow even bad detections
     389  if (image[i].flags & (ID_IMAGE_PHOTOM_POOR | ID_IMAGE_PHOTOM_FEW)) return NAN; 
    443390
    444391  switch (class) {
     
    464411  if (i == -1) return (1000);
    465412
    466   if (image[i].flags & IMAGE_BAD) return (1000); 
    467413  distance = image[i].ubercalDist; // was dummy3 in structure
    468414  return (distance);
     
    552498}
    553499
    554 float getMflat (off_t meas, int cat, FlatCorrectionTable *flatcorr, Catalog *catalog) {
    555   OHANA_UNUSED_PARAM(flatcorr);
    556 
    557   off_t i = MeasureToImage[cat][meas];
    558   if (i == -1) return (NAN);
    559 
    560   float offset = catalog[cat].measureT[meas].Mflat;
    561   if (!isfinite(offset)) {
    562     offset = 0.0;
    563   }
    564 
    565   // to do this, I need to pass in the catalog and flatcorr pointers
    566   // int flat_id = image[i].photom_map_id;
    567   // if (flat_id) {
    568   //   offset = FlatCorrectionOffset (flatcorr, flat_id, catalog[cat].measureT[meas].Xccd, catalog[cat].measureT[meas].Yccd);
    569   // }
    570 
    571   return (offset);
    572 }
    573 
    574500Coords *getCoords (off_t meas, int cat) {
    575501
     
    582508
    583509/* determine Mcal values for all images */
    584 void setMcal (Catalog *catalog, FlatCorrectionTable *flatcorr) {
     510void setMcal (Catalog *catalog) {
    585511
    586512  off_t i, j, m, c, n;
     
    690616          continue;
    691617      }
    692       float Mgrid = getMgrid (m, c);
     618      float Mgrid = getMgridTiny (&catalog[c].measureT[m]);
    693619      if (isnan(Mgrid)) {
    694620          Ngrid++;
     
    711637      // apply that offset as well here for this image (in other words, each detection is
    712638      // being compared to the model, excluding the zero point, Mcal.  The model includes
    713       // the flat-correction.  NOTE the sign of Mflat (Image.Mcal = Measure.Mcal - Mflat)
    714 
    715       float Mflat = getMflat (m, c, flatcorr, catalog);
     639      // the flat-correction.  NOTE the sign of Mflat (Image.Mcal = Measure.Mcal + Mflat)
     640      // this was inconsistent w.r.t. PhotRel pre-r41606
     641
     642      float Mflat = getMflat (m, c, catalog);
    716643
    717644      n = catalog[c].measureT[m].averef;
     
    722649      }
    723650
    724       float Moff = Mmos + Mgrp + Mgrid - Mflat;
     651      float Moff = Mmos + Mgrp + Mgrid + Mflat;
    725652
    726653      PhotCode *code = GetPhotcodebyCode (catalog[c].measureT[m].photcode);
     
    763690    if (mark) {
    764691      image[i].flags |= ID_IMAGE_PHOTOM_FEW;
     692      image[i].McalPSF    = 0.0;
     693      image[i].McalAPER   = 0.0;
     694      image[i].McalChiSq  = NAN;
    765695      image[i].dMcal      = NAN;
    766       image[i].McalChiSq  = NAN;
     696      image[i].dMagSys    = NAN;
    767697      image[i].nFitPhotom = 0;
    768698      Nfew ++;
     
    835765
    836766/* determine McalTEST values for all images -- this is not used to set measure.Mcal, but only to test */
    837 void setMcalTest (Catalog *catalog, FlatCorrectionTable *flatcorr) {
     767void setMcalTest (Catalog *catalog) {
    838768
    839769  off_t i, j, m, c, n;
     
    889819          continue;
    890820      }
    891       float Mgrid = getMgrid (m, c);
     821      float Mgrid = getMgridTiny (&catalog[c].measureT[m]);
    892822      if (isnan(Mgrid)) {
    893823          Ngrid++;
     
    905835      // apply that offset as well here for this image (in other words, each detection is
    906836      // being compared to the model, excluding the zero point, Mcal.  The model includes
    907       // the flat-correction.  NOTE the sign of Mflat (Image.Mcal = Measure.Mcal - Mflat)
    908 
    909       float Mflat = getMflat (m, c, flatcorr, catalog);
     837      // the flat-correction.  NOTE the sign of Mflat (Image.Mcal = Measure.Mcal + Mflat)
     838
     839      float Mflat = getMflat (m, c, catalog);
    910840
    911841      // get the PSF magnitude for thie measurement, with airmass slope applied
     
    917847      }
    918848
    919       float Moff = Mmos + Mgrp + Mgrid - Mflat;
     849      float Moff = Mmos + Mgrp + Mgrid + Mflat;
    920850
    921851      psfStars.alldata-> yVector[Nref] = MsysPSF - MrelPSF - Moff;
     
    968898  // measure stats for Mcal and dMcal
    969899  for (i = N = 0; i < Nimage; i++) {
    970     if (image[i].flags & IMAGE_BAD) continue;
     900    if (image[i].flags & (ID_IMAGE_PHOTOM_POOR | ID_IMAGE_PHOTOM_FEW)) continue;
    971901
    972902    if (FREEZE_IMAGES && isMosaicChip(image[i].photcode)) continue;
     
    996926
    997927    mark = FALSE;
    998     image[i].flags &= ~ID_IMAGE_PHOTOM_POOR;
    999     mark = (image[i].dMcal > MaxScatter) || (fabs(image[i].McalPSF - MedOffset) > MaxOffset);
     928
     929    if (image[i].flags & ID_IMAGE_PHOTOM_FEW) {
     930      mark = TRUE;
     931    }
     932    if (image[i].dMcal > MaxScatter) {
     933      mark = TRUE;
     934    }
     935    if (fabs(image[i].McalPSF - MedOffset) > MaxOffset) {
     936      mark = TRUE;
     937    }
     938
    1000939    if (mark) {
    1001940      Nmark ++;
     
    11461085}
    11471086
    1148 StatType statsImageN (Catalog *catalog, FlatCorrectionTable *flatcorr) {
     1087StatType statsImageN (Catalog *catalog) {
    11491088
    11501089  off_t i, j, m, c, n, N;
     
    11631102  n = 0;
    11641103  for (i = 0; i < Nimage; i++) {
    1165     if (image[i].flags & IMAGE_BAD) continue;
     1104    if (image[i].flags & (ID_IMAGE_PHOTOM_POOR | ID_IMAGE_PHOTOM_FEW)) continue;
    11661105
    11671106    if (FREEZE_IMAGES && isMosaicChip(image[i].photcode)) continue;
     
    11791118      Mgrp  = getMgrp  (m, c, catalog[c].measureT[m].airmass, NULL);
    11801119      if (isnan(Mgrp)) continue;
    1181       Mgrid = getMgrid (m, c);
     1120      Mgrid = getMgridTiny (&catalog[c].measureT[m]);
    11821121      if (isnan(Mgrid)) continue;
    11831122      N++;
     
    12121151  for (i = 0; i < Nimage; i++) {
    12131152
    1214     if (image[i].flags & IMAGE_BAD) continue;
     1153    if (image[i].flags & (ID_IMAGE_PHOTOM_POOR | ID_IMAGE_PHOTOM_FEW)) continue;
    12151154
    12161155    if (FREEZE_IMAGES && isMosaicChip(image[i].photcode)) continue;
     
    12451184  for (i = 0; i < Nimage; i++) {
    12461185
    1247     if (image[i].flags & IMAGE_BAD) continue;
     1186    if (image[i].flags & (ID_IMAGE_PHOTOM_POOR | ID_IMAGE_PHOTOM_FEW)) continue;
    12481187
    12491188    if (FREEZE_IMAGES && isMosaicChip(image[i].photcode)) continue;
     
    12781217  for (i = 0; i < Nimage; i++) {
    12791218
    1280     if (image[i].flags & IMAGE_BAD) continue;
     1219    if (image[i].flags & (ID_IMAGE_PHOTOM_POOR | ID_IMAGE_PHOTOM_FEW)) continue;
    12811220
    12821221    if (FREEZE_IMAGES && isMosaicChip(image[i].photcode)) continue;
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/MagResidSave.c

    r41561 r41649  
    192192  CHECK_STATUS (!status, "ERROR: problem closing meanmags file %s\n", filename);
    193193
     194  FitDataSetFree (&psfStars);
     195
    194196  return TRUE;
    195197}
     
    213215    off_t c = ImageToCatalog[j];
    214216     
    215     // XXX drop this?
    216217    if (catalog[c].measureT[m].dbFlags & MEAS_BAD) continue;
    217218
     
    225226    if (isnan(Mgrp)) continue;
    226227
    227     float Mgrid = getMgrid (m, c);
     228    float Mgrid = getMgridTiny (&catalog[c].measureT[m]);
    228229    if (isnan(Mgrid)) continue;
    229230
     
    231232    // apply that offset as well here for this image (in other words, each detection is
    232233    // being compared to the model, excluding the zero point, Mcal.  The model includes
    233     // the flat-correction.  NOTE the sign of Mflat (Image.Mcal = Measure.Mcal - Mflat)
    234 
    235     // float Mflat = getMflat (m, c, flatcorr, catalog);
     234    // the flat-correction.  NOTE the sign of Mflat (Image.Mcal = Measure.Mcal + Mflat)
     235
     236    float Mflat = getMflat (m, c, catalog);
    236237
    237238    // MrelPSF is the average magnitude for this star. 
     
    246247    if (isnan(MsysPSF)) continue;
    247248
    248     // XXX skip Mflat for now
    249     // float Moff = Mcal + Mmos + Mgrp + Mgrid - Mflat;
    250 
    251     float Moff = Mcal + Mmos + Mgrp + Mgrid;
     249    float Moff = Mcal + Mmos + Mgrp + Mgrid + Mflat;
    252250
    253251    // Mrel is the true average apparent magnitude of this star
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/MosaicOps.c

    r41559 r41649  
    11# include "relphot.h"
    22off_t findMosaic (unsigned int *startTimes, off_t Nmosaic, unsigned int start);
    3 int save_test_mosaic_measures (FILE *fout, int Nmos, Catalog *catalog, FlatCorrectionTable *flatcorr);
     3int save_test_mosaic_measures (FILE *fout, int Nmos, Catalog *catalog);
    44
    55// see discussion in ImagesOps.c re: IDX_T
     
    5050# undef COMPARE
    5151
    52 }
    53 
    54 /* find mosaic frames (unique time periods & photcode name matches mosaic) */
    55 void initMosaics_old (Image *image, off_t Nimage) {
    56 
    57   off_t i, j, status, found, NMOSAIC, *MosaicN_IMAGE;
    58   unsigned int start, stop;
    59   char *pname;
    60 
    61   if (!MOSAIC_ZEROPT) return;
    62 
    63   Nmosaic = 0;
    64   NMOSAIC = 10;
    65   ALLOCATE (mosaic, Mosaic, NMOSAIC);
    66 
    67   ALLOCATE (MosaicToImage, off_t *, NMOSAIC);
    68   ALLOCATE (MosaicN_Image, off_t,   NMOSAIC);
    69   ALLOCATE (MosaicN_IMAGE, off_t,   NMOSAIC);
    70 
    71   ALLOCATE (ImageToMosaic, off_t, Nimage); // mosaic to which image belongs
    72 
    73   /* a 'mosaic' in relphot is (unlike relastro) a virtual concept: there is no
    74    * entry in the image table that represents this mosaic.  Instead, it is an
    75    * internal construct that defines a group of related images
    76    */
    77 
    78   /* generate list of unique mosaics */
    79   for (i = 0; i < Nimage; i++) {
    80     ImageToMosaic[i] = -1;
    81 
    82     /* select valid mosaic images by photcode */
    83     pname = GetPhotcodeNamebyCode (image[i].photcode);
    84     status = strncmp (pname, MOSAICNAME, strlen (MOSAICNAME));
    85     if (status) continue;
    86 
    87     /* set image time range */
    88     start = image[i].tzero - MAX(0.01*image[i].trate*image[i].NY, 1);
    89     stop  = image[i].tzero + MAX(1.01*image[i].trate*image[i].NY, 1);
    90 
    91     /* find existing mosaic with this time range */
    92     found = FALSE;
    93     for (j = 0; !found && (j < Nmosaic); j++) {
    94       if (stop  < mosaic[j].start) continue;
    95       if (start > mosaic[j].stop)  continue;
    96       found = TRUE;
    97 
    98       // add reference from image to mosaic
    99       ImageToMosaic[i] = j;
    100 
    101       /* add image to mosaic image list */
    102       MosaicToImage[j][MosaicN_Image[j]] = i;
    103       MosaicN_Image[j] ++;
    104       if (MosaicN_Image[j] == MosaicN_IMAGE[j]) {
    105         MosaicN_IMAGE[j] += 10;
    106         REALLOCATE (MosaicToImage[j], off_t, MosaicN_IMAGE[j]);
    107       }
    108 
    109     }
    110     if (found) continue;
    111    
    112     /* a new mosaic, define ranges -- preserve the original values incase this image is not used */
    113     mosaic[Nmosaic].start     = start;
    114     mosaic[Nmosaic].stop      = stop;
    115     mosaic[Nmosaic].McalPSF   = 0.0; // note : at the end, mosaic.Mcal is added back to the input images
    116     mosaic[Nmosaic].McalAPER  = 0.0; // note : mosaic stores only offsets relative to the original image values
    117     mosaic[Nmosaic].dMcal     = 0.0; // note : at the end, mosaic.Mcal is added back to the input images
    118     mosaic[Nmosaic].dMsys     = 0.0;
    119     mosaic[Nmosaic].McalChiSq = 0.0;// NAN or 0.0?
    120     mosaic[Nmosaic].flags     = image[i].flags;
    121     mosaic[Nmosaic].secz      = image[i].secz;
    122     mosaic[Nmosaic].photcode  = GetPhotcodeEquivCodebyCode (image[i].photcode);
    123 
    124     // XXX do we need to do something about flag consistency across a mosaic?
    125 
    126     /* add image to mosaic image list */
    127     MosaicN_IMAGE[Nmosaic] = 10;
    128     MosaicN_Image[Nmosaic] = 1;
    129     ALLOCATE (MosaicToImage[Nmosaic], off_t, MosaicN_IMAGE[Nmosaic]);
    130     MosaicToImage[Nmosaic][0] = i;
    131 
    132     // add reference from image to mosaic
    133     ImageToMosaic[i] = Nmosaic;
    134    
    135     Nmosaic ++;
    136     if (Nmosaic == NMOSAIC) {
    137       NMOSAIC += 10;
    138       REALLOCATE (mosaic,  Mosaic,  NMOSAIC);
    139       REALLOCATE (MosaicToImage,  off_t *, NMOSAIC);
    140       REALLOCATE (MosaicN_Image, off_t,   NMOSAIC);
    141       REALLOCATE (MosaicN_IMAGE, off_t,   NMOSAIC);
    142     }
    143   }
    144 
    145   // free this or not?
    146   free (MosaicN_IMAGE);
    147 
    148   initMosaicGrid (image, Nimage);
    149 
    150   fprintf (stderr, "matched %d images to %d mosaics\n", (int) Nimage, (int) Nmosaic);
    151   return;
    15252}
    15353
     
    318218  free (startTimesMosaic);
    319219
    320   initMosaicGrid (subset, Nsubset);
     220  initMosaicMcal (subset, Nsubset);
    321221
    322222  fprintf (stderr, "matched %d images to %d mosaics, %d simple chips not matched to mosaics\n", (int) (Nsubset - Nsimple), (int) Nmosaic, (int) Nsimple);
     
    460360
    461361  if (mergeMcal) {
    462     initMosaicGrid (image, Nimage);
     362    initMosaicMcal (image, Nimage);
    463363  }
    464364
     
    511411}
    512412
     413// this function sets mosaic->coords to the median of the individual chips.  This
     414// coordinate frame is used by the parallel region analysis to assign exposures (mosaics)
     415// to specific machines by a single center (rather than individual chips)
    513416void setMosaicCenters (Image *image, off_t Nimage) {
    514417  OHANA_UNUSED_PARAM(Nimage);
     
    599502    mosaic[i].coords.cdelt1 = 1.0 / 3600.0;
    600503    mosaic[i].coords.cdelt2 = 1.0 / 3600.0;
    601 
    602     mosaic[i].McalPSF   = 0.0;
    603     mosaic[i].McalAPER  = 0.0;
    604     mosaic[i].dMcal     = 0.0;
    605     mosaic[i].dMsys     = 0.0;
    606     mosaic[i].McalChiSq = 0.0;
    607504  }
    608505  return;
    609506}
    610507
    611 void initMosaicGrid (Image *image, off_t Nimage) {
     508void initMosaicMcal (Image *image, off_t Nimage) {
    612509  OHANA_UNUSED_PARAM(Nimage);
    613510
    614   /* find max dR, dD range for all mosaics */
    615   /* define mosaic.coords to cover dR, dD */
    616   /* send results to initGridBins */
    617 
    618   off_t i, j, m, NX, NY;
    619   int dXmax, dYmax;
    620   double dS, dX, dY;
    621   double R, D, Rmin, Rmax, Dmin, Dmax;
    622511  double McalPSF, McalAPER, dMcal, McalChiSq;
    623512
    624513  fprintf (stderr, "*** moving Mcal from image.Mcal to mosaic.Mcal ***\n");
    625514
    626   dXmax = dYmax = 0.0;
    627   for (i = 0; i < Nmosaic; i++) {
    628     Dmin = Rmin =  360.0;
    629     Dmax = Rmax = -360.0;
    630     dS = 0.0;
     515  for (off_t i = 0; i < Nmosaic; i++) {
    631516    McalPSF = McalAPER = dMcal = McalChiSq = 0;
    632     for (j = 0; j < MosaicN_Image[i]; j++) {
    633       m = MosaicToImage[i][j];
    634       NX = image[m].NX;
    635       NY = image[m].NY;
    636       dS += hypot (image[m].coords.cdelt1*image[m].coords.pc1_1, image[m].coords.cdelt1*image[m].coords.pc2_1);
    637 
    638       OhanaProjection proj = GetProjection (image[m].coords.ctype);
    639       if ((proj == PROJ_WRP) && !image[m].coords.mosaic) {
    640         XY_to_LM (&R, &D, 0.0, 0.0, &image[m].coords);
    641       } else {
    642         XY_to_RD (&R, &D, 0.0, 0.0, &image[m].coords);
    643       }
    644       Rmin = MIN (Rmin, R);
    645       Rmax = MAX (Rmax, R);
    646       Dmin = MIN (Dmin, D);
    647       Dmax = MAX (Dmax, D);
    648 
    649       if ((proj == PROJ_WRP) && !image[m].coords.mosaic) {
    650         XY_to_LM (&R, &D, (double) NX, 0.0, &image[m].coords);
    651       } else {
    652         XY_to_RD (&R, &D, (double) NX, 0.0, &image[m].coords);
    653       }
    654       Rmin = MIN (Rmin, R);
    655       Rmax = MAX (Rmax, R);
    656       Dmin = MIN (Dmin, D);
    657       Dmax = MAX (Dmax, D);
    658 
    659       if ((proj == PROJ_WRP) && !image[m].coords.mosaic) {
    660         XY_to_LM (&R, &D, (double) NX, (double) NY, &image[m].coords);
    661       } else {
    662         XY_to_RD (&R, &D, (double) NX, (double) NY, &image[m].coords);
    663       }
    664       Rmin = MIN (Rmin, R);
    665       Rmax = MAX (Rmax, R);
    666       Dmin = MIN (Dmin, D);
    667       Dmax = MAX (Dmax, D);
    668 
    669       if ((proj == PROJ_WRP) && !image[m].coords.mosaic) {
    670         XY_to_LM (&R, &D, 0.0, (double) NY, &image[m].coords);
    671       } else {
    672         XY_to_RD (&R, &D, 0.0, (double) NY, &image[m].coords);
    673       }
    674       Rmin = MIN (Rmin, R);
    675       Rmax = MAX (Rmax, R);
    676       Dmin = MIN (Dmin, D);
    677       Dmax = MAX (Dmax, D);
    678 
    679       // XXX : this probably does not handle mosaics at RA = 0,360 well
    680 
    681       /* we are using mosaic.Mcal, not image.Mcal. reset image.Mcal */
    682 
    683       // XXX: how does this work with UBERCAL?  We want to keep the Mcal values supplied by ubercal, but
    684       // solve for a single offset for each exposure (Mosaic.Mcal). 
    685       // we also want to keep the flat-field terms for each exposure (regardless of ubercal or not)
    686       // if it helps, note that ubercal uses a single zp per exposure, so the mean of those values is the same as the value
     517    for (off_t j = 0; j < MosaicN_Image[i]; j++) {
     518      off_t m = MosaicToImage[i][j];
    687519
    688520      if (!isfinite(image[m].McalPSF)) {
    689         image[m].McalPSF = 0.0;
    690         image[m].McalAPER = 0.0;
    691         image[m].dMcal = 0.0;
     521        image[m].McalPSF   = 0.0;
     522        image[m].McalAPER  = 0.0;
     523        image[m].dMcal     = 0.0;
    692524        image[m].McalChiSq = 0.0;
    693525        fprintf (stderr, "warning: resetting NAN value for Mcal %s\n", image[m].name);
     
    703535      image[m].dMcal     = NAN;
    704536      image[m].McalChiSq = NAN;
    705 
    706     }
    707     dS /= MosaicN_Image[i];
    708 
    709     InitCoords (&mosaic[i].coords, "DEC--TAN");
    710     mosaic[i].coords.crval1 = Rmin;
    711     mosaic[i].coords.crval2 = Dmin;
    712     mosaic[i].coords.cdelt1 = dS;
    713     mosaic[i].coords.cdelt2 = dS;
    714 
    715     RD_to_XY (&dX, &dY, Rmax, Dmax, &mosaic[i].coords);
     537    }
    716538
    717539    mosaic[i].McalPSF   = McalPSF / MosaicN_Image[i];
     
    720542    mosaic[i].McalChiSq = McalChiSq / MosaicN_Image[i];
    721543  }
    722   if (!USE_GRID) return;
    723 
    724   dXmax = MAX (dXmax, dX);
    725   dYmax = MAX (dYmax, dY);
    726   initGrid (dXmax, dYmax);
    727544  return;
    728545}
     
    963780  if (i == -1) return (0.0);
    964781
    965   if (mosaic[i].flags & IMAGE_BAD) return (NAN); 
     782  // if the mosaic cannot be calibrated (too few measurements, skip it)
     783  // XXX: if the mosaic is bad (few) but the chips are OK, I can used them.
     784  // XXX: if (mosaic[i].flags & ID_IMAGE_PHOTOM_FEW) return (NAN); 
    966785  value = mosaic[i].McalPSF;
    967786  return (value);
     
    1001820  Catalog *catalog;
    1002821  Image *image;
    1003   FlatCorrectionTable *flatcorr;
    1004822  SetMmosInfo info;
    1005823} ThreadInfo;
    1006824
    1007 int setMmos_mosaic (Mosaic *mosaic, off_t Nmos, Image *image, Catalog *catalog, SetMmosInfo *info, FlatCorrectionTable *flatcorr);
     825int setMmos_mosaic (Mosaic *mosaic, off_t Nmos, Image *image, Catalog *catalog, SetMmosInfo *info);
    1008826void *setMmos_worker (void *data);
    1009 int setMmos_threaded (Catalog *catalog, FlatCorrectionTable *flatcorr);
     827int setMmos_threaded (Catalog *catalog);
    1010828
    1011829void SetMmosInfoInit (SetMmosInfo *info, off_t Nmax, int allocLists) {
     
    1073891}
    1074892
    1075 int setMmos (Catalog *catalog, FlatCorrectionTable *flatcorr) {
     893int setMmos (Catalog *catalog) {
    1076894
    1077895  off_t i, N, Nmax;
     
    1086904  // so do not run setMmos in threaded mode if PLOTSTUFF is set
    1087905  if (NTHREADS && !PLOTSTUFF) {
    1088     int status = setMmos_threaded (catalog, flatcorr);
     906    int status = setMmos_threaded (catalog);
    1089907    return status;
    1090908  }
     
    1106924
    1107925  for (i = 0; i < Nmosaic; i++) {
    1108     setMmos_mosaic (&mosaic[i], i, image, catalog, &info, flatcorr);
     926    setMmos_mosaic (&mosaic[i], i, image, catalog, &info);
    1109927  }
    1110928  SetMmosInfoFree (&info);
     
    1123941 
    1124942// 'mosaic' is a pointer to the current mosaic of interest (Nmos)
    1125 int setMmos_mosaic (Mosaic *myMosaic, off_t Nmos, Image *image, Catalog *catalog, SetMmosInfo *info, FlatCorrectionTable *flatcorr) {
     943int setMmos_mosaic (Mosaic *myMosaic, off_t Nmos, Image *image, Catalog *catalog, SetMmosInfo *info) {
    1126944
    1127945  off_t j, NimageReal;
     
    12041022    snprintf (filename, 64, "test.%05d.%02d.dat", (int) Nmos, npass_output);
    12051023    fout = fopen (filename, "w");
    1206     save_test_mosaic_measures (fout, Nmos, catalog, flatcorr);
     1024    save_test_mosaic_measures (fout, Nmos, catalog);
    12071025    fclose (fout);
    12081026  }
     
    12311049      continue;
    12321050    }
    1233     float Mgrid = getMgrid (m, c);
     1051    float Mgrid = getMgridTiny (&catalog[c].measureT[m]);
    12341052    if (isnan(Mgrid)) {
    12351053      info->Ngrid ++;
     
    12531071    // apply that offset as well here for this image (in other words, each detection is
    12541072    // being compared to the model, excluding the zero point, Mcal.  The model includes
    1255     // the flat-correction.  NOTE the sign of Mflat (Image.Mcal = Measure.Mcal - Mflat)
    1256 
    1257     float Mflat = getMflat (m, c, flatcorr, catalog);
     1073    // the flat-correction.  NOTE the sign of Mflat (Image.Mcal = Measure.Mcal + Mflat).
     1074    // this was inconsistent pre r41606
     1075
     1076    float Mflat = getMflat (m, c, catalog);
    12581077
    12591078    off_t n = catalog[c].measureT[m].averef;
     
    12781097    assert (Nbright >= 0);
    12791098
    1280     float Moff =  Mcal + Mgrp + Mgrid - Mflat;
     1099    float Moff =  Mcal + Mgrp + Mgrid + Mflat;
    12811100
    12821101    psfStars->alldata-> yVector[N] = MsysPSF - MrelPSF - Moff;
     
    13701189}
    13711190 
    1372 int save_test_mosaic_measures (FILE *fout, int Nmos, Catalog *catalog, FlatCorrectionTable *flatcorr) {
     1191int save_test_mosaic_measures (FILE *fout, int Nmos, Catalog *catalog) {
    13731192
    13741193  int Nsecfilt = GetPhotcodeNsecfilt ();
     
    13821201    float Mcal     = getMcal  (m, c, MAG_CLASS_PSF);
    13831202    // float Mgrp     = getMgrp  (m, c, catalog[c].measureT[m].airmass, NULL);
    1384     float Mgrid    = getMgrid (m, c);
     1203    float Mgrid    = getMgridTiny (&catalog[c].measureT[m]);
    13851204    float MrelPSF  = getMrel  (catalog, m, c, MAG_CLASS_PSF, MAG_SRC_CHP);
    1386     float Mflat    = getMflat (m, c, flatcorr, catalog);
     1205    float Mflat    = getMflat (m, c, catalog);
    13871206
    13881207    off_t n = catalog[c].measureT[m].averef;
    13891208    float MsysPSF = PhotSysTiny (&catalog[c].measureT[m], &catalog[c].averageT[n], &catalog[c].secfilt[n*Nsecfilt], MAG_CLASS_PSF);
    13901209   
    1391     float delta = MsysPSF - MrelPSF - Mcal - Mgrid + Mflat;
     1210    float delta = MsysPSF - MrelPSF - Mcal - Mgrid - Mflat;
    13921211
    13931212    int isBad = (catalog[c].measureT[m].dbFlags & MEAS_BAD);
     
    13981217}
    13991218
    1400 int setMmos_threaded (Catalog *catalog, FlatCorrectionTable *flatcorr) {
     1219int setMmos_threaded (Catalog *catalog) {
    14011220
    14021221  int i;
     
    14351254    threadinfo[i].catalog  =  catalog;
    14361255    threadinfo[i].image    =    image;
    1437     threadinfo[i].flatcorr = flatcorr;
    14381256
    14391257    // we do NOT allocate the arrays here, we only supply basic info (Nmax, Nloop) used in
     
    14811299           summary.Nskip);
    14821300  free (threadinfo);
     1301  // XXX SetMmosInfoFree (&summary);
    14831302
    14841303  npass_output ++;
     
    15031322
    15041323    Catalog *catalog = threadinfo->catalog;
    1505     FlatCorrectionTable *flatcorr = threadinfo->flatcorr;
    15061324    Image *image = threadinfo->image;
    15071325
    1508     setMmos_mosaic (&mosaic[i], i, image, catalog, &results, flatcorr);
     1326    setMmos_mosaic (&mosaic[i], i, image, catalog, &results);
    15091327    SetMmosInfoAccum (&threadinfo->info, &results);
    15101328  }
     
    15121330  SetMmosInfoFree (&results);
    15131331  return NULL;
    1514 }
    1515 
    1516 // When we rationalize the images/mosaics, we are driving the negative cloud images back
    1517 // to 0.0.  At the same time, we make a guess to the effective impact on all other images,
    1518 // driven by the coupling of common stars.
    1519 // XXX this function is no longer used because we force significantly negative clouds to 0.0
    1520 int rationalize_mosaics (Catalog *catalog, int Ncatalog) {
    1521 
    1522   double *imageOffset, **starOffset;
    1523   int **starNcount, *seclist;
    1524   int **Slist, *NSlist, *NSLIST;
    1525   int i, j, k, m, nMos, Ns, found;
    1526 
    1527   off_t Nimage;
    1528   Image *image;
    1529 
    1530   // set a test value for now
    1531   float CLOUD_TOLERANCE = 0.025;
    1532 
    1533   if (!MOSAIC_ZEROPT) return (FALSE);
    1534   if (FREEZE_MOSAICS) return (FALSE);
    1535 
    1536   image = getimages (&Nimage, NULL);
    1537 
    1538   ALLOCATE (imageOffset, double, Nmosaic);
    1539   ALLOCATE ( Slist, int *, Nmosaic); // array of calibrated star indexes on this mosaic
    1540   ALLOCATE (NSlist, int,   Nmosaic); // number of stars on mosaic
    1541   ALLOCATE (NSLIST, int,   Nmosaic); // number of Slist entries allocated
    1542   memset (Slist, 0, Nmosaic*sizeof(int *));
    1543 
    1544   // find the images / mosaics with negative clouds and save their offset
    1545   for (i = 0; i < Nmosaic; i++) {
    1546  
    1547     NSlist[i] =   0;
    1548     NSLIST[i] = 100;
    1549     ALLOCATE (Slist[i], int, NSLIST[i]);
    1550 
    1551     imageOffset[i] = 0.0;
    1552 
    1553     if (VERBOSE2 && (fabs(mosaic[i].McalPSF) < CLOUD_TOLERANCE)) {
    1554       fprintf (stderr, "cloud-free: %s : %f\n", image[MosaicToImage[i][0]].name, mosaic[i].McalPSF);
    1555     }
    1556     if (VERBOSE2 && (mosaic[i].McalPSF < -CLOUD_TOLERANCE)) {
    1557       imageOffset[i] = -mosaic[i].McalPSF;
    1558       // NOTE the negative sign: down below, we are going to add in the negative of McalPSF
    1559       // to this image, and the propagated mean values for other images
    1560       fprintf (stderr, "anti-clouds: %s : %f\n", image[MosaicToImage[i][0]].name, mosaic[i].McalPSF);
    1561     }
    1562     if (VERBOSE2 && (mosaic[i].McalPSF > CLOUD_TOLERANCE)) {
    1563       fprintf (stderr, "cloudy    : %s : %f\n", image[MosaicToImage[i][0]].name, mosaic[i].McalPSF);
    1564     }
    1565   }
    1566 
    1567   int Nsecfilt = GetPhotcodeNsecfilt ();
    1568   ALLOCATE (seclist, int, Nphotcodes);
    1569   for (Ns = 0; Ns < Nphotcodes; Ns ++) {
    1570     int thisCode = photcodes[Ns][0].code;
    1571     seclist[Ns] = GetPhotcodeNsec(thisCode);
    1572   }
    1573 
    1574   // allocate an array for star offsets
    1575   int Nstars = 0;
    1576   int NSTARS = 1000;
    1577   ALLOCATE (starOffset, double *, NSTARS);
    1578   ALLOCATE (starNcount, int *,    NSTARS);
    1579   memset (starOffset, 0, NSTARS*sizeof(double *));
    1580   memset (starNcount, 0, NSTARS*sizeof(int *));
    1581 
    1582   // find the mean offset for each star
    1583   for (i = 0; i < Ncatalog; i++) {
    1584     for (j = 0; j < catalog[i].Naverage; j++) {
    1585       ALLOCATE (starOffset[Nstars], double, Nphotcodes);
    1586       ALLOCATE (starNcount[Nstars], int,    Nphotcodes);
    1587       memset (starOffset[Nstars], 0, Nphotcodes*sizeof(double));
    1588       memset (starNcount[Nstars], 0, Nphotcodes*sizeof(int));
    1589      
    1590       m = catalog[i].averageT[j].measureOffset;
    1591 
    1592       // determine the mosaic for each measurement
    1593       for (k = 0; k < catalog[i].averageT[j].Nmeasure; k++, m++) {
    1594 
    1595         // skip unused measurements
    1596         if (catalog[i].measureT[m].dbFlags & MEAS_BAD) continue;
    1597 
    1598         // skip unused measurements
    1599 
    1600         // XXX replace with:
    1601         // Ns = GetActivePhotcodeIndex (photcode);
    1602         // if (Ns < 0) continue;
    1603 
    1604         int Nsec;
    1605         int ecode = GetPhotcodeEquivCodebyCode (catalog[i].measureT[m].photcode);
    1606         found = FALSE;
    1607         for (Ns = 0; !found && (Ns < Nphotcodes); Ns ++) {
    1608           if (ecode == photcodes[Ns][0].code) {
    1609             found = TRUE;
    1610             break;
    1611           }
    1612         }
    1613         if (!found) continue;
    1614         Nsec = seclist[Ns];
    1615 
    1616         // bad stars for this secfilt
    1617         if (catalog[i].secfilt[Nsecfilt*j+Nsec].flags & STAR_BAD) continue; 
    1618 
    1619         // skip REF measurements (not tied to an image)
    1620         if (getImageEntry (m, i) < 0) continue;
    1621 
    1622         // find the source of this measurement (skip unassigned measurements)
    1623         nMos = MeasureToMosaic[i][m];
    1624         if (nMos == -1) continue;
    1625 
    1626         // XXX how can this not be true? 
    1627         if (mosaic[nMos].photcode != ecode) {
    1628           fprintf (stderr, "*");
    1629         }
    1630 
    1631         assert (Ns >= 0);
    1632         assert (Ns < Nphotcodes);
    1633 
    1634         // accumulate the offsets from the negative cloud images (others have 0.0 value)
    1635         starOffset[Nstars][Ns] += imageOffset[nMos];
    1636         starNcount[Nstars][Ns] ++;
    1637        
    1638         // record the mosaic->star reference
    1639         Slist[nMos][NSlist[nMos]] = Nstars;
    1640         NSlist[nMos] ++;
    1641         if (NSlist[nMos] == NSLIST[nMos]) {
    1642           NSLIST[nMos] += 100;
    1643           REALLOCATE (Slist[nMos], int, NSLIST[nMos]);
    1644         }         
    1645       }
    1646       Nstars ++;
    1647       if (Nstars == NSTARS) {
    1648         NSTARS += 1000;
    1649         REALLOCATE (starOffset, double *, NSTARS);
    1650         REALLOCATE (starNcount, int *,    NSTARS);
    1651         memset (&starOffset[NSTARS-1000], 0, 1000*sizeof(double *));
    1652         memset (&starNcount[NSTARS-1000], 0, 1000*sizeof(int *));
    1653       }
    1654     }
    1655   }
    1656 
    1657   // find the mean offset of the images without negative clouds
    1658   for (i = 0; i < Nmosaic; i++) {
    1659 
    1660     found = FALSE;
    1661     for (Ns = 0; !found && (Ns < Nphotcodes); Ns ++) {
    1662       if (mosaic[i].photcode == photcodes[Ns][0].code) {
    1663         found = TRUE;
    1664         break;
    1665       }
    1666     }
    1667     if (!found) {
    1668       fprintf (stderr, "invalid photcode for mosaic?\n");
    1669       abort();
    1670     }
    1671 
    1672     // a negative cloud image (cloud: McalPSF > 0; anti-clouds: McalPSF < 0; imageOffset = -McalPSF)
    1673     if (imageOffset[i] > 0.0) continue;
    1674 
    1675     // we need to actually have cross-references to count
    1676     if (NSlist[i] < 2) continue;
    1677 
    1678     float dM = 0.0;
    1679     for (j = 0; j < NSlist[i]; j++) {
    1680       k = Slist[i][j];
    1681       if (starNcount[k][Ns] > 1) {
    1682         dM += (starOffset[k][Ns] / starNcount[k][Ns]);
    1683       }
    1684     }
    1685     imageOffset[i] = dM / NSlist[i];
    1686     // fprintf (stderr, "adjust image: %s : (%f %d) : %f\n", image[MosaicToImage[i][0]].name, dM, NSlist[i], imageOffset[i]);
    1687   }
    1688 
    1689   // for (i = 0; i < Nmosaic; i++) {
    1690   //   fprintf (stderr, "correction: %s : %f\n", image[MosaicToImage[i][0]].name, imageOffset[i]);
    1691   // }
    1692 
    1693   // apply all offset values to the mosaics
    1694   // find the images / mosaics with negative clouds and save their offset
    1695   for (i = 0; i < Nmosaic; i++) {
    1696     mosaic[i].McalPSF += imageOffset[i];
    1697   }
    1698 
    1699   for (i = 0; i < Nstars; i++) {
    1700     free (starOffset[i]);
    1701     free (starNcount[i]);
    1702   }
    1703   free (starOffset);
    1704   free (starNcount);
    1705 
    1706   free (seclist);
    1707   free (NSlist);
    1708   free (NSLIST);
    1709   for (i = 0; i < Nmosaic; i++){
    1710     free (Slist[i]);
    1711   }
    1712   free (Slist);
    1713   free (imageOffset);
    1714   return (TRUE);
    17151332}
    17161333
     
    17311348  n = 0;
    17321349  for (i = 0; i < Nmosaic; i++) {
    1733     if (mosaic[i].flags & IMAGE_BAD) continue;
     1350    if (mosaic[i].flags & (ID_IMAGE_MOSAIC_POOR | ID_IMAGE_PHOTOM_FEW)) continue;
    17341351    if (mosaic[i].skipCal) continue;
    17351352    if (KEEP_UBERCAL && (mosaic[i].flags & ID_IMAGE_PHOTOM_UBERCAL)) continue;
     
    17641381  n = 0;
    17651382  for (i = 0; i < Nmosaic; i++) {
    1766     if (mosaic[i].flags & IMAGE_BAD) continue;
     1383    if (mosaic[i].flags & (ID_IMAGE_MOSAIC_POOR | ID_IMAGE_PHOTOM_FEW)) continue;
    17671384    if (mosaic[i].skipCal) continue;
    17681385    if (KEEP_UBERCAL && (mosaic[i].flags & ID_IMAGE_PHOTOM_UBERCAL)) continue;
     
    17811398}
    17821399
    1783 StatType statsMosaicN (Catalog *catalog, FlatCorrectionTable *flatcorr) {
     1400StatType statsMosaicN (Catalog *catalog) {
    17841401
    17851402  off_t i, j, m, c, n, N;
     
    17971414  n = 0;
    17981415  for (i = 0; i < Nmosaic; i++) {
    1799     if (mosaic[i].flags & IMAGE_BAD)  continue;
     1416    if (mosaic[i].flags & (ID_IMAGE_MOSAIC_POOR | ID_IMAGE_PHOTOM_FEW))  continue;
    18001417    if (mosaic[i].skipCal) continue;
    18011418    if (KEEP_UBERCAL && (mosaic[i].flags & ID_IMAGE_PHOTOM_UBERCAL)) continue;
     
    18111428      Mgrp = getMgrp  (m, c, catalog[c].measureT[m].airmass, NULL);
    18121429      if (isnan(Mgrp)) continue;
    1813       Mgrid = getMgrid (m, c);
     1430      Mgrid = getMgridTiny (&catalog[c].measureT[m]);
    18141431      if (isnan(Mgrid)) continue;
    18151432      Mrel = getMrel  (catalog, m, c, MAG_CLASS_PSF, MAG_SRC_CHP);
     
    18471464  n = 0;
    18481465  for (i = 0; i < Nmosaic; i++) {
    1849     if (mosaic[i].flags & IMAGE_BAD) continue;
     1466    if (mosaic[i].flags & (ID_IMAGE_MOSAIC_POOR | ID_IMAGE_PHOTOM_FEW)) continue;
    18501467    if (mosaic[i].skipCal) continue;
    18511468    if (KEEP_UBERCAL && (mosaic[i].flags & ID_IMAGE_PHOTOM_UBERCAL)) continue;
     
    18661483/* mark mosaic if: abs(Mcal - <Mcal>) too large, dMcal too large */
    18671484
    1868 static float MinMaxChiSq = NAN;
    1869 static float MinMaxScatter = NAN;
     1485static float MinChiSqLim = NAN;
     1486static float MaxChiSqLim = NAN;
     1487static float MinScatterLim = NAN;
     1488static float MaxScatterLim = NAN;
    18701489
    18711490void clean_mosaics () {
     
    18771496
    18781497  if (VERBOSE) fprintf (stderr, "marking poor mosaics\n");
     1498
     1499  if (isnan (MaxChiSqLim))   MaxChiSqLim   = MOSAIC_CHISQ;
     1500  if (isnan (MaxScatterLim)) MaxScatterLim = MOSAIC_SCATTER;
    18791501
    18801502  ALLOCATE (mlist, double, Nmosaic);
     
    18991521  liststats (mlist, NULL, NULL, N, &stats);
    19001522  float ChiSqUpper90 = stats.Upper90;
    1901   if (isnan (MinMaxChiSq)) MinMaxChiSq = 2.0*stats.median;
    1902   float MaxChiSq = MAX (MinMaxChiSq, ChiSqUpper90);
     1523  if (isnan (MinChiSqLim)) MinChiSqLim = 2.0*stats.median;             // chi-square cut cannot fall below this value (even if this is > MaxChiSqLim)
     1524  float ChiSqLimit = MAX(MinChiSqLim, MIN(MaxChiSqLim, ChiSqUpper90)); // chi-square cut should be between MinChiSqLim and MaxChiSqLim
    19031525
    19041526  liststats (slist, NULL, NULL, N, &stats);
    19051527  float ScatterUpper90 = stats.Upper90;
    1906   if (isnan (MinMaxScatter)) MinMaxScatter = 2.0*stats.median;
    1907   float MaxScatter = MAX (MinMaxScatter, ScatterUpper90);
    1908 
    1909   fprintf (stderr, "MOSAIC: Max ChiSq: %f, Max Scatter: %f | ChiSquare Upper 90: %f, Scatter Upper 90: %f\n", MaxChiSq, MaxScatter, ChiSqUpper90, ScatterUpper90);
     1528  if (isnan (MinScatterLim)) MinScatterLim = 2.0*stats.median;         // scatter cut cannto fall below this value (even if this is > MaxScatterLim)
     1529  float ScatterLimit = MAX(MinScatterLim, MIN(MaxScatterLim, ScatterUpper90));
     1530
     1531  fprintf (stderr, "MOSAIC: ChiSqLimit: %f, ScatterLimit: %f | ChiSquare Upper 90: %f, Scatter Upper 90: %f\n", ChiSqLimit, ScatterLimit, ChiSqUpper90, ScatterUpper90);
    19101532 
    19111533  int Ntotal = 0, Npoor = 0, Nmark = 0, Nscatter = 0, Nfew = 0, Nchisq = 0;
     
    19301552      Nfew ++;
    19311553    }
    1932     if (mosaic[i].stdev > MaxScatter) {
     1554    if (mosaic[i].stdev > ScatterLimit) {
    19331555      mark = TRUE;
    19341556      Nscatter ++;
    19351557    }
    1936     if (mosaic[i].McalChiSq > MaxChiSq) {
     1558    if (mosaic[i].McalChiSq > ChiSqLimit) {
    19371559      mark = TRUE;
    19381560      Nchisq ++;
     
    19791601      c = MosaicToCatalog[i][j];
    19801602     
    1981       if (catalog[c].measureT[m].dbFlags & (ID_MEAS_AREA | ID_MEAS_NOCAL)) continue;
     1603      if (catalog[c].measureT[m].dbFlags & MEAS_BAD) continue;
    19821604
    19831605      // ave = catalog[c].measureT[m].averef;
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/Shutdown.c

    r38986 r41649  
    1010int Shutdown (char *format, ...) { 
    1111  va_list argp;
    12   char *formatplus;
     12  char formatplus[1024];
    1313 
    14   ALLOCATE (formatplus, char, strlen(format));
    15   strcpy (formatplus, format);
    16   strcat (formatplus, "\n");
     14  // we cannot allocate this with the ohana allocation tools
     15  // because it could deadlock
     16  snprintf (formatplus, 1024, "%s\n", format);
    1717
    1818  va_start (argp, format);
    1919  vfprintf (stderr, formatplus, argp);
    20   free (formatplus);
    2120  va_end (argp);
    2221
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/StarOps.c

    r41556 r41649  
    11# include "relphot.h"
     2
     3# define STAR_BAD (ID_SECF_STAR_FEW | ID_SECF_STAR_POOR)
    24
    35enum {THREAD_RUN, THREAD_DONE};
     
    810  Catalog *catalog;
    911  int Ncatalog;
    10   FlatCorrectionTable *flatcorr;
    1112  SetMrelInfo summary;
    1213} ThreadInfo;
     
    1415// ** internal functions:
    1516void *setMrel_worker (void *data);
    16 int setMrel_threaded (Catalog *catalog, int Ncatalog, FlatCorrectionTable *flatcorr);
    17 int setMrel_catalog (Catalog *catalog, int Nc, int pass, FlatCorrectionTable *flatcorr, SetMrelInfo *results, int Nsecfilt);
     17int setMrel_threaded (Catalog *catalog, int Ncatalog);
    1818int print_measure_set (Average *average, SecFilt *secfilt, Measure *measure);
    1919
     
    292292
    293293// setMrel and setMrelOutput are extremely similar, but have slightly different implications:
    294 // * setMrel uses the internal Tiny structures only
    295 // * setMrelOutput skips stars for which there are too few good measurements
    296 // * setMrelOutput is meant to be called repeatedly, relaxing the criteria for 'good' on each pass
     294// * both call setMrelCatalog, but setMrel set isSetMrelFinal to FALSE
     295// * setMrel only uses the internal Tiny structures
     296// * setMrel skips stars for which there are too few good measurements
     297// -> (setMrelOutput assigns an average mag for all objects, even those with only 1 measurement)
     298// * setMrelOutput sets psfQF, psfQFperf, extNsigma, rank info, etc
     299// * setMrelOutput sets average Map
    297300// * setMrelOutput updates 2MASS average flags
    298301// * setMrelOutput updates average EXT flags (PS1 and 2MASS)
    299 
    300 int setMrel (Catalog *catalog, int Ncatalog, FlatCorrectionTable *flatcorr) {
     302// * setMrelOutput sets average stack & warp photometry (if requested), setMrel always skips those
     303// * setMrelOutput is NOT threaded it reads/writes catalogs one at a time
     304
     305int setMrel (Catalog *catalog, int Ncatalog) {
    301306
    302307  int i;
    303308
    304309  if (NTHREADS) {
    305     int status = setMrel_threaded (catalog, Ncatalog, flatcorr);
     310    int status = setMrel_threaded (catalog, Ncatalog);
    306311    return status;
    307312  }
     
    314319
    315320  for (i = 0; i < Ncatalog; i++) {
    316     setMrel_catalog_alt (catalog, i, FALSE, flatcorr, &results, Nsecfilt);
     321    setMrelCatalog (catalog, i, FALSE, &results, Nsecfilt);
    317322    SetMrelInfoAccum (&summary, &results);
    318323  }
     
    325330}
    326331
    327 // setMrelOutput is NOT threaded because we read/write catalogs one at a time (for now)
    328 int setMrelOutput (Catalog *catalog, int Ncatalog, FlatCorrectionTable *flatcorr) {
     332int setMrelOutput (Catalog *catalog, int Ncatalog) {
    329333
    330334  int i;
     
    337341
    338342  for (i = 0; i < Ncatalog; i++) {
    339     setMrel_catalog_alt (catalog, i, TRUE, flatcorr, &results, Nsecfilt);
     343    setMrelCatalog (catalog, i, TRUE, &results, Nsecfilt);
    340344    SetMrelInfoAccum (&summary, &results);
    341345  }
     
    347351}
    348352
    349 int setMrel_threaded (Catalog *catalog, int Ncatalog, FlatCorrectionTable *flatcorr) {
     353int setMrel_threaded (Catalog *catalog, int Ncatalog) {
    350354
    351355  int i;
     
    374378    threadinfo[i].catalog  =  catalog;
    375379    threadinfo[i].Ncatalog = Ncatalog;
    376     threadinfo[i].flatcorr = flatcorr;
    377380    SetMrelInfoInit (&threadinfo[i].summary, FALSE);
    378381    pthread_create (&threads[i], NULL, setMrel_worker, &threadinfo[i]);
     
    435438
    436439    Catalog *catalog = threadinfo->catalog;
    437     FlatCorrectionTable *flatcorr = threadinfo->flatcorr;
    438 
    439     setMrel_catalog_alt (catalog, i, FALSE, flatcorr, &results, Nsecfilt);
     440
     441    setMrelCatalog (catalog, i, FALSE, &results, Nsecfilt);
    440442    SetMrelInfoAccum (&threadinfo->summary, &results);
    441443  }
     
    444446  return NULL;
    445447}
    446 
    447 # define SKIP_THIS_MEAS(REASON) {                               \
    448     catalog[Nc].measureT[m].dbFlags |= ID_MEAS_SKIP_PHOTOM;     \
    449     if (catalog[Nc].measure) {                                  \
    450       catalog[Nc].measure [m].dbFlags |= ID_MEAS_SKIP_PHOTOM;   \
    451     }                                                           \
    452     results->REASON ++;                                         \
    453     continue; }
    454 
    455448
    456449int print_measure_set (Average *average, SecFilt *secfilt, Measure *measure) {
     
    473466}
    474467
    475 /* set measure.Mcal for all measures except ID_MEAS_NOCAL and ID_IMAGE_PHOTOM_NOCAL */
    476 int setMcalOutput (Catalog *catalog, int Ncatalog, FlatCorrectionTable *flatcorr) {
     468/* set measure.Mcal for all measures except ID_MEAS_NOCAL */
     469int setMcalOutput (Catalog *catalog, int Ncatalog) {
    477470
    478471  int i;
    479472  off_t j, k, m;
    480473
    481   MEAS_BAD = ID_MEAS_NOCAL;
    482   IMAGE_BAD = ID_IMAGE_PHOTOM_NOCAL;
    483 
    484474  for (i = 0; i < Ncatalog; i++) {
    485475    for (j = 0; j < catalog[i].Naverage; j++) {
     
    487477      m = catalog[i].averageT[j].measureOffset;
    488478      for (k = 0; k < catalog[i].averageT[j].Nmeasure; k++, m++) {
    489         if (catalog[i].measureT[m].dbFlags & MEAS_BAD) continue;
     479        if (catalog[i].measureT[m].dbFlags & ID_MEAS_NOCAL) continue;
    490480        float McalPSF  = getMcal  (m, i, MAG_CLASS_PSF);
    491481        float McalAPER = getMcal  (m, i, MAG_CLASS_APER);
    492482        if (isnan(McalPSF)) continue;
    493         float Mmos  = getMmos  (m, i);
    494         if (isnan(Mmos)) continue;
    495         float Mgrp  = getMgrp  (m, i, catalog[i].measureT[m].airmass, NULL);
    496         if (isnan(Mgrp)) continue;
    497         float Mgrid = getMgrid (m, i);
    498         if (isnan(Mgrid)) continue;
     483
     484        // Mmos, Mgrp have already been transfered to Mcal and should be zero here
     485        // float Mmos  = getMmos  (m, i);
     486        // if (isnan(Mmos)) continue;
     487        // float Mgrp  = getMgrp  (m, i, catalog[i].measureT[m].airmass, NULL);
     488        // if (isnan(Mgrp)) continue;
     489
     490        // Mgrid is applied to Mflat and should be ignored here
     491        // float Mgrid = getMgridTiny (&catalog[i].measureT[m]);
     492        // if (isnan(Mgrid)) continue;
    499493
    500494        // Note that this operation is setting measure->McalAPER to image->McalAPER only
     
    509503
    510504        // set the output calibration
    511         // float Moff = Mmos + Mgrp + Mgrid;
    512         float Moff = Mmos + Mgrid; // Mgrp has already been applied to the image.Mcal
    513         catalog[i].measure[m].McalPSF  = McalPSF + Moff;
    514         catalog[i].measure[m].McalAPER = useStackAper ? McalAPER + Moff : McalPSF + Moff;
     505        catalog[i].measure[m].McalPSF  = McalPSF;
     506        catalog[i].measure[m].McalAPER = useStackAper ? McalAPER : McalPSF;
    515507
    516508        if (catalog[i].measureT[m].dbFlags & ID_MEAS_PHOTOM_UBERCAL) {
     
    584576}
    585577
     578static float MinChiSqLim = NAN;
     579static float MaxChiSqLim = NAN;
     580static float MinScatterLim = NAN;
     581static float MaxScatterLim = NAN;
     582
    586583void clean_stars (Catalog *catalog, int Ncatalog) {
    587584
    588   int i, j, Ndel, Nave, Ntot, mark, Ns, Nscat, Nchi, Nnan;
    589   float dM;
    590   double MaxScatter, MaxChisq;
    591   double *xlist, *slist, *dlist;
     585  int Ndel, Nave, Ntot, Nscat, Nchi, Nnan;
     586  double *xlist, *slist;
     587
     588  if (isnan (MaxChiSqLim))   MaxChiSqLim   = STAR_CHISQ;
     589  if (isnan (MaxScatterLim)) MaxScatterLim = STAR_SCATTER;
    592590
    593591  StatType stats;
     
    597595
    598596  /* find Mchisq median -> ChiSq lim must be > median */
    599   for (i = Ntot = 0; i < Ncatalog; i++) {
     597  for (int i = Ntot = 0; i < Ncatalog; i++) {
    600598    Ntot += catalog[i].Naverage;
    601599  }
    602600  ALLOCATE (xlist, double, Ntot);
    603601  ALLOCATE (slist, double, Ntot);
    604   ALLOCATE (dlist, double, Ntot);
    605602
    606603  int Nsecfilt = GetPhotcodeNsecfilt ();
    607604
    608605  // eliminate bad stars using the stats for a single secfilt at a time
    609   for (Ns = 0; Ns < Nphotcodes; Ns ++) {
     606  for (int Ns = 0; Ns < Nphotcodes; Ns ++) {
    610607   
    611608    int thisCode = photcodes[Ns][0].code;
    612609    int Nsec = GetPhotcodeNsec(thisCode);
    613610
    614     for (i = Ntot = 0; i < Ncatalog; i++) {
    615       for (j = 0; j < catalog[i].Naverage; j++) {
    616         if ( catalog[i].secfilt[Nsecfilt*j+Nsec].flags & STAR_BAD ) continue;
     611    for (int i = Ntot = 0; i < Ncatalog; i++) {
     612      for (int j = 0; j < catalog[i].Naverage; j++) {
     613        if (catalog[i].secfilt[Nsecfilt*j+Nsec].flags & STAR_BAD) continue;
    617614        float Mchisq = catalog[i].secfilt[Nsecfilt*j+Nsec].Mchisq;
    618615        if (isnan(Mchisq)) continue;
    619616        xlist[Ntot] = Mchisq;
    620617        slist[Ntot] = catalog[i].secfilt[Nsecfilt*j+Nsec].dMpsfChp;
    621         dlist[Ntot] = 1;
    622618        Ntot ++;
    623619      }
    624620    }
    625  
    626     liststats (xlist, dlist, NULL, Ntot, &stats);
    627     MaxChisq = MAX (STAR_CHISQ, 2*stats.median);
    628 
    629     liststats (slist, dlist, NULL, Ntot, &stats);
    630     MaxScatter = MAX (STAR_SCATTER, 2*stats.median);
    631     fprintf (stderr, "Max Scatter: %f, Max Chisq: %f\n", MaxScatter, MaxChisq);
     621
     622    liststats (xlist, NULL, NULL, Ntot, &stats);
     623    float ChiSqUpper90 = stats.Upper90;
     624    if (isnan (MinChiSqLim)) MinChiSqLim = 2.0*stats.median;             // chi-square cut cannot fall below this value (even if this is > MaxChiSqLim)
     625    float ChiSqLimit = MAX(MinChiSqLim, MIN(MaxChiSqLim, ChiSqUpper90)); // chi-square cut should be between MinChiSqLim and MaxChiSqLim
     626
     627    liststats (slist, NULL, NULL, Ntot, &stats);
     628    float ScatterUpper90 = stats.Upper90;
     629    if (isnan (MinScatterLim)) MinScatterLim = 2.0*stats.median;         // scatter cut cannto fall below this value (even if this is > MaxScatterLim)
     630    float ScatterLimit = MAX(MinScatterLim, MIN(MaxScatterLim, ScatterUpper90));
     631
     632    fprintf (stderr, "STARS: ChiSqLimit: %f, ScatterLimit: %f | ChiSquare Upper 90: %f, Scatter Upper 90: %f\n", ChiSqLimit, ScatterLimit, ChiSqUpper90, ScatterUpper90);
    632633
    633634    Ndel = Nave = Nscat = Nnan = Nchi = 0;
    634     for (i = 0; i < Ncatalog; i++) {
    635       for (j = 0; j < catalog[i].Naverage; j++) {
    636         dM = catalog[i].secfilt[Nsecfilt*j+Nsec].dMpsfChp;
     635    for (int i = 0; i < Ncatalog; i++) {
     636      for (int j = 0; j < catalog[i].Naverage; j++) {
     637        float dM = catalog[i].secfilt[Nsecfilt*j+Nsec].dMpsfChp;
    637638        float Mchisq = catalog[i].secfilt[Nsecfilt*j+Nsec].Mchisq;
    638         mark = (dM > MaxScatter) || (isnan(Mchisq)) || (Mchisq > MaxChisq);
     639        int mark = (dM > ScatterLimit) || (isnan(Mchisq)) || (Mchisq > ChiSqLimit);
    639640        if (mark) {
    640           catalog[i].secfilt[Nsecfilt*j+Nsec].flags |= ID_OBJ_POOR;
     641          catalog[i].secfilt[Nsecfilt*j+Nsec].flags |= ID_SECF_STAR_POOR;
    641642          Ndel ++;
    642           if (dM > MaxScatter)   { Nscat ++; }
    643           if (isnan(Mchisq))     { Nnan ++; }
    644           if (Mchisq > MaxChisq) { Nchi ++; }
     643          if (dM > ScatterLimit)   { Nscat ++; }
     644          if (isnan(Mchisq))       { Nnan ++; }
     645          if (Mchisq > ChiSqLimit) { Nchi ++; }
    645646        } else {
    646           catalog[i].secfilt[Nsecfilt*j+Nsec].flags &= ~ID_OBJ_POOR;
     647          catalog[i].secfilt[Nsecfilt*j+Nsec].flags &= ~ID_SECF_STAR_POOR;
    647648        }
    648649        Nave ++;
    649650      }
    650651    }
    651     fprintf (stderr, "%d stars marked variable (%d scat, %d nan, %d chi), %d total\n", Ndel, Nscat, Nnan, Nchi, Nave);
     652    fprintf (stderr, "%d of %d stars marked variable (%d scat, %d nan, %d chi)\n", Ndel, Nave, Nscat, Nnan, Nchi);
    652653  }
    653654  free (xlist);
    654655  free (slist);
    655   free (dlist);
    656 }
    657 
    658 // clean_measures examines the stats for a single star.  It measures the INNER 50% mean
    659 // and sigma, it then re-measures the mean and sigma using all stars with NSIGMA_CLIP (3)
    660 // sigma of the INNER 50% mean.  it then flags any measurements which are more than
    661 // NSIGMA_REJECT (5) sigma of the mean
    662 
    663 // this function only operations on the PSF magnitudes
    664 
    665 // XXX EAM clean_measures is no longer used -- we rely on IRLS to down-weight outliers
    666 
    667 # define NSIGMA_CLIP 3.0
    668 # define NSIGMA_REJECT 5.0
    669 void clean_measures (Catalog *catalog, int Ncatalog, int final, FlatCorrectionTable *flatcorr) {
    670 
    671   off_t j, k, m, Nmax, Ndel, Nave;
    672   int i, N, image_bad, TOOFEW;
    673   off_t *ilist;
    674   double *tlist, *list, *dlist;
    675   float Msys, Mcal, Mmos, Mgrp, Mgrid;
    676   int Ncal, Nmos, Ngrp, Ngrid, Nfew;
    677 
    678   int Nsecfilt = GetPhotcodeNsecfilt ();
    679 
    680   if (VERBOSE) fprintf (stderr, "marking poor measures\n");
    681   /* Nmeasure is now different, need to reallocate */
    682   Nmax = 0;
    683   for (i = 0; i < Ncatalog; i++) {
    684     for (j = 0; j < catalog[i].Naverage; j++) {
    685       Nmax = MAX (Nmax, catalog[i].averageT[j].Nmeasure);
    686     }
    687   }
    688   ALLOCATE (list, double, MAX (1, Nmax));
    689   ALLOCATE (dlist, double, MAX (1, Nmax));
    690   ALLOCATE (ilist, off_t, Nmax);
    691   ALLOCATE (tlist, double, Nmax);
    692  
    693   /* it makes no sense to mark 3-sigma outliers with <5 measurements */
    694   TOOFEW = MAX (5, STAR_TOOFEW);
    695 
    696   // stats structures for inner and full stats
    697   StatType instats, stats;
    698   liststats_setmode (&instats, "INNER_MEAN");
    699   liststats_setmode (&stats, "MEAN");
    700 
    701   Ndel = Nave = 0;
    702   Ncal = Nmos = Ngrp = Ngrid = Nfew = 0;
    703   for (i = 0; i < Ncatalog; i++) {
    704     for (j = 0; j < catalog[i].Naverage; j++) {
    705 
    706       int Ns;
    707       for (Ns = 0; Ns < Nphotcodes; Ns++) {
    708        
    709         int thisCode = photcodes[Ns][0].code;
    710         int Nsec = GetPhotcodeNsec(thisCode);
    711        
    712         /* on final processing, skip stars already measured */
    713         if (final && catalog[i].found_t[Nsecfilt*j + Nsec]) continue; 
    714 
    715         /* skip bad stars to prevent them from becoming good (on inner sample) */
    716         if (catalog[i].secfilt[Nsecfilt*j+Nsec].flags & STAR_BAD) continue; 
    717 
    718         /* accumulate list of valid measurements */
    719         m = catalog[i].averageT[j].measureOffset;
    720         N = 0;
    721         for (k = 0; k < catalog[i].averageT[j].Nmeasure; k++, m++) {
    722           // skip measurements that do not match the current photcode
    723           int ecode = GetPhotcodeEquivCodebyCode (catalog[i].measureT[m].photcode);
    724           if (ecode != thisCode) { continue; }
    725 
    726           // SKIP gpc1 stack data
    727           if (isGPC1stack(catalog[i].measureT[m].photcode)) continue;
    728          
    729           // SKIP gpc1 forced-warp data
    730           if (isGPC1warp(catalog[i].measureT[m].photcode)) continue;
    731          
    732           // NOTE: we do not skip MEAS_BAD because this measurement is just an internal assessment of the outliers
    733           Mcal  = getMcal  (m, i, MAG_CLASS_PSF);
    734           if (isnan(Mcal)) { Ncal ++; continue; }
    735           Mmos  = getMmos  (m, i);
    736           if (isnan(Mmos)) { Nmos ++; continue; }
    737           Mgrp  = getMgrp  (m, i, catalog[i].measureT[m].airmass, NULL);
    738           if (isnan(Mgrp)) { Ngrp ++; continue; }
    739           Mgrid = getMgrid (m, i);
    740           if (isnan(Mgrid)) { Ngrid ++; continue; }
    741 
    742           Msys = PhotSysTiny (&catalog[i].measureT[m], &catalog[i].averageT[j], &catalog[i].secfilt[j*Nsecfilt], MAG_CLASS_PSF);
    743           list[N] = Msys - Mcal - Mmos - Mgrp - Mgrid;
    744           dlist[N] = MAX (catalog[i].measureT[m].dM, MIN_ERROR);
    745           N++;
    746         }
    747         if (N <= TOOFEW) {
    748           Nfew ++;
    749           continue;
    750         }
    751 
    752         /* 3-sigma clip based on stats of inner 50% */
    753 
    754         // calculated mean of inner 50%
    755         liststats (list, dlist, NULL, N, &instats);
    756         instats.sigma = MAX (MIN_ERROR, instats.sigma); /* if measurements agree too well, sigma -> 0.0 */
    757 
    758         // ignore entries > 3sigma from inner mean
    759         for (k = m = 0; k < N; k++) {
    760           if (fabs (list[k] - instats.median) < NSIGMA_CLIP*instats.sigma) {
    761             list[m] = list[k];
    762             m++;
    763           }
    764         }
    765         // recalculate the mean & sigma of the accepted measurements
    766         liststats (list, dlist, NULL, m, &stats);
    767         stats.sigma = MAX (MIN_ERROR, stats.sigma);
    768 
    769         /* apply to list of all relevant measurements, including IMAGE_POOR & IMAGE_FEW */
    770         image_bad = IMAGE_BAD;
    771         IMAGE_BAD = ID_IMAGE_PHOTOM_NOCAL;
    772         m = catalog[i].averageT[j].measureOffset;
    773         N = 0;
    774         for (k = 0; k < catalog[i].averageT[j].Nmeasure; k++, m++) {
    775           // skip measurements that do not match the current photcode
    776           int ecode = GetPhotcodeEquivCodebyCode (catalog[i].measureT[m].photcode);
    777           if (ecode != thisCode) { continue; }
    778 
    779           // SKIP gpc1 stack data
    780           if (isGPC1stack(catalog[i].measureT[m].photcode)) continue;
    781          
    782           // SKIP gpc1 forced-warp data
    783           if (isGPC1warp(catalog[i].measureT[m].photcode)) continue;
    784          
    785           // NOTE: we do not skip MEAS_BAD because this measurement is just an internal assessment of the outliers
    786           Mcal  = getMcal  (m, i, MAG_CLASS_PSF);
    787           if (isnan(Mcal)) continue;
    788           Mmos  = getMmos  (m, i);
    789           if (isnan(Mmos)) continue;
    790           Mgrid = getMgrid (m, i);
    791           if (isnan(Mgrid)) continue;
    792 
    793           Msys = PhotSysTiny (&catalog[i].measureT[m], &catalog[i].averageT[j], &catalog[i].secfilt[j*Nsecfilt], MAG_CLASS_PSF);
    794           list[N] = Msys - Mcal - Mmos - Mgrid;
    795           dlist[N] = MAX (catalog[i].measureT[m].dM, MIN_ERROR);
    796           ilist[N] = m;
    797           N++;
    798           Nave ++;
    799         }
    800         if (N < TOOFEW) continue;
    801 
    802         /* mark bad measures (> 5 sigma deviant) */
    803         for (k = 0; k < N; k++) {
    804           // treat the scatter of the star as a systematic term.  this is a bit of an
    805           // over-estimage (a perfect Gauss distribution with perfect errors would have
    806           // mySigma = sqrt(2) too large)
    807           float mySigma = hypot (stats.sigma, dlist[k]);
    808           if (fabs (list[k] - stats.median) > NSIGMA_REJECT*mySigma) {
    809             catalog[i].measureT[ilist[k]].dbFlags |= ID_MEAS_POOR_PHOTOM;
    810             if (final) {
    811               // for the final pass, we have a duplicate set of values in measure and measureT
    812               catalog[i].measure[ilist[k]].dbFlags |= ID_MEAS_POOR_PHOTOM;
    813             }
    814             Ndel ++;
    815           } else {
    816             catalog[i].measureT[ilist[k]].dbFlags &= ~ID_MEAS_POOR_PHOTOM;
    817             if (final) {
    818               // for the final pass, we have a duplicate set of values in measure and measureT
    819               catalog[i].measure[ilist[k]].dbFlags &= ~ID_MEAS_POOR_PHOTOM;
    820             }
    821           }
    822         }
    823         IMAGE_BAD = image_bad;
    824       }
    825     }
    826   }
    827   if (VERBOSE) fprintf (stderr, OFF_T_FMT" measures marked poor, "OFF_T_FMT" total\n", Ndel, Nave);
    828 
    829   free (list);
    830   free (dlist);
    831   free (ilist);
    832   free (tlist);
    833 }
    834 
    835 StatType statsStarN (Catalog *catalog, int Ncatalog, int Nsec, int seccode, FlatCorrectionTable *flatcorr) {
     656}
     657
     658StatType statsStarN (Catalog *catalog, int Ncatalog, int Nsec, int seccode) {
    836659
    837660  off_t j, k, m, Ntot;
     
    869692        Mmos = getMmos  (m, i);
    870693        if (isnan(Mmos)) { continue; }
    871         Mgrid = getMgrid (m, i);
     694        Mgrid = getMgridTiny (&catalog[i].measureT[m]);
    872695        if (isnan(Mgrid)) { continue;}
    873696        N++;
     
    1105928
    1106929      float MrelPSF  = getMrel  (catalog, m, c, MAG_CLASS_PSF, MAG_SRC_CHP); // average magnitude
    1107       // float Mgrid    = getMgrid (m, c);                    // camera offset (deprecated?)
    1108       // float Mflat    = getMflat (m, c, flatcorr, catalog); // flat-field correction
     930      // float Mgrid    = getMgridTiny (&catalog[c].measureT[m]);                    // camera offset (deprecated?)
     931      // float Mflat    = getMflat (m, c, catalog); // flat-field correction
    1109932
    1110933      off_t n = catalog[c].measureT[m].averef;
     
    1121944  fclose (fout);
    1122945}
     946
     947// maybe make this a macro
     948float getMflat (off_t meas, int cat, Catalog *catalog) {
     949  float offset = catalog[cat].measureT[meas].Mflat;
     950  if (!isfinite(offset)) {
     951    offset = 0.0;
     952  }
     953  return (offset);
     954}
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/TGroupOps.c

    r41562 r41649  
    22
    33void assignMosaicsToTGroups (void);
    4 int save_test_night_measures (FILE *fout, TGroup *myTGroup, Catalog *catalog, FlatCorrectionTable *flatcorr);
     4int save_test_night_measures (FILE *fout, TGroup *myTGroup, Catalog *catalog);
    55
    66// tgroupTimes carries the times of the tgroups (initially, just the photometric nights)
     
    647647  Catalog *catalog;
    648648  Image *image;
    649   FlatCorrectionTable *flatcorr;
    650649  SetMgrpInfo info;
    651650} ThreadInfo;
    652651
    653 int   setMgrp_tgroup (TGroup *tgroup, off_t Nmos, Image *image, Catalog *catalog, SetMgrpInfo *info, FlatCorrectionTable *flatcorr);
     652int   setMgrp_tgroup (TGroup *tgroup, off_t Nmos, Image *image, Catalog *catalog, SetMgrpInfo *info);
    654653void *setMgrp_worker (void *data);
    655 int   setMgrp_threaded (Catalog *catalog, FlatCorrectionTable *flatcorr);
     654int   setMgrp_threaded (Catalog *catalog);
    656655
    657656void SetMgrpInfoInit (SetMgrpInfo *info, off_t Nmax, int allocLists) {
     
    727726}
    728727
    729 int setMgrp (Catalog *catalog, FlatCorrectionTable *flatcorr) {
     728int setMgrp (Catalog *catalog) {
    730729
    731730  off_t N;
     
    738737  // so do not run setMgrp in threaded mode if PLOTSTUFF is set
    739738  if (NTHREADS && !PLOTSTUFF) {
    740     int status = setMgrp_threaded (catalog, flatcorr);
     739    int status = setMgrp_threaded (catalog);
    741740    return status;
    742741  }
     
    758757    TGroup *tgroup = tgroupTimes[i][0].byCode;
    759758    for (off_t j = 0; j < tgroupTimes[i][0].nCode; j++) {
    760       setMgrp_tgroup (&tgroup[j], i, image, catalog, &info, flatcorr);
     759      setMgrp_tgroup (&tgroup[j], i, image, catalog, &info);
    761760      // fprintf (stderr, "TGROUP time %.0f photcode %d Mcal: %f, dK: %f, dMcal: %f, sigma: %f, chisq: %f, %d of %d, limiting negative clouds to %f\n",
    762761      // ohana_sec_to_mjd(tgroupTimes[i][0].start), tgroup[j].photcode, tgroup[j].McalPSF, tgroup[j].dKlam, tgroup[j].dMcal, tgroup[j].stdev, tgroup[j].McalChiSq, tgroup[j].nFitPhotom, tgroup[j].nValPhotom, CLOUD_TOLERANCE);
     
    781780
    782781// 'tgroup' is a pointer to the current tgroup of interest (entry Ngrp)
    783 int setMgrp_tgroup (TGroup *myTGroup, off_t Ngrp, Image *image, Catalog *catalog, SetMgrpInfo *info, FlatCorrectionTable *flatcorr) {
     782int setMgrp_tgroup (TGroup *myTGroup, off_t Ngrp, Image *image, Catalog *catalog, SetMgrpInfo *info) {
    784783
    785784  off_t j;
     
    826825    fout = fopen (filename, "w");
    827826    fprintf (fout, "# tgroup %s (%.0f)\n", ohana_sec_to_date(tgroup->start), mjdStart);
    828     save_test_night_measures (fout, myTGroup, catalog, flatcorr);
     827    save_test_night_measures (fout, myTGroup, catalog);
    829828    fclose (fout);
    830829  }
     
    853852      continue;
    854853    }
    855     float Mgrid = getMgrid (m, c);
     854    float Mgrid = getMgridTiny (&catalog[c].measureT[m]);
    856855    if (isnan(Mgrid)) {
    857856      info->Ngrid ++;
     
    875874    // apply that offset as well here for this image (in other words, each detection is
    876875    // being compared to the model, excluding the zero point, Mcal.  The model includes
    877     // the flat-correction.  NOTE the sign of Mflat (Image.Mcal = Measure.Mcal - Mflat)
    878 
    879     float Mflat = getMflat (m, c, flatcorr, catalog);
     876    // the flat-correction.  NOTE the sign of Mflat (Image.Mcal = Measure.Mcal + Mflat)
     877    // this was inconsistent with PhotRel pre-r41606
     878
     879    float Mflat = getMflat (m, c, catalog);
    880880
    881881    off_t n = catalog[c].measureT[m].averef;
     
    900900    assert (Nbright >= 0);
    901901
    902     float Moff =  Mcal + Mmos + Mgrid - Mflat;
     902    float Moff =  Mcal + Mmos + Mgrid + Mflat;
    903903
    904904    psfStars->alldata-> yVector[N] = MsysPSF - MrelPSF - Moff;
     
    10001000}
    10011001 
    1002 int save_test_night_measures (FILE *fout, TGroup *myTGroup, Catalog *catalog, FlatCorrectionTable *flatcorr) {
     1002int save_test_night_measures (FILE *fout, TGroup *myTGroup, Catalog *catalog) {
    10031003
    10041004  int Nsecfilt = GetPhotcodeNsecfilt ();
     
    10131013    float Mmos     = getMmos  (m, c);                    // mosaic zero point
    10141014
    1015     float Mgrid    = getMgrid (m, c);                    // camera offset (deprecated?)
     1015    float Mgrid    = getMgridTiny (&catalog[c].measureT[m]);                    // camera offset (deprecated?)
    10161016    float MrelPSF  = getMrel  (catalog, m, c, MAG_CLASS_PSF, MAG_SRC_CHP); // average magnitude
    1017     float Mflat    = getMflat (m, c, flatcorr, catalog); // flat-field correction
     1017    float Mflat    = getMflat (m, c, catalog); // flat-field correction
    10181018
    10191019    off_t n = catalog[c].measureT[m].averef;
     
    10231023
    10241024    // for historical reasons, Mflat is defined with the wrong sign
    1025     float delta = MsysPSF - MrelPSF - Mcal - Mmos - Mgrid + Mflat - myTGroup->McalPSF;
     1025    float delta = MsysPSF - MrelPSF - Mcal - Mmos - Mgrid - Mflat - myTGroup->McalPSF;
    10261026
    10271027    int isBad = (catalog[c].measureT[m].dbFlags & MEAS_BAD);
     
    10371037}
    10381038
    1039 int setMgrp_threaded (Catalog *catalog, FlatCorrectionTable *flatcorr) {
     1039int setMgrp_threaded (Catalog *catalog) {
    10401040
    10411041  int i;
     
    10751075    threadinfo[i].catalog  =  catalog;
    10761076    threadinfo[i].image    =    image;
    1077     threadinfo[i].flatcorr = flatcorr;
    10781077
    10791078    // we do NOT allocate the arrays here, we only supply basic info used in the threads
     
    11241123  free (threadinfo);
    11251124
     1125  // XXX not allocated SetMgrpInfoFree (&summary);
     1126
    11261127  npass_output ++;
    11271128
     
    11451146
    11461147    Catalog *catalog = threadinfo->catalog;
    1147     FlatCorrectionTable *flatcorr = threadinfo->flatcorr;
    11481148    Image *image = threadinfo->image;
    11491149
    11501150    TGroup *tgroup = tgroupTimes[i][0].byCode;
    11511151    for (int j = 0; j < tgroupTimes[i][0].nCode; j++) {
    1152       setMgrp_tgroup (&tgroup[j], i, image, catalog, &results, flatcorr);
     1152      setMgrp_tgroup (&tgroup[j], i, image, catalog, &results);
    11531153      SetMgrpInfoAccum (&threadinfo->info, &results);
    11541154    }
     
    11721172  ALLOCATE (dlist, double, NtgroupTimes*Nphotcodes);
    11731173
    1174   int NIGHT_BAD = ID_IMAGE_NIGHT_POOR | ID_IMAGE_PHOTOM_FEW;
    1175 
    11761174  int n = 0;
    11771175  for (int i = 0; i < NtgroupTimes; i++) {
    11781176    TGroup *tgroup = tgroupTimes[i][0].byCode;
    11791177    for (int j = 0; j < tgroupTimes[i][0].nCode; j++) {
    1180       if (tgroup[j].flags & NIGHT_BAD) continue;
     1178      if (tgroup[j].flags & (ID_IMAGE_NIGHT_POOR | ID_IMAGE_PHOTOM_FEW)) continue;
    11811179      list[n] = tgroup[j].McalPSF;
    11821180      dlist[n] = 1;
     
    12091207    TGroup *tgroup = tgroupTimes[i][0].byCode;
    12101208    for (int j = 0; j < tgroupTimes[i][0].nCode; j++) {
    1211       if (tgroup[j].flags & IMAGE_BAD) continue;
     1209      if (tgroup[j].flags & (ID_IMAGE_NIGHT_POOR | ID_IMAGE_PHOTOM_FEW)) continue;
    12121210      list[n] = tgroup[j].dMcal;
    12131211      dlist[n] = 1;
     
    12401238    TGroup *tgroup = tgroupTimes[i][0].byCode;
    12411239    for (int j = 0; j < tgroupTimes[i][0].nCode; j++) {
    1242       if (tgroup[j].flags & IMAGE_BAD) continue;
     1240      if (tgroup[j].flags & (ID_IMAGE_NIGHT_POOR | ID_IMAGE_PHOTOM_FEW)) continue;
    12431241      list[n] = tgroup[j].McalChiSq;
    12441242      dlist[n] = 1;
     
    12671265 */
    12681266
    1269 static float MinMaxChiSq = NAN;
    1270 static float MinMaxScatter = NAN;
     1267static float MinChiSqLim = NAN;
     1268static float MaxChiSqLim = NAN;
     1269static float MinScatterLim = NAN;
     1270static float MaxScatterLim = NAN;
    12711271
    12721272void clean_tgroups () {
     
    12771277
    12781278  if (VERBOSE) fprintf (stderr, "marking poor tgroups\n");
     1279
     1280  if (isnan (MaxChiSqLim))   MaxChiSqLim   = NIGHT_CHISQ;
     1281  if (isnan (MaxScatterLim)) MaxScatterLim = NIGHT_SCATTER;
    12791282
    12801283  ALLOCATE (mlist, double, NtgroupTimes*Nphotcodes);
     
    13001303  liststats (mlist, NULL, NULL, N, &stats);
    13011304  float ChiSqUpper90 = stats.Upper90;
    1302   if (isnan (MinMaxChiSq)) MinMaxChiSq = 2.0*stats.median;
    1303   float MaxChiSq = MAX (MinMaxChiSq, ChiSqUpper90);
     1305  if (isnan (MinChiSqLim)) MinChiSqLim = 2.0*stats.median;             // chi-square cut cannot fall below this value (even if this is > MaxChiSqLim)
     1306  float ChiSqLimit = MAX(MinChiSqLim, MIN(MaxChiSqLim, ChiSqUpper90)); // chi-square cut should be between MinChiSqLim and MaxChiSqLim
    13041307
    13051308  liststats (slist, NULL, NULL, N, &stats);
    13061309  float ScatterUpper90 = stats.Upper90;
    1307   if (isnan (MinMaxScatter)) MinMaxScatter = 2.0*stats.median;
    1308   float MaxScatter = MAX (MinMaxScatter, ScatterUpper90);
    1309 
    1310   fprintf (stderr, "TGROUPS: Max ChiSq: %f, Max Scatter: %f | ChiSquare Upper 90: %f, Scatter Upper 90: %f\n", MaxChiSq, MaxScatter, ChiSqUpper90, ScatterUpper90);
     1310  if (isnan (MinScatterLim)) MinScatterLim = 2.0*stats.median;         // scatter cut cannto fall below this value (even if this is > MaxScatterLim)
     1311  float ScatterLimit = MAX(MinScatterLim, MIN(MaxScatterLim, ScatterUpper90));
     1312
     1313  fprintf (stderr, "TGROUPS: ChiSqLimit: %f, ScatterLimit: %f | ChiSquare Upper 90: %f, Scatter Upper 90: %f\n", ChiSqLimit, ScatterLimit, ChiSqUpper90, ScatterUpper90);
    13111314 
    13121315  int Ntotal = 0, Npoor = 0, Nmark = 0, Nscatter = 0, Nchisq = 0, NfewNights = 0, NfewExp = 0;
     
    13371340      }
    13381341      // scatter too large
    1339       if (tgroup[j].stdev > MaxScatter) {
     1342      if (tgroup[j].stdev > ScatterLimit) {
    13401343        mark = TRUE;
    13411344        Nscatter ++;
    13421345      }
    13431346      // chisq too large
    1344       if (tgroup[j].McalChiSq > MaxChiSq) {
     1347      if (tgroup[j].McalChiSq > ChiSqLimit) {
    13451348        mark = TRUE;
    13461349        Nchisq ++;
     
    13941397        c = tgroup[i].catalog[j];
    13951398     
    1396         if (catalog[c].measureT[m].dbFlags & (ID_MEAS_AREA | ID_MEAS_NOCAL)) continue;
     1399        if (catalog[c].measureT[m].dbFlags & MEAS_BAD) continue;
    13971400
    13981401        // ave = catalog[c].measureT[m].averef;
     
    15011504
    15021505        float MrelPSF  = getMrel  (catalog, m, c, MAG_CLASS_PSF, MAG_SRC_CHP); // average magnitude
    1503         // float Mgrid    = getMgrid (m, c);                    // camera offset (deprecated?)
    1504         // float Mflat    = getMflat (m, c, flatcorr, catalog); // flat-field correction
     1506        // float Mgrid    = getMgridTiny (&catalog[c].measureT[m]); // camera offset (deprecated?)
     1507        float Mflat    = getMflat (m, c, catalog); // flat-field correction
    15051508
    15061509        off_t n = catalog[c].measureT[m].averef;
     
    15101513
    15111514        // for historical reasons, Mflat is defined with the wrong sign
    1512         float delta = MsysPSF - MrelPSF - Mcal - Mmos - Mgrp;
     1515        float delta = MsysPSF - MrelPSF - Mcal - Mmos - Mgrp - Mflat;
    15131516
    15141517        fprintf (fout, "%f %f : %f %f : %f %f %f  : %f %f\n", catalog[c].averageT[n].R, catalog[c].averageT[n].D, MsysPSF, MrelPSF, Mcal, Mmos, Mgrp, catalog[c].measureT[m].airmass, delta);
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/ZeroPointModes.c

    r41555 r41649  
    88    int newValue;
    99    fprintf (stdout, "Set Iteration (current = %d): ", CurrentLoop);
    10     fscanf (stdin, "%d", &newValue);
     10    if (!fscanf (stdin, "%d", &newValue)) return;
    1111    fprintf (stdout, "Using iteration %d\n", newValue);
    1212    CurrentLoop = newValue;
     
    2222}
    2323
    24 void SetZeroPointModes (void) {
     24void SetZeroPointModes (Catalog *catalog, int Ncatalog) {
    2525
    2626  if (TGROUP_ZEROPT && MOSAIC_ZEROPT) {
     
    4949      clean_mosaics(); // do this on every pass
    5050    }
    51     if ((CurrentLoop >= 18) && (CurrentLoop <= 999)) {
     51    if ((CurrentLoop >= 18) && (CurrentLoop < 21)) {
    5252      // after iterating a few times on the TGroup & Mosaic zero points:
    5353      // * identify the good / bad Mosaics
     
    5959      clean_mosaics(); // do this on every pass
    6060      clean_images(); // do this on every pass
     61      clean_stars(catalog, Ncatalog); // do this on every pass
     62    }
     63    if ((CurrentLoop >= 21) && (CurrentLoop <= 999)) {
     64      // after iterating a few times on the TGroup & Mosaic zero points:
     65      // * identify the good / bad Mosaics
     66      // * fit the chips from the bad Mosaics
     67      TGROUP_ZPT_MODE = TGROUP_ZPT_MODE_GOOD_NIGHT; // stop fitting the bad nights
     68      MOSAIC_ZPT_MODE = MOSAIC_ZPT_MODE_BAD_NIGHT_GOOD_MOSAIC; // only fit good mosaics on bad nights
     69      IMAGE_ZPT_MODE  = IMAGE_ZPT_MODE_BAD_NIGHT_BAD_MOSAIC; // only fit bad mosaics on bad nights
     70      GRID_ZPT_MODE  = GRID_ZPT_MODE_ALL; // only fit bad mosaics on bad nights
     71      clean_tgroups(); // do this on every pass
     72      clean_mosaics(); // do this on every pass
     73      clean_images(); // do this on every pass
     74      clean_stars(catalog, Ncatalog); // do this on every pass
    6175    }
    6276  }
     
    6882      MOSAIC_ZPT_MODE = MOSAIC_ZPT_MODE_NONE;
    6983    }
    70     if ((CurrentLoop > 4) && (CurrentLoop <= 999)) {
     84    if ((CurrentLoop > 4) && (CurrentLoop <= 8)) {
    7185      // after iterating a few times on the TGroup zero points:
    7286      // * identify the photometric nights
     
    7791      clean_tgroups(); // do this on every pass or just sometimes?
    7892    }
     93    if ((CurrentLoop > 8) && (CurrentLoop <= 999)) {
     94      // after iterating a few times on the TGroup zero points:
     95      // * identify the photometric nights
     96      // * fit the images from the non-photometric nights
     97      TGROUP_ZPT_MODE = TGROUP_ZPT_MODE_GOOD_NIGHT; // stop fitting the bad nights
     98      MOSAIC_ZPT_MODE = MOSAIC_ZPT_MODE_NONE;
     99      IMAGE_ZPT_MODE  = IMAGE_ZPT_MODE_BAD_NIGHT;
     100      GRID_ZPT_MODE  = GRID_ZPT_MODE_ALL; // only fit bad mosaics on bad nights
     101      clean_tgroups(); // do this on every pass or just sometimes?
     102    }
    79103  }
    80104
    81105  if (!TGROUP_ZEROPT && MOSAIC_ZEROPT) {
    82     if (CurrentLoop <= 4) {
     106    if (CurrentLoop < 6) {
    83107      TGROUP_ZPT_MODE = TGROUP_ZPT_MODE_NONE;
    84108      MOSAIC_ZPT_MODE = MOSAIC_ZPT_MODE_ALL;
    85109      IMAGE_ZPT_MODE  = IMAGE_ZPT_MODE_NONE;
    86110    }
    87     if ((CurrentLoop > 4) && (CurrentLoop <= 999)) {
     111    if ((CurrentLoop >= 6) && (CurrentLoop < 12)) {
    88112      // after iterating a few times on the Mosaic zero points:
    89113      // * identify the good / bad mosaics
     
    94118      clean_mosaics(); // do this on every pass or just sometimes?
    95119    }
     120    if ((CurrentLoop >= 12) && (CurrentLoop < 18)) {
     121      // after iterating a few times on the Mosaic zero points:
     122      // * identify the good / bad mosaics
     123      // * fit the images from the bad mosaics
     124      TGROUP_ZPT_MODE = TGROUP_ZPT_MODE_NONE; // stop fitting the bad nights
     125      MOSAIC_ZPT_MODE = MOSAIC_ZPT_MODE_GOOD_MOSAIC;
     126      IMAGE_ZPT_MODE  = IMAGE_ZPT_MODE_BAD_MOSAIC;
     127      clean_mosaics(); // do this on every pass or just sometimes?
     128      clean_images(); // do this on every pass
     129      clean_stars(catalog, Ncatalog); // do this on every pass
     130    }
     131    if ((CurrentLoop >= 18) && (CurrentLoop < 999)) {
     132      // after iterating a few times on the Mosaic zero points:
     133      // * identify the good / bad mosaics
     134      // * fit the images from the bad mosaics
     135      TGROUP_ZPT_MODE = TGROUP_ZPT_MODE_NONE; // stop fitting the bad nights
     136      MOSAIC_ZPT_MODE = MOSAIC_ZPT_MODE_GOOD_MOSAIC;
     137      IMAGE_ZPT_MODE  = IMAGE_ZPT_MODE_BAD_MOSAIC;
     138      GRID_ZPT_MODE  = GRID_ZPT_MODE_ALL; // only fit bad mosaics on bad nights
     139      clean_mosaics(); // do this on every pass or just sometimes?
     140      clean_images(); // do this on every pass
     141      clean_stars(catalog, Ncatalog); // do this on every pass
     142    }
    96143  }
    97144
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/args.c

    r41562 r41649  
    198198  }
    199199
    200   NGRID = 8;
    201   if ((N = get_argument (argc, argv, "-ngrid"))) {
    202     remove_argument (N, &argc, argv);
    203     NGRID = atof (argv[N]);
    204     remove_argument (N, &argc, argv);
    205   }
    206 
    207200  TEST_IMAGE1 = -1;
    208201  if ((N = get_argument (argc, argv, "-test-image1"))) {
     
    227220    RESET = TRUE;
    228221  }
    229 
    230222  RESET_ZEROPTS = FALSE;
    231223  if ((N = get_argument (argc, argv, "-reset-zpts"))) {
     
    233225    RESET_ZEROPTS = TRUE;
    234226  }
     227  RESET_FLATCORR = FALSE;
     228  if ((N = get_argument (argc, argv, "-reset-flat"))) {
     229    remove_argument (N, &argc, argv);
     230    RESET_FLATCORR = TRUE;
     231  }
    235232
    236233  REPAIR_WARPS = FALSE;
     
    244241    remove_argument (N, &argc, argv);
    245242    PRESERVE_PS1 = TRUE;
     243  }
     244  REQUIRE_PSFFIT = FALSE;
     245  if ((N = get_argument (argc, argv, "-require-psffit"))) {
     246    remove_argument (N, &argc, argv);
     247    REQUIRE_PSFFIT = TRUE;
    246248  }
    247249
     
    387389  }
    388390
    389   // USE_GRID is not valid for all cases, probably should be its own mode...
    390   USE_GRID = FALSE;
     391  // GRID_ZEROPT is not valid for all cases, probably should be its own mode...
     392  GRID_ZEROPT = FALSE;
     393  GRID_MEANFILE = NULL; // this is set by GridCorrectionSave()
     394  GRID_ZPT_MODE = GRID_ZPT_MODE_NONE; // start with grid off
    391395  if ((N = get_argument (argc, argv, "-grid"))) {
    392396    remove_argument (N, &argc, argv);
    393     USE_GRID = TRUE;
     397    GRID_ZEROPT = TRUE;
     398  }
     399  if ((N = get_argument (argc, argv, "-grid-meanfile"))) {
     400    GRID_ZEROPT = TRUE;
     401    remove_argument (N, &argc, argv);
     402    GRID_MEANFILE = strcreate (argv[N]); // used by relphot -averages and relphot -apply-offsets
     403    remove_argument (N, &argc, argv);
     404    GRID_ZPT_MODE  = GRID_ZPT_MODE_ALL; // since we are applying the grid, need to active this
     405  }
     406
     407  GRID_BIN_GPC1 = 16;
     408  if ((N = get_argument (argc, argv, "-grid-bin-gpc1"))) {
     409    remove_argument (N, &argc, argv);
     410    GRID_BIN_GPC1 = atof (argv[N]);
     411    remove_argument (N, &argc, argv);
     412  }
     413  GRID_BIN_GPC2 = 16;
     414  if ((N = get_argument (argc, argv, "-grid-bin-gpc2"))) {
     415    remove_argument (N, &argc, argv);
     416    GRID_BIN_GPC2 = atof (argv[N]);
     417    remove_argument (N, &argc, argv);
     418  }
     419  GRID_BIN_HSC = 8;
     420  if ((N = get_argument (argc, argv, "-grid-bin-hsc"))) {
     421    remove_argument (N, &argc, argv);
     422    GRID_BIN_HSC = atof (argv[N]);
     423    remove_argument (N, &argc, argv);
     424  }
     425  GRID_BIN_CFH = 8;
     426  if ((N = get_argument (argc, argv, "-grid-bin-cfh"))) {
     427    remove_argument (N, &argc, argv);
     428    GRID_BIN_CFH = atof (argv[N]);
     429    remove_argument (N, &argc, argv);
    394430  }
    395431
     
    555591    case SYNTH_PHOT:
    556592    case UPDATE_AVERAGES:
     593      // note: initialize sets PhotcodeList to the full set of average photcodes
     594      // if the mode is UPDATE_AVERAGES
    557595      if (argc != 1) relphot_usage();
    558596      break;
     
    608646  FREE (REGION_FILE);
    609647  FREE (SYNTH_ZERO_POINTS);
     648  FREE (GRID_MEANFILE);
    610649  FREE (IMAGE_TABLE);
    611650  FREE (CATDIR);
     
    763802    RESET = TRUE;
    764803  }
    765 
    766804  RESET_ZEROPTS = FALSE;
    767805  if ((N = get_argument (argc, argv, "-reset-zpts"))) {
    768806    remove_argument (N, &argc, argv);
    769807    RESET_ZEROPTS = TRUE;
     808  }
     809  RESET_FLATCORR = FALSE;
     810  if ((N = get_argument (argc, argv, "-reset-flat"))) {
     811    remove_argument (N, &argc, argv);
     812    RESET_FLATCORR = TRUE;
    770813  }
    771814
     
    864907  }
    865908
     909  // load the GridCorrection file
     910  GRID_ZEROPT = FALSE;
     911  GRID_MEANFILE = NULL;
     912  if ((N = get_argument (argc, argv, "-grid"))) {
     913    GRID_ZEROPT = TRUE;
     914    remove_argument (N, &argc, argv);
     915    GRID_MEANFILE = strcreate (argv[N]);
     916    remove_argument (N, &argc, argv);
     917    GRID_ZPT_MODE  = GRID_ZPT_MODE_ALL; // since we are applying the grid, need to active this
     918  }
     919
    866920  ImagSelect = FALSE;
    867921  if ((N = get_argument (argc, argv, "-instmag"))) {
     
    922976
    923977  FREE (SYNTH_ZERO_POINTS);
     978  FREE (GRID_MEANFILE);
    924979  FREE (BOUNDARY_TREE);
    925980  FREE (UPDATE_CATFORMAT);
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/assign_images.c

    r41485 r41649  
    3636  if (MOSAIC_ZEROPT) {
    3737    makeMosaics (image, Nimage, FALSE);
    38 
    39     // center coords and Mcal, dMcal, Mchisq for the mosaics
     38    MARKTIME("set mosaic coordinates and Mcal values: %f sec\n", dtime);
     39
     40    // center coords and zero Mcal, dMcal, Mchisq for the mosaics
    4041    setMosaicCenters (image, Nimage);
    4142    MARKTIME("set mosaic coordinates and Mcal values: %f sec\n", dtime);
     
    124125      Mosaic *mosaic = getMosaicForImage (j);
    125126      if (mosaic) {
    126         Rc = mosaic->coords.crval1;
    127         Dc = mosaic->coords.crval2;
    128         // NOTE : have defined mosaic Rc,Dc to choose the side of 0,360 on which most of the
    129         // chips are located.  but, for host assignment, we rationalize to 0.0 - 360.0
    130         Rc = ohana_normalize_angle_to_midpoint (Rc, 180.0);
     127        Rc = mosaic->coords.crval1;
     128        Dc = mosaic->coords.crval2;
     129        // NOTE : have defined mosaic Rc,Dc to choose the side of 0,360 on which most of the
     130        // chips are located.  but, for host assignment, we rationalize to 0.0 - 360.0
     131        Rc = ohana_normalize_angle_to_midpoint (Rc, 180.0);
    131132      }
    132133    }
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/bcatalog.c

    r41561 r41649  
    3535  ALLOCATE (Nvalid, int, Nsecfilt);
    3636
    37   // flags used by the photometry analysis (excluding UBERCAL)
    38   unsigned int PHOTOM_FLAGS =
    39     ID_MEAS_NOCAL          | // detection ignored for this analysis (photcode, time range)
    40     ID_MEAS_POOR_PHOTOM    | // detection is photometry outlier
    41     ID_MEAS_SKIP_PHOTOM    | // detection was ignored for photometry measurement
    42     ID_MEAS_AREA           | // detetion was outside acceptable area of device
    43     ID_MEAS_SYNTH_MAG      | // magnitude is synthetic
    44     ID_MEAS_STACK_PRIMARY  | // this stack measurement is in the primary skycell
    45     ID_MEAS_STACK_PHOT_SRC | // this measurement supplied the stack photometry
    46     ID_MEAS_PHOTOM_PSF     | // this measurement is used for the mean psf mag
    47     ID_MEAS_PHOTOM_APER    | // this measurement is used for the mean ap mag
    48     ID_MEAS_PHOTOM_KRON    ; // this measurement is used for the mean kron mag
    49    
    5037  /* exclude stars not in range or with too few measurements */
    5138  for (i = 0; i < catalog[0].Naverage; i++) {
     
    6148    }
    6249
    63     // reset the calculated average magnitudes (does not affect ubercal-tied measurements or images)
    64     if (RESET) {
    65       int Ns;
    66 
    67       for (Ns = 0; Ns < Nphotcodes; Ns++) {
    68 
    69         int thisCode = photcodes[Ns][0].code;
    70         int Nsec = GetPhotcodeNsec(thisCode);
    71 
    72         dvo_secfilt_init (&subcatalog[0].secfilt[Nsecfilt*Naverage+Nsec], SECFILT_RESET_ALL);
    73       }
    74     }
     50    // reset the calculated average magnitudes for active photcode only
     51    ResetAverageActivePhotcodes (&subcatalog[0].secfilt[Nsecfilt*Naverage]);
    7552
    7653    Nm = 0;
     
    11188      if (isnan(catalog[0].measure[offset].Mkron)) { Nnan ++; continue; }
    11289
    113       // require 0x01 in photFlags (fitted with a PSF)
    114       if ((catalog[0].measure[offset].photFlags & 0x01) == 0) { Nbad ++; continue; }
     90      // require 0x01 in photFlags (fitted with a PSF) -- add to the test data
     91      if (REQUIRE_PSFFIT && (catalog[0].measure[offset].photFlags & 0x01) == 0) { Nbad ++; continue; }
    11592
    11693      // very loose cut on PSF - Kron
     
    156133      subcatalog[0].measureT[Nmeasure].dbFlags &= ~ID_MEAS_SKIP_PHOTOM;
    157134      subcatalog[0].measureT[Nmeasure].averef = Naverage;
    158       if (RESET) {
    159         // only reset Mcal for measures with a matching image
    160         // do not reset Mcal for ubercal images unless explicitly requested
    161         if (subcatalog[0].measureT[Nmeasure].dbFlags & ID_MEAS_PHOTOM_UBERCAL) {
    162           if (!KEEP_UBERCAL) {
    163             subcatalog[0].measureT[Nmeasure].McalPSF  = 0.0;
    164             subcatalog[0].measureT[Nmeasure].McalAPER = 0.0;
    165             subcatalog[0].measureT[Nmeasure].dbFlags &= ~ID_MEAS_PHOTOM_UBERCAL;
    166           }
    167         } else {
    168           if (getImageEntry (Nmeasure, Ncat) >= 0) {
    169             subcatalog[0].measureT[Nmeasure].McalPSF  = 0.0;
    170             subcatalog[0].measureT[Nmeasure].McalAPER = 0.0;
    171           }
    172         }
    173         subcatalog[0].measureT[Nmeasure].dbFlags &= ~PHOTOM_FLAGS;
    174       }
     135      ResetMeasureZeroPoints (&subcatalog[0].measureT[Nmeasure], Nmeasure, Ncat);
     136
    175137      Nmeasure ++;
    176138      Nm ++;
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/extra.c

    r41467 r41649  
    11# include "relphot.h"
     2# define DISABLE_CORNER_GPC1 0
    23
    34int isMosaicChip (int photcode) {
     
    1415int whichGPC1filter (int photcode) {
    1516
    16 # if (1)
     17# if (DISABLE_CORNER_GPC1)
    1718  // disable the corner chips:
    1819  if (((photcode >  10000) && (photcode <  10077)) || (photcode == 4100)) return PS1_g; // g-band
     
    3738int isGPC1chip (int photcode) {
    3839
    39 # if (1)
     40# if (DISABLE_CORNER_GPC1)
    4041  if (((photcode >  10000) && (photcode <  10077)) || (photcode == 4100)) return TRUE; // g-band
    4142  if (((photcode >  10100) && (photcode <  10177)) || (photcode == 4200)) return TRUE; // r-band
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/global_stats.c

    r41462 r41649  
    11# include "relphot.h"
    22
    3 void global_stats (Catalog *catalog, int Ncatalog, FlatCorrectionTable *flatcorr, int nloop) {
     3void global_stats (Catalog *catalog, int Ncatalog, int nloop) {
    44
    55  StatType stN, stX, stS, imN, imX, imM, imD, msM, msX, msN, msD, tgM, tgX, tgD;
     
    3333    int seccode = photcodes[Ns][0].code;
    3434
    35     stN = statsStarN (catalog, Ncatalog, Nsec, seccode, flatcorr);
     35    stN = statsStarN (catalog, Ncatalog, Nsec, seccode);
    3636    stX = statsStarX (catalog, Ncatalog, Nsec);
    3737    stS = statsStarS (catalog, Ncatalog, Nsec);
     
    4343  }
    4444 
    45   imN = statsImageN (catalog, flatcorr);
     45  imN = statsImageN (catalog);
    4646  imX = statsImageX (catalog);
    4747  imM = statsImageM (catalog);
    4848  imD = statsImagedM (catalog);
    4949 
    50   msN = statsMosaicN (catalog, flatcorr);
     50  msN = statsMosaicN (catalog);
    5151  msM = statsMosaicM (catalog);
    5252  msD = statsMosaicdM (catalog);
     
    5858 
    5959  fprintf (stderr, "meas / image:   %7.0f  %7.0f  %7.0f  %7.0f  %7.0f  %6d\n",   imN.median, imN.mean, imN.sigma, imN.min, imN.max, imN.Nmeas);
    60   fprintf (stderr, "Mcal image:     %7.4f  %7.4f  %7.4f  %7.4f  %7.4f  %6d\n",   imM.median, imM.mean, imM.sigma, imM.min, imM.max, imM.Nmeas);
     60  fprintf (stderr, "Mcal  image:    %7.4f  %7.4f  %7.4f  %7.4f  %7.4f  %6d\n",   imM.median, imM.mean, imM.sigma, imM.min, imM.max, imM.Nmeas);
    6161  fprintf (stderr, "dMcal image:    %7.4f  %7.4f  %7.4f  %7.4f  %7.4f  %6d\n",   imD.median, imD.mean, imD.sigma, imD.min, imD.max, imD.Nmeas);
    6262  fprintf (stderr, "chisq image:    %7.1f  %7.1f  %7.1f  %7.1f  %7.1f  %6d\n",   imX.median, imX.mean, imX.sigma, imX.min, imX.max, imX.Nmeas);
    6363
    6464  fprintf (stderr, "meas / mosaic:  %7.0f  %7.0f  %7.0f  %7.0f  %7.0f  %6d\n",   msN.median, msN.mean, msN.sigma, msN.min, msN.max, msN.Nmeas);
    65   fprintf (stderr, "Mcal mosaic:    %7.4f  %7.4f  %7.4f  %7.4f  %7.4f  %6d\n",   msM.median, msM.mean, msM.sigma, msM.min, msM.max, msM.Nmeas);
     65  fprintf (stderr, "Mcal  mosaic:   %7.4f  %7.4f  %7.4f  %7.4f  %7.4f  %6d\n",   msM.median, msM.mean, msM.sigma, msM.min, msM.max, msM.Nmeas);
    6666  fprintf (stderr, "dMcal mosaic:   %7.4f  %7.4f  %7.4f  %7.4f  %7.4f  %6d\n",   msD.median, msD.mean, msD.sigma, msD.min, msD.max, msD.Nmeas);
    6767  fprintf (stderr, "chisq mosaic:   %7.1f  %7.1f  %7.1f  %7.1f  %7.1f  %6d\n",   msX.median, msX.mean, msX.sigma, msX.min, msX.max, msX.Nmeas);
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/initialize.c

    r41453 r41649  
    2727  }   
    2828   
    29   if (USE_GRID && (Nphotcodes > 1)) {
    30     fprintf (stderr, "grid correction analysis currently can only operate on a single photcode\n");
    31     exit (1);
    32   }
    33 
    34   IMAGE_BAD = ID_IMAGE_PHOTOM_POOR | ID_IMAGE_PHOTOM_FEW | ID_IMAGE_PHOTOM_SKIP;
    35   STAR_BAD  = ID_OBJ_POOR | ID_OBJ_FEW;
    36   MEAS_BAD  = ID_MEAS_NOCAL | ID_MEAS_POOR_PHOTOM | ID_MEAS_SKIP_PHOTOM | ID_MEAS_AREA;
    37 
    3829  if (SHOW_PARAMS) {
    3930    int Ns;
     
    6758
    6859    fprintf (stderr, "VERBOSE: %d, PLOTSTUFF: %d\n", VERBOSE, PLOTSTUFF);
    69     fprintf (stderr, "GRID_X: %d, GRID_Y: %d, BINNING: %d == Nmx: %d, Nmy: %d\n",
    70              RELPHOT_GRID_X,
    71              RELPHOT_GRID_Y,
    72              RELPHOT_GRID_BINNING,
    73              (int)(RELPHOT_GRID_X/RELPHOT_GRID_BINNING), (int)(RELPHOT_GRID_Y/RELPHOT_GRID_BINNING));
    7460
    7561    fprintf (stderr, "STAR_SCATTER           %lf\n", STAR_SCATTER);
     62    fprintf (stderr, "STAR_CHISQ             %lf\n", STAR_CHISQ);
     63
     64    fprintf (stderr, "MOSAIC_SCATTER         %lf\n", MOSAIC_SCATTER);
     65    fprintf (stderr, "MOSAIC_CHISQ           %lf\n", MOSAIC_CHISQ);
     66
     67    fprintf (stderr, "NIGHT_SCATTER          %lf\n", NIGHT_SCATTER);
     68    fprintf (stderr, "NIGHT_CHISQ            %lf\n", NIGHT_CHISQ);
     69
    7670    fprintf (stderr, "IMAGE_SCATTER          %lf\n", IMAGE_SCATTER);
    7771    fprintf (stderr, "IMAGE_OFFSET           %lf\n", IMAGE_OFFSET);
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/launch_region_hosts.c

    r40291 r41649  
    6262    if (RESET)                      strextend (&command, "-reset");
    6363    if (RESET_ZEROPTS)              strextend (&command, "-reset-zpts");
     64    if (RESET_FLATCORR)             strextend (&command, "-reset-flat");
    6465    if (!KEEP_UBERCAL)              strextend (&command, "-reset-ubercal");
    6566    if (DophotSelect)               strextend (&command, "-dophot %d", DophotValue);
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/load_catalogs.c

    r40549 r41649  
    165165    if (RESET)               { strextend (&command, "-reset"); }
    166166    if (RESET_ZEROPTS)       { strextend (&command, "-reset-zpts"); }
     167    if (RESET_FLATCORR)      { strextend (&command, "-reset-flat"); }
    167168    if (!KEEP_UBERCAL)       { strextend (&command, "-reset-ubercal"); }
    168169    if (DophotSelect)        { strextend (&command, "-dophot %d", DophotValue); }
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/load_images.c

    r41555 r41649  
    5757  // reset image values as needed.  always allow 'few' images to succeed, if possible (new
    5858  // images / detections may have been added
    59   for (off_t i = 0; i < Nsubset; i++) {
    60     // reset these two regardless (we will re-determine)
    61     subset[i].flags &= ~(ID_IMAGE_PHOTOM_NOCAL | ID_IMAGE_PHOTOM_POOR | ID_IMAGE_PHOTOM_SKIP | ID_IMAGE_PHOTOM_FEW);
    62     if (RESET) {
    63       if (RESET_ZEROPTS) {
    64         if (!KEEP_UBERCAL || !(subset[i].flags & ID_IMAGE_PHOTOM_UBERCAL)) {
    65           subset[i].McalPSF  = 0.0;
    66           subset[i].McalAPER = 0.0;
    67           subset[i].dMcal    = NAN;
    68           subset[i].flags   &= ~ID_IMAGE_PHOTOM_UBERCAL;
    69         }
    70       }
    71       subset[i].flags &= ~(ID_IMAGE_MOSAIC_POOR | ID_IMAGE_NIGHT_POOR);
    72       subset[i].flags &= ~(ID_IMAGE_IMAGE_PHOTCAL | ID_IMAGE_MOSAIC_PHOTCAL | ID_IMAGE_TGROUP_PHOTCAL);
    73       subset[i].ubercalDist = 1000;
    74     }
    75   }
     59  ResetImages (subset, Nsubset);
    7660
    7761  // XXX consider allowing relphot to skip the AstroMap load (do we need precise astrometry here?)
     
    11599  return TRUE;
    116100}
     101
     102// This function re-creates the image subset array using the array of LineNumbers saved
     103// initially by load_images.  This function is only called by relphot_images.c after the
     104// loops have been completed (if any).  I am not certain this function is doing anything
     105// at all : the values in the image subset are copied back to the master table in
     106// save_images_updates() so the values copied from the master to the subset should already
     107// be there.
    117108
    118109int reload_images (FITS_DB *db) {
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/plot_scatter.c

    r40291 r41649  
    11# include "relphot.h"
    22   
    3 void plot_scatter (Catalog *catalog, int Ncatalog, FlatCorrectionTable *flatcorr) {
     3void plot_scatter (Catalog *catalog, int Ncatalog) {
    44
    55  off_t i, j, k, m, N, Ntot;
     
    2828    N = 0;
    2929    for (i = 0; i < Ncatalog; i++) {
    30         for (j = 0; j < catalog[i].Naverage; j++) {
     30      for (j = 0; j < catalog[i].Naverage; j++) {
    3131
    32             /* calculate the average value for a single star */
    33             if (catalog[i].secfilt[Nsecfilt*j+Nsec].flags & STAR_BAD) continue; 
    34             m = catalog[i].averageT[j].measureOffset;
     32        /* calculate the average value for a single star */
     33        // if (catalog[i].secfilt[Nsecfilt*j+Nsec].flags & STAR_BAD) continue; 
     34        m = catalog[i].averageT[j].measureOffset;
    3535
    36             for (k = 0; k < catalog[i].averageT[j].Nmeasure; k++, m++) {
    37                 // skip measurements that do not match the current photcode
    38                 int ecode = GetPhotcodeEquivCodebyCode (catalog[i].measureT[m].photcode);
    39                 if (ecode != thisCode) { continue; }
     36        for (k = 0; k < catalog[i].averageT[j].Nmeasure; k++, m++) {
     37          // skip measurements that do not match the current photcode
     38          int ecode = GetPhotcodeEquivCodebyCode (catalog[i].measureT[m].photcode);
     39          if (ecode != thisCode) { continue; }
    4040
    41                 if (catalog[i].measureT[m].dbFlags & MEAS_BAD) continue;
    42                 Mcal = getMcal  (m, i, MAG_CLASS_PSF);
    43                 if (isnan(Mcal)) continue;
    44                 Mmos = getMmos  (m, i);
    45                 if (isnan(Mmos)) continue;
    46                 Mgrid = getMgrid (m, i);
    47                 if (isnan(Mgrid)) continue;
     41          if (catalog[i].measureT[m].dbFlags & MEAS_BAD) continue;
     42          Mcal = getMcal  (m, i, MAG_CLASS_PSF);
     43          if (isnan(Mcal)) continue;
     44          Mmos = getMmos  (m, i);
     45          if (isnan(Mmos)) continue;
     46          Mgrid = getMgridTiny (&catalog[i].measureT[m]);
     47          if (isnan(Mgrid)) continue;
    4848
    49                 Mrel = catalog[i].secfilt[Nsecfilt*j+Nsec].MpsfChp;
    50                 if (isnan(Mrel)) continue;
     49          Mrel = catalog[i].secfilt[Nsecfilt*j+Nsec].MpsfChp;
     50          if (isnan(Mrel)) continue;
    5151
    52                 xlist[N] = Mrel;
    53                 ylist[N] = PhotSysTiny (&catalog[i].measureT[m], &catalog[i].averageT[j], &catalog[i].secfilt[j*Nsecfilt], MAG_CLASS_PSF) - Mcal - Mmos - Mgrid - Mrel;
    54                 ilist[N] = PhotInstTiny (&catalog[i].measureT[m], MAG_CLASS_PSF);
    55                 N++;
    56             }
     52          xlist[N] = Mrel;
     53          ylist[N] = PhotSysTiny (&catalog[i].measureT[m], &catalog[i].averageT[j], &catalog[i].secfilt[j*Nsecfilt], MAG_CLASS_PSF) - Mcal - Mmos - Mgrid - Mrel;
     54          ilist[N] = PhotInstTiny (&catalog[i].measureT[m], MAG_CLASS_PSF);
     55          N++;
    5756        }
     57      }
    5858    }
    5959
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/reload_catalogs.c

    r41390 r41649  
    99    gettimeofday (&start, (void *) NULL);
    1010
    11 void reload_catalogs (SkyList *skylist, FlatCorrectionTable *flatcorr, int hostID, char *hostpath) {
     11void reload_catalogs (SkyList *skylist, int hostID, char *hostpath) {
    1212
    1313  int i;
     
    1717
    1818  struct timeval start, stop;
    19   double dtime = 0.0;
    20   double time1 = 0.0;
    21   double time2 = 0.0;
    22   double time3a = 0.0;
    23   double time3b = 0.0;
    24   double time4 = 0.0;
    25   double time5 = 0.0;
    26   double time6 = 0.0;
    27   double time7 = 0.0;
     19  double dtime = 0.0, time1 = 0.0, time2 = 0.0, time3 = 0.0;
     20  double time4 = 0.0, time5 = 0.0, time6 = 0.0, time7 = 0.0, time8 = 0.0;
    2821
    2922  // XXX need to decide how to determine PARALLEL mode...
     
    8174
    8275    populate_tiny_values(&catalog, DVO_TV_MEASURE | DVO_TV_AVERAGE);
    83     TIMESTAMP(time3a);
     76    TIMESTAMP(time3);
    8477
    8578    // XXX need to worry about the image subset data
    8679    initImageBins  (&catalog, 1, FALSE);
    87     initMosaicBins (&catalog, 1, FALSE);
    88     initTGroupBins (&catalog, 1);
    89 
    90     initGridBins   (&catalog, 1);
    91     TIMESTAMP(time3b);
     80    TIMESTAMP(time4);
    9281
    9382    findImages (&catalog, 1, FALSE);
    94     findMosaics (&catalog, 1, FALSE);
    95     findTGroups (&catalog, 1);
    96 
    97     TIMESTAMP(time4);
     83    TIMESTAMP(time5);
    9884
    9985    initMrel (&catalog, 1);
    100     setMrelFinal (&catalog, flatcorr, FALSE);
    101     TIMESTAMP(time5);
     86
     87    setMrelFinal (&catalog, FALSE);
     88    TIMESTAMP(time6);
    10289
    10390    // modify the output format as desired (ignore current format on disk)
     
    119106    free_tiny_values(&catalog);
    120107    dvo_catalog_free (&catalog);
    121     TIMESTAMP(time6);
    122 
    123     // XXX freeTgroupBins here:
     108    TIMESTAMP(time7);
    124109
    125110    freeImageBins (1, FALSE);
    126     freeMosaicBins (1, FALSE);
    127     freeTGroupBins (1);
    128     freeGridBins (1);
    129     TIMESTAMP(time7);
     111    TIMESTAMP(time8);
    130112
    131113    if (hostID) {
     
    134116  }
    135117
    136   fprintf (stderr, "time step 1  %10.3f sec : find catalog\n", time1);
    137   fprintf (stderr, "time step 2  %10.3f sec : load catalog\n", time2);
    138   fprintf (stderr, "time step 3  %10.3f sec : make tiny values\n", time3a);
    139   fprintf (stderr, "time step 4  %10.3f sec : init imbins\n",  time3b);
    140   fprintf (stderr, "time step 5  %10.3f sec : find images\n",  time4);
    141   fprintf (stderr, "time step 6  %10.3f sec : set Mrel\n",     time5);
    142   fprintf (stderr, "time step 7  %10.3f sec : save catalog\n", time6);
    143   fprintf (stderr, "time step 8  %10.3f sec : free catalog\n", time7);
     118  fprintf (stderr, "time step 1  %10.3f sec : find catalog\n",     time1);
     119  fprintf (stderr, "time step 2  %10.3f sec : load catalog\n",     time2);
     120  fprintf (stderr, "time step 3  %10.3f sec : make tiny values\n", time3);
     121  fprintf (stderr, "time step 4  %10.3f sec : init imbins\n",      time4);
     122  fprintf (stderr, "time step 5  %10.3f sec : find images\n",      time5);
     123  fprintf (stderr, "time step 6  %10.3f sec : set Mrel\n",         time6);
     124  fprintf (stderr, "time step 7  %10.3f sec : save catalog\n",     time7);
     125  fprintf (stderr, "time step 8  %10.3f sec : free catalog\n",     time8);
    144126}
    145127
     
    231213    char *command = NULL;
    232214    strextend (&command, "relphot_client %s -update-catalogs %s", PhotcodeList, imageFile);
    233     strextend (&command, "-hostID %d -D CATDIR %s -hostdir %s", group->hosts[i][0].hostID, CATDIR, group->hosts[i][0].pathname);
     215    strextend (&command, "-hostID %d", group->hosts[i][0].hostID);
     216    strextend (&command, "-D CATDIR %s", CATDIR);
     217    strextend (&command, "-hostdir %s", group->hosts[i][0].pathname);
    234218    strextend (&command, "-region %f %f %f %f", UserPatch.Rmin, UserPatch.Rmax, UserPatch.Dmin, UserPatch.Dmax);
    235219    strextend (&command, "-statmode %s", STATMODE);
    236220    strextend (&command, "-D CAMERA %s", CAMERA);
    237     strextend (&command, "-D STAR_TOOFEW %d -minerror %f", STAR_TOOFEW, MIN_ERROR);
    238 
    239     // options & configs which affect relphot_client -update-catalogs
    240     // VERBOSE, VERBOSE2
    241     // RESET
    242     // RESET_ZEROPTS
    243     // TimeSelect
    244     // AreaSelect
    245     // STATMODE
    246     // STAR_TOOFEW
    247     // MIN_ERROR
    248    
     221    strextend (&command, "-D STAR_TOOFEW %d", STAR_TOOFEW);
     222    strextend (&command, "-minerror %f", MIN_ERROR);
     223
    249224    if (VERBOSE)           { strextend (&command, "-v"); }
    250225    if (VERBOSE2)          { strextend (&command, "-vv"); }
    251226    if (RESET)             { strextend (&command, "-reset"); }
    252227    if (RESET_ZEROPTS)     { strextend (&command, "-reset-zpts"); }
     228    if (RESET_FLATCORR)    { strextend (&command, "-reset-flat"); }
     229    if (!KEEP_UBERCAL)     { strextend (&command, "-reset-ubercal"); }
    253230    if (PRESERVE_PS1)      { strextend (&command, "-preserve-ps1"); }
     231    if (IS_DIFF_DB)        { strextend (&command, "-is-diff-db"); }
    254232    if (UPDATE)            { strextend (&command, "-update"); }
    255     if (IS_DIFF_DB)        { strextend (&command, "-is-diff-db"); }
    256     if (!KEEP_UBERCAL)     { strextend (&command, "-reset-ubercal"); }
    257233    if (UPDATE_CATFORMAT)  { strextend (&command, "-update-catformat %s", UPDATE_CATFORMAT); }
    258234    if (BOUNDARY_TREE)     { strextend (&command, "-boundary-tree %s", BOUNDARY_TREE); }
    259235    if (SYNTH_ZERO_POINTS) { strextend (&command, "-synthphot-zpts %s", SYNTH_ZERO_POINTS); }
     236    if (GRID_ZEROPT)       { strextend (&command, "-grid %s", GRID_MEANFILE); }
    260237    if (USE_BASIC_CHECK)   {  strextend (&command, "-basic-image-search"); }
     238    // if (USE_ALL_IMAGES)    { strextend (&command, "-use-all-images"); }
    261239    if (USE_MCAL_PSF_FOR_STACK_APER) { strextend (&command, "-use-mcal-psf-for-stack-aper"); }
    262240
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/relphot.c

    r39481 r41649  
    3434  switch (mode) {
    3535    case UPDATE_IMAGES:
     36      // calculate zero points for images (may group by exposure [mosaic], night [tgroups]; may measure flat-correction)
    3637      // IF CALLED WITH NLOOP == 0, DOES NOT LOAD bcatalog, just loads image table and generates ImageSubset.dat
     38      // If called with -update, calls reload_catalogs() just like apply_offsets
    3739      relphot_images (skylist);
    3840      relphot_free (sky, skylist);
     
    5254
    5355    case PARALLEL_REGIONS:
    54       // run image updates in parallel across multiple remote machines
     56      // calculate zero points for images (may group my exposure [mosaic], night [tgroups]; may measure flat-correction)
     57      // equivalent to relphot_images, but run in parallel across multiple remote machines
    5558      relphot_parallel_regions (sky);
    5659      relphot_free (sky, skylist);
     
    6972        exit (2);
    7073      }
    71       reload_catalogs (skylist, NULL, 0, NULL);
     74      // we do not need to load grid corrections here.  the value of
     75      // GRID_MEANFILE, if specified, is passed to the clients
     76      reload_catalogs (skylist, 0, NULL);
    7277      relphot_free (sky, skylist);
    7378      exit (0);
     
    8489
    8590    I would like to merge the functionality of relphot_images (Nloop == 0), relphot_objects, and apply_offsets
     91
     92    relphot_objects vs reload_objects (apply offsets):
     93
     94    relphot_objects
     95   
    8696   
    8797***/
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/relphot_client.c

    r39643 r41649  
    8080      initImagesSubset (image, NULL, Nimage);
    8181
    82       // load the flat-field correction table from CATDIR
    83       FlatCorrectionTable *flatcorr = NULL;
    84       reload_catalogs (skylist, flatcorr, HOST_ID, HOSTDIR);
     82      // load grid corrections here
     83      GridCorrectionLoad (GRID_MEANFILE);
     84
     85      reload_catalogs (skylist, HOST_ID, HOSTDIR);
    8586      freeImages ((char *)image);
    8687      free (image);
     88      freeGridBins ();
    8789      client_logger_message ("updated catalogs\n");
    8890      relphot_client_free (sky, skylist);
     
    9092    }
    9193
     94/* deprecated (absorbed into MODE_UPDATE)
    9295    case MODE_UPDATE_OBJECTS: {
    9396      // take the current set of detections and set the mean magnitudes
     
    97100      break;
    98101    }
     102*/
    99103
    100104    case MODE_SYNTH_PHOT:
     
    104108      break;
    105109
     110    case MODE_UPDATE_OBJECTS:
    106111    default:
    107112      fprintf (stderr, "impossible!");
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/relphot_images.c

    r41556 r41649  
    3838  MARKTIME("-- load image data: %f sec\n", dtime);
    3939
    40   /* load regions and images based on specified sky patch and/or catalog */
     40  // load regions and images based on specified sky patch and/or catalog
     41  // NOTE: load_images transfers zero points from images to mosaics (initMosaicMcal)
     42  // and to tgroups (initTGroupMcal), resetting the image zero points to 0.0.
     43
     44  // (if both tgroups and mosaics are used, the mosaics will hold the value and tgroups
     45  // will get values of 0.0.  This is not clearly the right way to go, but may not matter
     46  // if we reset everything).
     47
    4148  load_images (&db, skylist, &UserPatch, FALSE, USE_ALL_IMAGES);
    4249  MARKTIME("-- load images: %f sec\n", dtime);
     
    4552  if (!UPDATE) dvo_image_unlock (&db);
    4653
    47   // load the flat correction table (if defined)
    48   // we no longer need to do this: the flatcorrection is now saved in measure.Mflat
    49 # if (0)
    50   char flatcorrfile[256];
    51   sprintf (flatcorrfile, "%s/flatcorr.fits", CATDIR);
    52   FlatCorrectionTable *flatcorr = FlatCorrectionLoad (flatcorrfile, VERBOSE);
    53 # endif
    54   FlatCorrectionTable *flatcorr = NULL;
     54  initGridBins (); // allocates the empty array of corrections (elements are built below)
    5555
    5656  if (CALIBRATE_STACKS_AND_WARPS || (NLOOP > 0)) {
     57    initGrid (); // allocate grid correction entries for existing photcodes
     58
    5759    /* load catalog data from region files (hostID is 0 since we are not a client */
    5860    catalog = load_catalogs (skylist, &Ncatalog, 0, NULL, NULL);
     
    6870    initTGroupBins (catalog, Ncatalog);
    6971
    70     initGridBins   (catalog, Ncatalog);
    7172    initMrel (catalog, Ncatalog);
    7273
     
    7475    MARKTIME("-- set up image indexes: %f sec\n", dtime);
    7576
    76     findMosaics (catalog, Ncatalog, TRUE);  /* also sets Grid values */
     77    findMosaics (catalog, Ncatalog, TRUE);
    7778    MARKTIME("-- set up mosaic indexes: %f sec\n", dtime);
    7879
     
    8283    SAVEPLOT = FALSE;
    8384
     85    // mark ID_MEAS_AREA (user-selected chip region) and ID_MEAS_NOCAL (time range & active photcode)
    8486    setExclusions (catalog, Ncatalog, TRUE);
    8587
    86     global_stats (catalog, Ncatalog, flatcorr, 0);
     88    global_stats (catalog, Ncatalog, 0);
    8789
    8890    if (PLOTSTUFF) {
     
    9193    }
    9294
    93     // if we are measuring the flat-field correction grid, we need to perform a number of iterations first:
    94     if (USE_GRID) {
    95       int star_toofew;
    96 
    97       // until we finish the grid analysis, do not reject stars out-of-hand based on ID_OBJ_FEW
    98       // XXX this is kind of poor: need to have a better distinctions about STAR_BAD in setMrel vs getMrel
    99       star_toofew = STAR_TOOFEW;
    100       STAR_TOOFEW = 0;
    101       for (i = 0; i < NGRID; i++) {
    102         STAR_BAD = ID_OBJ_POOR;
    103         setMrel  (catalog, Ncatalog, flatcorr);
    104         STAR_BAD  = ID_OBJ_POOR | ID_OBJ_FEW;
    105         setMgrid (catalog, flatcorr);
    106       }
    107       STAR_BAD  = ID_OBJ_POOR | ID_OBJ_FEW;
    108       STAR_TOOFEW = star_toofew;
    109     }
    110 
    11195    /* determine fit values */
    11296    for (i = 0; i < NLOOP; i++) {
    11397      SetZptIteration (i);
    11498
    115       setMrel  (catalog, Ncatalog, flatcorr); // threaded
    116 
    117       setMcal  (catalog, flatcorr);
    118       setMmos  (catalog, flatcorr);
    119       setMgrp  (catalog, flatcorr);
    120 
    121       setMgrid (catalog, flatcorr);
     99      setMrel  (catalog, Ncatalog); // threaded (calls setMrelCatalog)
     100
     101      setMcal  (catalog);
     102      setMmos  (catalog);
     103      setMgrp  (catalog);
     104
     105      setMgrid (catalog, Ncatalog);
    122106      MARKTIME("-- set Mrel, Mcal, Mmos, Mgrid : %f sec\n", dtime);
    123107   
    124108      if (PLOTSTUFF) {
    125         plot_scatter (catalog, Ncatalog, flatcorr);
    126         plot_grid (catalog, flatcorr);
     109        plot_scatter (catalog, Ncatalog);
    127110        plot_mosaics ();
    128111        plot_images ();
     
    131114      }
    132115
    133       global_stats (catalog, Ncatalog, flatcorr, i);
    134       SetZeroPointModes ();
     116      global_stats (catalog, Ncatalog, i);
     117      SetZeroPointModes (catalog, Ncatalog);
    135118
    136119      MARKTIME("-- finished loop %d: %f sec\n", i, dtime);
     
    139122
    140123    if (PLOTSTUFF) {
    141       plot_scatter (catalog, Ncatalog, flatcorr);
    142       plot_grid (catalog, flatcorr);
     124      plot_scatter (catalog, Ncatalog);
    143125      plot_mosaics ();
    144126      plot_images ();
     
    147129    }
    148130 
    149     if (USE_GRID) dump_grid ();
     131    // if (GRID_ZEROPT) dump_grid ();
    150132
    151133    MARKTIME("-- finalize Mcal values: %f sec\n", dtime);
     
    169151    freeMosaicBins (Ncatalog, TRUE);
    170152    freeTGroupBins (Ncatalog);
    171     freeGridBins (Ncatalog);
     153
     154    GridCorrectionSave ();
    172155
    173156    // end of if (NLOOP > 0) block : this loop determines the offsets per chip
     
    179162  }
    180163
     164  // once the zero points have been calculated, they are reassigned to the
     165  // individual images.  At this point, the mosaic and tgroup values should not
     166  // be used.
     167  freeMosaics ();
     168  freeTGroups ();
     169  MOSAIC_ZEROPT = FALSE;
     170  TGROUP_ZEROPT = FALSE;
     171
     172  // only change the real database files if -update is requested
     173  if (!UPDATE) {
     174    dvo_image_unlock (&db);
     175    freeImages (db.ftable.buffer);
     176    gfits_db_free (&db);
     177    freeGridBins ();
     178    return TRUE;
     179  }
     180 
    181181  reload_images (&db);
    182182
    183   // only change the real database files if -update is requested
    184   if (!UPDATE) exit (0);
    185  
    186183  /* Load catalog data from region files, update Mrel include all data.  In a parallel
    187184     context, this function writes the image parameters as a subset table for the remote
    188185     clients */
    189186  if (!CALIBRATE_STACKS_AND_WARPS) {
    190     reload_catalogs (skylist, flatcorr, 0, NULL);
     187    reload_catalogs (skylist, 0, NULL); // calls setMrelFinal which setMrelOutput which calls setMrelCatalog
    191188    MARKTIME("-- updated all catalogs: %f sec\n", dtime);
    192189  }
    193190
    194191  if (UPDATE_CATFORMAT) {
    195     // ensure the db format is updated
     192    // ensure the Image db format is updated
    196193    db.format = dvo_catalog_catformat (UPDATE_CATFORMAT);
    197194    gfits_modify (&db.header, "FORMAT", "%s", 1, UPDATE_CATFORMAT);
     
    204201
    205202  freeImages (db.ftable.buffer);
    206   freeMosaics ();
     203  freeGridBins ();
     204
    207205  gfits_db_free (&db);
    208206
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/relphot_objects.c

    r41507 r41649  
    66// has been correctly propagated to the measurement, the average will respect that value.
    77
    8 int relphot_objects_parallel (SkyList *sky);
    9 
    108int relphot_objects (SkyList *skylist, int hostID, char *hostpath) {
    119
    12   off_t i, j, k;
    13   int Nsecfilt;
    14   struct stat filestat;
    15 
    16   Catalog catalog;
     10  FITS_DB db;
    1711
    1812  INITTIME;
    1913
    20   // XXX need to decide how to determine PARALLEL mode...
    21   if (PARALLEL && !hostID) {
    22     relphot_objects_parallel (skylist);
    23     return TRUE;
    24   }
    25 
    26   FITS_DB db;
    27      
    2814  set_db (&db);
    2915  gfits_db_init (&db);
     
    4127  MARKTIME("loaded images: %f sec\n", dtime);
    4228
    43   // load the ZP corrections here
    44   if (SYNTH_ZERO_POINTS) SynthZeroPointsLoad (SYNTH_ZERO_POINTS);
     29  // load grid corrections here (specified by -grid-meanfile)
     30  GridCorrectionLoad (GRID_MEANFILE);
    4531
    46   if (REPAIR_WARPS) {
    47     FindWarpGroups ();
    48     MARKTIME("setup warp groups: %f sec\n", dtime);
    49     MakeStackIndex ();
    50     MARKTIME("setup stack index: %f sec\n", dtime);
    51     RepairWarpMeasuresOpenLogfile ();
    52   }
    53 
    54   // load data from each region file, only use bright stars
    55   for (i = 0; i < skylist[0].Nregions; i++) {
    56 
    57     // does this host ID match the desired location for the table?
    58     if (!HostTableTestHost(skylist[0].regions[i], hostID)) continue;
    59 
    60     // set up the basic catalog info
    61     char hostfile[1024];
    62     snprintf (hostfile, 1024, "%s/%s.cpt", hostpath, skylist[0].regions[i]->name);
    63 
    64     dvo_catalog_init (&catalog, TRUE);
    65     catalog.filename    = hostID ? hostfile : skylist[0].filename[i];
    66 
    67     // only update existing db tables
    68     int status = stat (catalog.filename, &filestat);
    69     if ((status == -1) && (errno == ENOENT)) {
    70       if (VERBOSE) fprintf (stderr, "no file %s, skipping\n", catalog.filename);
    71       continue;
    72     }
    73 
    74     catalog.catflags    = DVO_LOAD_AVERAGE | DVO_LOAD_MEASURE | DVO_LOAD_MISSING | DVO_LOAD_SECFILT;
    75     // if we are going to update the format, we should update all tables
    76     if (UPDATE_CATFORMAT) {
    77       catalog.catflags |= DVO_LOAD_LENSING | DVO_LOAD_LENSOBJ | DVO_LOAD_STARPAR | DVO_LOAD_GALPHOT;
    78     }
    79     catalog.Nsecfilt    = GetPhotcodeNsecfilt ();
    80 
    81     if (!dvo_catalog_open (&catalog, skylist[0].regions[i], VERBOSE, "w")) {
    82       fprintf (stderr, "ERROR: failure reading catalog %s, skipping\n", catalog.filename);
    83       continue;
    84     }
    85     if (!catalog.Naverage_disk) {
    86       if (VERBOSE) fprintf (stderr, "no data in %s, skipping\n", catalog.filename);
    87       dvo_catalog_unlock (&catalog);
    88       dvo_catalog_free (&catalog);
    89       continue;
    90     }
    91 
    92     // reset the calculated average magnitudes (does not affect ubercal-tied measurements or images)
    93     if (RESET) {
    94       Nsecfilt = catalog.Nsecfilt;
    95 
    96       DVOAverageFlags photomBits =
    97         ID_OBJ_EXT             | // extended in our data (eg, PS)
    98         ID_OBJ_EXT_ALT         | // extended in external data (eg, 2MASS)
    99         ID_OBJ_GOOD            | // good-quality measurement in our data (eg,PS)
    100         ID_OBJ_GOOD_ALT        | // good-quality measurement in  external data (eg, 2MASS)
    101         ID_OBJ_GOOD_STACK      | // good-quality object in the stack (> 1 good stack)
    102         ID_OBJ_BEST_STACK      | // the primary stack measurement are the best measurements
    103         ID_OBJ_SUSPECT_STACK   | // suspect object in the stack (> 1 good or suspect stack, < 2 good)
    104         ID_OBJ_BAD_STACK;        // good-quality object in the stack (> 1 good stack)
    105      
    106       for (j = 0; j < catalog.Naverage; j++) {
    107         catalog.average[j].flags    &= ~photomBits; // reset all except astrometry bits
    108         catalog.average[j].psfQF     = NAN;     // reset (will be re-calculated here)
    109         catalog.average[j].psfQFperf = NAN;     // reset (will be re-calculated here)
    110         catalog.average[j].stargal   = NAN;     // reset (will be re-calculated here)
    111         catalog.average[j].photFlagsUpper = 0;  // reset (will be re-calculated here)
    112         catalog.average[j].photFlagsLower = 0;  // reset (will be re-calculated here)
    113         catalog.average[j].NwarpOK        = 0;  // reset (will be re-calculated here)
    114         for (k = 0; k < Nsecfilt; k++) {
    115           dvo_secfilt_init (&catalog.secfilt[j*Nsecfilt + k], SECFILT_RESET_ALL);
    116         }
    117       }
    118     }
    119 
    120     populate_tiny_values(&catalog, DVO_TV_MEASURE | DVO_TV_AVERAGE);
    121 
    122     // XXX need to worry about the image subset data
    123     initImageBins  (&catalog, 1, FALSE);
    124     initMosaicBins (&catalog, 1, FALSE);
    125     initGridBins   (&catalog, 1);
    126 
    127     findImages (&catalog, 1, FALSE);
    128     findMosaics (&catalog, 1, FALSE);
    129 
    130     // update the detection coordinates using the new image parameters
    131     if (REPAIR_WARPS) RepairWarpMeasures (&catalog);
    132 
    133     initMrel (&catalog, 1);
    134     setMrelFinal (&catalog, NULL, TRUE);
    135 
    136     // uncomment for extra verbosity
    137     // MARKTIME("setMrelFinal for "OFF_T_FMT" average "OFF_T_FMT" measure : %f sec\n", catalog.Naverage, catalog.Nmeasure, dtime);
    138     // gettimeofday (&startTimer, NULL); // reset timer
    139 
    140     // XXX if we want to have options for setting warp, chip, stack independently, we need to init only the desired ones
    141     // NOTE flatcorr == NULL, but it should have been applied already by setphot
    142 
    143     if (!UPDATE) {
    144       dvo_catalog_unlock (&catalog);
    145       free_tiny_values(&catalog);
    146       dvo_catalog_free (&catalog);
    147       freeImageBins (1, FALSE);
    148       freeMosaicBins (1, FALSE);
    149       freeGridBins (1);
    150       continue;
    151     }
    152    
    153     if (VERBOSE) fprintf (stderr, "saving catalog %s\n", catalog.filename);
    154    
    155     char history[128];
    156     struct timeval now;
    157     gettimeofday (&now, (void *) NULL);
    158     char *moddate = ohana_sec_to_date (now.tv_sec);
    159     gfits_modify (&catalog.header, "RELPHOT", "%s", 1, moddate);     
    160     if (REPAIR_WARPS) {
    161       snprintf (history, 128, "repair warp measure.imageID: %s", moddate);
    162       gfits_modify_alt (&catalog.header, "HISTORY", "%S", 0, history); // adds a new entry
    163     }
    164     free (moddate);
    165 
    166     // we can optionally convert output format here
    167     // but it would be better to define a dvo crawler program to do this
    168     // catalog.catformat = DVO_FORMAT_PS1_V1;
    169 
    170     // modify the output format as desired (ignore current format on disk)
    171     if (UPDATE_CATFORMAT) {
    172       catalog.catformat = dvo_catalog_catformat (UPDATE_CATFORMAT);
    173     }
    174    
    175     SetProtect (TRUE);
    176     if (!dvo_catalog_save (&catalog, VERBOSE)) { fprintf (stderr, "ERROR: failed to save %s\n", catalog.filename); exit (1); }
    177     if (!dvo_catalog_unlock (&catalog)) { fprintf (stderr, "ERROR: failed to unlock %s\n", catalog.filename); exit (1); }
    178     SetProtect (FALSE);
    179 
    180     free_tiny_values(&catalog);
    181     dvo_catalog_free (&catalog);
    182 
    183     freeImageBins (1, FALSE);
    184     freeMosaicBins (1, FALSE);
    185     freeGridBins (1);
    186   }
    187 
    188   if (REPAIR_WARPS) {
    189     FreeWarpGroups ();
    190     FreeStackGroups ();
    191     RepairWarpMeasuresCloseLogfile ();
    192   }
     32  reload_catalogs (skylist, hostID, hostpath);
    19333
    19434  freeImages(db.ftable.buffer);
     35  freeGridBins ();
     36
    19537  gfits_db_free (&db);
    19638
    19739  return (TRUE);
    19840}
    199 
    200 // CATDIR is supplied globally
    201 # define DEBUG 1
    202 int relphot_objects_parallel (SkyList *sky) {
    203 
    204   // launch the setphot_client jobs to the parallel hosts
    205 
    206   // load the list of hosts
    207   HostTable *table = HostTableLoad (CATDIR, sky->hosts);
    208   if (!table) {
    209     fprintf (stderr, "ERROR: failure reading Host Table %s for database %s\n", sky->hosts, CATDIR);
    210     exit (1);
    211   }   
    212 
    213   if (BOUNDARY_TREE) {
    214     char *tmppath = abspath(BOUNDARY_TREE, DVO_MAX_PATH);
    215     free (BOUNDARY_TREE);
    216     BOUNDARY_TREE = tmppath;
    217   }
    218 
    219   int i;
    220   for (i = 0; i < table->Nhosts; i++) {
    221 
    222     // ensure that the paths are absolute path names
    223     char *tmppath = abspath (table->hosts[i].pathname, DVO_MAX_PATH);
    224     free (table->hosts[i].pathname);
    225     table->hosts[i].pathname = tmppath;
    226 
    227     // options / arguments that can affect relphot_client -update-objects:
    228     // VERBOSE, VERBOSE2
    229     // KEEP_UBERCAL
    230     // RESET (-reset)
    231     // TimeSelect -time
    232     // DophotSelect
    233     // (note that psfQF is applied rigidly at 0.85, as is the galaxy test)
    234     // MAG_LIM
    235     // SIGMA_LIM
    236     // ImagSelect, ImagMin, ImagMax
    237     // MaxDensityUse, MaxDensityValue
    238 
    239     char *command = NULL;
    240     strextend (&command, "relphot_client -update-objects");
    241     strextend (&command, "-hostID %d", table->hosts[i].hostID);
    242     strextend (&command, "-D CATDIR %s", CATDIR);
    243     strextend (&command, "-hostdir %s", table->hosts[i].pathname);
    244     strextend (&command, "-region %f %f %f %f", UserPatch.Rmin, UserPatch.Rmax, UserPatch.Dmin, UserPatch.Dmax);
    245     strextend (&command, "-statmode %s", STATMODE);
    246     strextend (&command, "-D CAMERA %s", CAMERA);
    247     strextend (&command, "-D STAR_TOOFEW %d", STAR_TOOFEW);
    248     strextend (&command, "-minerror %f", MIN_ERROR);
    249 
    250     if (VERBOSE)           { strextend (&command, "-v"); }
    251     if (VERBOSE2)          { strextend (&command, "-vv"); }
    252     if (RESET)             { strextend (&command, "-reset"); }
    253     if (RESET_ZEROPTS)     { strextend (&command, "-reset-zpts"); }
    254     if (REPAIR_WARPS)      { strextend (&command, "-repair-warps"); }
    255     if (PRESERVE_PS1)      { strextend (&command, "-preserve-ps1"); }
    256     if (IS_DIFF_DB)        { strextend (&command, "-is-diff-db"); }
    257     if (UPDATE)            { strextend (&command, "-update"); }
    258     if (!KEEP_UBERCAL)     { strextend (&command, "-reset-ubercal"); }
    259     if (UPDATE_CATFORMAT)  { strextend (&command, "-update-catformat %s", UPDATE_CATFORMAT); }
    260     if (BOUNDARY_TREE)     { strextend (&command, "-boundary-tree %s", BOUNDARY_TREE); }
    261     if (SYNTH_ZERO_POINTS) { strextend (&command, "-synthphot-zpts %s", SYNTH_ZERO_POINTS); }
    262     if (USE_BASIC_CHECK)   { strextend (&command, "-basic-image-search"); }
    263     if (USE_ALL_IMAGES)    { strextend (&command, "-use-all-images"); }
    264     if (USE_MCAL_PSF_FOR_STACK_APER) { strextend (&command, "-use-mcal-psf-for-stack-aper"); }
    265 
    266     if (!(STAGES & STAGE_CHIP))  { strextend (&command, "-skip-chip"); }
    267     if (!(STAGES & STAGE_WARP))  { strextend (&command, "-skip-warp"); }
    268     if (!(STAGES & STAGE_STACK)) { strextend (&command, "-skip-stack"); }
    269 
    270     // if (SET_MREL_VERSION != 1) { strextend (&command, "-set-mrel-version %d", SET_MREL_VERSION); }
    271 
    272     fprintf (stderr, "command: %s\n", command);
    273 
    274     if (PARALLEL_MANUAL) {
    275       free (command);
    276       continue;
    277     }
    278 
    279     if (PARALLEL_SERIAL) {
    280       int status = system (command);
    281       if (status) {
    282         fprintf (stderr, "ERROR running relphot_client\n");
    283         exit (2);
    284       }
    285     } else {
    286       // launch the job on the remote machine (no handshake)
    287       int errorInfo = 0;
    288       int pid = rconnect ("ssh", table->hosts[i].hostname, command, table->hosts[i].stdio, &errorInfo, FALSE);
    289       if (!pid) {
    290         if (DEBUG) fprintf (stderr, "failure to start %s (error %d)\n", table->hosts[i].hostname, errorInfo);
    291         exit (1);
    292       }
    293       table->hosts[i].pid = pid; // save for future reference
    294     }
    295     free (command);
    296   }
    297 
    298   if (PARALLEL_MANUAL) {
    299     fprintf (stderr, "run the relphot_client commands above.  when these are done, hit return\n");
    300     getchar();
    301   }
    302   if (!PARALLEL_MANUAL && !PARALLEL_SERIAL) {
    303     HostTableWaitJobsGetIO (table, __FILE__, __LINE__, VERBOSE);
    304   }
    305 
    306   FreeHostTable (table);
    307   return TRUE;
    308 }     
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/relphot_parallel_images.c

    r41556 r41649  
    88 * update the unowned detections for owned objects from neighbor regions
    99 * update the unowned objects for owned detections
     10
     11 * TGROUP and GRID corrections are not calculated.
    1012 */
    1113
     
    3941
    4042  initImages (image, NULL, Nimage);
    41 
    42   // load the flat correction table (if defined)
    43   // we no longer need to do this: the flatcorrection is now saved in measure.Mflat
    44 # if (0)
    45   char flatcorrfile[256];
    46   sprintf (flatcorrfile, "%s/flatcorr.fits", CATDIR);
    47   FlatCorrectionTable *flatcorr = FlatCorrectionLoad (flatcorrfile, VERBOSE);
    48 # endif
    49   FlatCorrectionTable *flatcorr = NULL;
    5043
    5144  // UserPatch.Rmin,Rmax may have range from a few degrees < 0.0 to few degrees > 360.0.
     
    8881  setExclusions (catalog, Ncatalog, TRUE);
    8982
    90   global_stats (catalog, Ncatalog, flatcorr, 0);
     83  global_stats (catalog, Ncatalog, 0);
    9184
    9285  if (PLOTSTUFF) {
     
    10194
    10295    // set the mean stellar mags given the measurements and the image calibrations
    103     setMrel  (catalog, Ncatalog, flatcorr);
     96    setMrel  (catalog, Ncatalog);
    10497
    10598    // share mean mags for objects at the boundary (number of unowned meas > 0)
     
    112105
    113106    // set the image (Mcal) and mosaic (Mmos) zero point offsets given the mean mags and measurements
    114     setMcal  (catalog, flatcorr);
    115     setMmos  (catalog, flatcorr);
    116     // setMgrp  (catalog, FALSE, flatcorr); XXX think this through: this may not make sense for tgroups
     107    setMcal  (catalog);
     108    setMmos  (catalog);
    117109    MARKTIME("-- set Mrel, Mcal, Mmos, Mgrid : %f sec\n", dtime);
    118110   
     
    124116    client_logger_message ("slurped image data : loop %d \n", i);
    125117
    126     global_stats (catalog, Ncatalog, flatcorr, i);
     118    global_stats (catalog, Ncatalog, i);
    127119
    128     SetZeroPointModes ();
     120    SetZeroPointModes (catalog, Ncatalog);
    129121    MARKTIME("-- finished loop %d: %f sec\n", i, dtime);
    130122  }
     
    147139
    148140  setMcalFromMosaics (); // copy per-mosaic calibrations to the images
    149   // XXX keep? setMcalFromTGroups (); // copy per-tgroup calibrations to the images
    150141
    151142  share_image_mags (regionHosts, -1);
     
    161152  freeImageBins(Ncatalog, TRUE);
    162153  freeMosaicBins (Ncatalog, TRUE);
    163   freeGridBins (Ncatalog);
    164154  freeImages((char *)image);
    165155  free (image);
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/relphot_parallel_regions.c

    r41556 r41649  
    1414    exit (2);
    1515  }
    16 
    17   // load the flat correction table (if defined)
    18 # if (0)
    19   char flatcorrfile[256];
    20   sprintf (flatcorrfile, "%s/flatcorr.fits", CATDIR);
    21   FlatCorrectionTable *flatcorr = FlatCorrectionLoad (flatcorrfile, VERBOSE);
    22 # endif
    23   FlatCorrectionTable *flatcorr = NULL;
    2416
    2517  // register database handle with shutdown procedure
     
    8173
    8274  /* update catalogs (in parallel) */
    83   reload_catalogs (skylist, flatcorr, 0, NULL);
     75  reload_catalogs (skylist, 0, NULL);
    8476
    8577  // save the changes to the image parameters
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/select_images.c

    r41485 r41649  
    103103    if (!(i % 300000)) fprintf (stderr, ".");
    104104
    105     // XXX I am just going for force this for the moment:
    106     // goto found_it;
    107 
    108     /* exclude images by photcode (we are not doing this, but I'm not sure why) */
    109     if (FALSE) {
     105    // only include active photcodes in the analysis
     106    if (timage[i].photcode) {
    110107      int Ns = GetActivePhotcodeIndex (timage[i].photcode);
    111108      if (Ns < 0) continue;
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/setMrelCatalog.c

    r41561 r41649  
    6060int useOLS = TRUE; // chosen based on iteration below
    6161
    62 int setMrel_catalog_alt (Catalog *catalog, int Nc, int isSetMrelFinal, FlatCorrectionTable *flatcorr, SetMrelInfo *results, int Nsecfilt) {
     62int setMrelCatalog (Catalog *catalog, int Nc, int isSetMrelFinal, SetMrelInfo *results, int Nsecfilt) {
    6363
    6464  off_t j;
     
    7575
    7676    if (STAGES & STAGE_CHIP) {
    77       setMrelAverageExposure (&catalog[Nc], Nc, j, Nsecfilt, isSetMrelFinal, flatcorr, results);
     77      setMrelAverageExposure (&catalog[Nc], Nc, j, Nsecfilt, isSetMrelFinal, results);
    7878    }
    7979
    8080    // only apply Stack operation on setMrelFinal in first pass
    8181    if (isSetMrelFinal && (STAGES & STAGE_STACK) && !IS_DIFF_DB) {
    82       setMrelAverageStack (&catalog[Nc], Nc, j, Nsecfilt, flatcorr);
     82      setMrelAverageStack (&catalog[Nc], Nc, j, Nsecfilt);
    8383    }
    8484
    8585    // only measure force-warp mean values if issetMrelFinal (make it optional?)
    8686    if (isSetMrelFinal && (STAGES & STAGE_WARP)) {
    87       setMrelAverageForcedWarp (&catalog[Nc], Nc, j, Nsecfilt, flatcorr, results);
     87      setMrelAverageForcedWarp (&catalog[Nc], Nc, j, Nsecfilt, results);
    8888    }
    8989  }
     
    113113
    114114// set mean of chip measurements (selected by photcode range for now):
    115 int setMrelAverageExposure (Catalog *catalog, int cat, off_t ave, int Nsecfilt, int isSetMrelFinal, FlatCorrectionTable *flatcorr, SetMrelInfo *results) {
     115int setMrelAverageExposure (Catalog *catalog, int cat, off_t ave, int Nsecfilt, int isSetMrelFinal, SetMrelInfo *results) {
    116116
    117117  int Nsec;
     
    225225    }
    226226
     227    /* some things to note here:
     228
     229       Mcal, Mmos, Mgrid are only relevant (non-zero) during the relphot_images and
     230       relphot_parallel_images analysis steps. For the final output steps (setMrelFinal),
     231       these are turned off
     232
     233       During the image analysis, Mflat is the prior stored value while Mgrid is the new
     234       measurement.  In the final output step, Mgrid is transferred to Mflat and zero
     235
     236       On the final calculation of Mrel, the value of Mgrid has been applied to Mflat, but
     237       it has not been removed from the GridOps.c structures.  In order to avoid
     238       double-counting, we need to skip Mgrid on the final calculation.
     239    */
     240
    227241    // ** Choose the calibration (depends on the mode : do I have an image reference or not?)
    228242    float Mcal = 0.0, Mmos = 0.0, Mgrid = 0.0, Mflat = 0.0, Mgrp = 0.0;
     
    233247      // data for which the associated image has not been loaded (probably because of
    234248      // overlaps).  Msys + measure.Mcal is our best guess of the true magnitude
    235       Mmos = Mgrid = 0;
    236249      Mcal = measureT[k].McalPSF; // check that this is zero for loaded REF value
    237250    } else {
    238       // getMcal returns image[].Mcal; note the flat-field correction is stored in measure.Mflat
     251      // getMcal returns image[].Mcal
    239252      Mcal  = getMcal (meas, cat, MAG_CLASS_PSF);
    240253      if (isnan(Mcal))  SKIP_THIS_MEAS(Ncal);
    241       Mmos  = getMmos  (meas, cat);
    242       if (isnan(Mmos))  SKIP_THIS_MEAS(Nmos);
    243       Mgrp  = getMgrp  (meas, cat, measureT[k].airmass, &dMgrp);
    244       if (isnan(Mgrp))  SKIP_THIS_MEAS(Ngrp);
    245       Mgrid = getMgrid (meas, cat);
    246       if (isnan(Mgrid)) SKIP_THIS_MEAS(Ngrid);
     254
     255      // the flat-field correction is stored in measure.Mflat
    247256      Mflat = isnan (measureT[k].Mflat) ? 0.0 : measureT[k].Mflat;
     257
     258      // see note above re: final output vs image analysis
     259      if (!isSetMrelFinal) {
     260        Mmos  = getMmos  (meas, cat);
     261        if (isnan(Mmos))  SKIP_THIS_MEAS(Nmos);
     262        Mgrp  = getMgrp  (meas, cat, measureT[k].airmass, &dMgrp);
     263        if (isnan(Mgrp))  SKIP_THIS_MEAS(Ngrp);
     264        Mgrid = getMgridTiny (&measureT[k]);
     265        if (isnan(Mgrid)) SKIP_THIS_MEAS(Ngrid);
     266      }
    248267    }
    249268
     
    269288    float dMap = NAN;
    270289
    271     // XXX I am not convinced the sign on Mflat here is correct
    272     float Moff =  Mflat + Mcal + Mmos + Mgrp + Mgrid;
     290    // This definition is consistent with PhotRel: Mrel = Msys - Mcal - Mflat
     291    float Moff =  Mcal + Mmos + Mgrp + Mgrid + Mflat;
    273292
    274293    if (isSetMrelFinal) {
     
    349368  for (Nsec = 0; Nsec < Nsecfilt; Nsec++) {
    350369
    351     // if we detected this object in PS1, or do not request -preserve-ps1, keep the mean photometry values
     370    // -preserve-ps1 means keep an existing average PS1 value
     371    // if we did not detect this object in PS1, or do not request -preserve-ps1, keep the mean photometry values
    352372    if (!PRESERVE_PS1 || !(secfilt[Nsec].flags & ID_SECF_HAS_PS1)) {
    353373      dvo_secfilt_init (&secfilt[Nsec], SECFILT_RESET_CHIP); // this does not reset astrometry or STACK bits
     
    364384    }
    365385
     386    // if -preserve-ps1 is set and this object has PS1 data, skip the rest of the steps:
     387    // NOTE: This test only applies if this bit was set by an earlier analysis
    366388    if (PRESERVE_PS1 && (secfilt[Nsec].flags & ID_SECF_HAS_PS1)) continue;
    367     // if -preserve-ps1 is set and this object has PS1 data, skip the rest of the steps:
    368389
    369390    // XXX hardwired grizy = (01234) JHK = (567) w = (8)
     
    416437    int NrankingPSF = useOLS ? magStatsByRanking (&results->psfData[Nsec], psfstats) : magStatsByRankingIRLS (&results->psfData[Nsec], psfstats);
    417438    if (NrankingPSF < Nminmeas) {
    418       secfilt[Nsec].flags |= ID_OBJ_FEW;
     439      secfilt[Nsec].flags |= ID_SECF_STAR_FEW;
    419440    } else {
    420441      secfilt[Nsec].MpsfChp  = psfstats->mean;
    421442      secfilt[Nsec].dMpsfChp = psfstats->error;
    422443      secfilt[Nsec].Mchisq   = (psfstats->Nmeas > 1) ? psfstats->chisq : NAN;
     444      secfilt[Nsec].flags &= ~ID_SECF_STAR_FEW;
    423445    }
    424446
     
    552574// measure->McalAPER to image->McalPSF for chips and warps, but not stacks
    553575
    554 int setMrelAverageStack (Catalog *catalog, int cat, off_t ave, int Nsecfilt, FlatCorrectionTable *flatcorr) {
     576int setMrelAverageStack (Catalog *catalog, int cat, off_t ave, int Nsecfilt) {
    555577
    556578  // we are guaranteed to have average, measure, secfilt
     
    562584  SecFilt *secfilt = &catalog[0].secfilt[ave*Nsecfilt];
    563585
    564   float McalPSF = 0, McalAPER = 0, Mmos = 0, Mgrid = 0;
     586  float McalPSF = 0, McalAPER = 0;
    565587
    566588  // set the primary projection cell and skycell for this coordinate
     
    604626
    605627    // reset all stack-related values for this secfilt:
    606     secfilt[Nsec].stackBestOff = -1;
    607     secfilt[Nsec].stackPrmryOff = -1;
    608     secfilt[Nsec].FpsfStk   = NAN;
    609     secfilt[Nsec].dFpsfStk  = NAN;
    610     secfilt[Nsec].FkronStk  = NAN;
    611     secfilt[Nsec].dFkronStk = NAN;
    612     secfilt[Nsec].FapStk    = NAN;
    613     secfilt[Nsec].dFapStk   = NAN;
    614     secfilt[Nsec].MpsfStk   = NAN;
    615     secfilt[Nsec].MkronStk  = NAN;
    616     secfilt[Nsec].MapStk    = NAN;
    617     secfilt[Nsec].Nstack    = 0;
    618     secfilt[Nsec].NstackDet = 0;
    619     secfilt[Nsec].flags    &= ~ID_SECF_STACK_FLAGS; // reset the stack flags
     628    dvo_secfilt_init (&secfilt[Nsec], SECFILT_RESET_STACK);
    620629
    621630    for (off_t k = 0; k < Nmeasure; k++) {
     
    638647      haveStack = TRUE;
    639648      haveStackObject = TRUE;
    640 
    641       // if (measure[k].dbFlags & MEAS_BAD) SKIP_THIS_MEAS_STACK(Nbad);
    642649
    643650      int isPrimary = FALSE;
     
    726733      McalPSF  = measure[meas].McalPSF; // check that this is zero for loaded REF value
    727734      McalAPER = McalPSF; // check that this is zero for loaded REF value
    728       Mmos     = 0.0;
    729       Mgrid    = 0.0;
    730735    } else {
    731736      McalPSF   = getMcal  (measSeq, cat, MAG_CLASS_PSF);
    732737      McalAPER  = USE_MCAL_PSF_FOR_STACK_APER ? getMcal  (measSeq, cat, MAG_CLASS_PSF) : getMcal  (measSeq, cat, MAG_CLASS_KRON);
    733       Mmos      = getMmos  (measSeq, cat);
    734       Mgrid     = getMgrid (measSeq, cat);
    735       // XXX can Mmos and Mgrid exist for stacks?
    736738    }
    737739   
     
    769771    // get the zero point for the selected image
    770772    // Use a different zero point for the PSF-like and APERTURE-like magnitudes
    771     float zpPSF  = PhotZeroPoint (&measure[meas], &average[0], &secfilt[0]) - (McalPSF  + Mmos + Mgrid);
    772     float zpAPER = PhotZeroPoint (&measure[meas], &average[0], &secfilt[0]) - (McalAPER + Mmos + Mgrid);
     773    float zpPSF  = PhotZeroPoint (&measure[meas], &average[0], &secfilt[0]) - McalPSF;
     774    float zpAPER = PhotZeroPoint (&measure[meas], &average[0], &secfilt[0]) - McalAPER;
    773775
    774776    // zpFactor to go from instrumental flux to Janskies
     
    884886// chips and warps, but not stacks
    885887
    886 int setMrelAverageForcedWarp (Catalog *catalog, int cat, off_t ave, int Nsecfilt, FlatCorrectionTable *flatcorr, SetMrelInfo *results) {
    887   OHANA_UNUSED_PARAM(flatcorr);
     888int setMrelAverageForcedWarp (Catalog *catalog, int cat, off_t ave, int Nsecfilt, SetMrelInfo *results) {
    888889
    889890  // we are guaranteed to have average, measure, secfilt
  • tags/ipp-ps1-20210510/Ohana/src/relphot/src/setMrelFinal.c

    r40291 r41649  
    55// output dbFlags values
    66
    7 void setMrelFinal (Catalog *catalog, FlatCorrectionTable *flatcorr, int simpleAverage) {
     7void setMrelFinal (Catalog *catalog, int simpleAverage) {
    88
    99  off_t i;
     
    1111  int Nsecfilt = GetPhotcodeNsecfilt ();
    1212
    13   /*** RESET photometry flags and Mcal values ***/
    14   if (RESET) {
    15     // flags used by the photometry analysis (excluding UBERCAL)
    16     unsigned int PHOTOM_FLAGS =
    17       ID_MEAS_NOCAL |          // detection ignored for this analysis (photcode, time range)
    18       ID_MEAS_POOR_PHOTOM |    // detection is photometry outlier
    19       ID_MEAS_SKIP_PHOTOM |    // detection was ignored for photometry measurement
    20       ID_MEAS_AREA |           // detetion was outside acceptable area of device
    21       ID_MEAS_SYNTH_MAG |      // magnitude is synthetic
    22       ID_MEAS_STACK_PRIMARY |  // this stack measurement is in the primary skycell
    23       ID_MEAS_STACK_PHOT_SRC;  // this measurement supplied the stack photometry
    24 
    25     // ID_MEAS_PHOTOM_UBERCAL -- externally-supplied zero point from ubercal analysis
    26     // this is set by 'setphot', do not reset here
    27 
    28     // flags used by the photometry analysis (excluding UBERCAL)
    29     // unsigned int secfiltFlags =
    30     //   ID_PHOTOM_PASS_0 | // average measured at pass 0
    31     //   ID_PHOTOM_PASS_1 | // average measured at pass 1
    32     //   ID_PHOTOM_PASS_2 | // average measured at pass 2
    33     //   ID_PHOTOM_PASS_3 | // average measured at pass 3
    34     //   ID_PHOTOM_PASS_4 | // average measured at pass 3
    35     //   ID_SECF_USE_SYNTH | // average measured at pass 3
    36     //   ID_SECF_USE_UBERCAL | // average measured at pass 3
    37     //   ID_SECF_OBJ_EXT; // average measured at pass 3
    38    
    39     // XXX I should really deprecate the concept of applying the average
    40     // calculation to a limited set of photcodes. 
    41     // for now, just do all photcodes here (
    42     // as it stands, only stacks are limited by photcode; mean exp and forced warp
    43     // are applied to all Nsecfilt
    44 
    45     for (i = 0; i < catalog[0].Naverage; i++) {
    46       int Ns;
    47       for (Ns = 0; Ns < Nsecfilt; Ns++) {
    48        
    49         off_t N = Nsecfilt*i+Ns;
    50         dvo_secfilt_init (&catalog[0].secfilt[N], SECFILT_RESET_ALL);
    51 
    52         off_t m = catalog[0].average[i].measureOffset;
    53         off_t j;
    54         for (j = 0; j < catalog[0].average[i].Nmeasure; j++, m++) {
    55        
    56           /* select measurements by time */
    57           if (TimeSelect) {
    58             if (catalog[0].measure[m].t < TSTART) continue;
    59             if (catalog[0].measure[m].t > TSTOP) continue;
    60           }
    61        
    62           // only reset Mcal for measures with a matching image
    63           // do not reset Mcal for ubercal images unless explicitly requested
    64 
    65           if (catalog[0].measure[m].dbFlags & ID_MEAS_PHOTOM_UBERCAL) {
    66             if (!KEEP_UBERCAL) {
    67               catalog[0].measure[m].McalPSF  = 0.0;
    68               catalog[0].measure[m].McalAPER = 0.0;
    69               catalog[0].measure[m].dbFlags &= ~ID_MEAS_PHOTOM_UBERCAL;
    70             }
    71           } else {
    72             if (RESET_ZEROPTS && (getImageEntry (m, 0) >= 0)) {
    73               catalog[0].measure[m].McalPSF  = 0.0;
    74               catalog[0].measure[m].McalAPER = 0.0;
    75             }
    76           }
    77           catalog[0].measure[m].dbFlags &= ~PHOTOM_FLAGS;
    78         }
    79       }
    80     }
    81   }
    82 
    83   // this sets flags in the measureT element, not the measure element
     13  ResetAverageAndMeasure (catalog);
     14 
     15  // This sets ID_MEAS flags in the measureT element, not the measure element
     16  // These bits are thus ephemeral and not saved. 
    8417  setExclusions (catalog, 1, VERBOSE);  /* mark by area */
    8518
     
    9225  }
    9326
    94   for (i = 0; i < catalog[0].Naverage; i++) {
    95     catalog[0].average[i].psfQF     = NAN;      // force recalculation below
    96     catalog[0].average[i].psfQFperf = NAN;      // force recalculation below
    97     catalog[0].average[i].stargal   = NAN;      // force recalculation below
    98     catalog[0].average[i].photFlagsUpper = 0;   // reset (will be re-calculated here)
    99     catalog[0].average[i].photFlagsLower = 0;   // reset (will be re-calculated here)
    100     catalog[0].average[i].NwarpOK        = 0;   // reset (will be re-calculated here)
    101   }
    102 
    103   // XXX make this optional? (do not clean for -averages?)
    104   // XXX : for the moment, disable clean_measures
    105   if (!simpleAverage && FALSE) clean_measures (catalog, 1, TRUE, flatcorr);    /* mark outliers ID_MEAS_POOR_PHOTOM */
    106 
    10727  ALLOCATE (catalog[0].measureRank, char, catalog[0].Nmeasure);
    10828  setMeasureRank (catalog);
    109   setMrelOutput (catalog, 1, flatcorr); // sets the values secfilt.MpsfChp = <measure.M + measure.Mflat - image.Mcal>
    110   setMcalOutput (catalog, 1, flatcorr); // sets measure.Mcal = image.Mcal
    11129
    112   /* clear ID_OBJ_POOR, ID_OBJ_FEW values before writing ??? */
    113   /* ID_MEAS_NOCAL is an internal bit, so it should be cleared */
    114   // XXX eventually: move these internal flags to an internal-only catalog->FOO element (like found)
    115   for (i = 0; i < catalog[0].Naverage; i++) {
    116     catalog[0].average[i].flags &= ~ID_OBJ_FEW;
    117     catalog[0].average[i].flags &= ~ID_OBJ_POOR;
    118     off_t j;
    119     for (j = 0; j < Nsecfilt; j++) {
    120         catalog[0].secfilt[i*Nsecfilt+j].flags &= ~ID_OBJ_FEW;
    121         catalog[0].secfilt[i*Nsecfilt+j].flags &= ~ID_OBJ_POOR;
    122     }
    123     off_t m = catalog[0].average[i].measureOffset;
    124     for (j = 0; j < catalog[0].average[i].Nmeasure; j++, m++) {
    125       catalog[0].measure[m].dbFlags &= ~ID_MEAS_NOCAL;
    126     }
    127   }
     30  setMflatFromGrid (catalog); // Mgrid is used to set Mflat; Mgrid is the ignored in setMrelOutput / setMrelCatalog
     31  setMrelOutput (catalog, 1); // sets the values secfilt.MpsfChp = <measure.M - image.Mcal - measure.Mflat>
     32  setMcalOutput (catalog, 1); // sets measure.Mcal = image.Mcal
    12833}
    129 
    130 /* ID_MEAS_SKIP marks measurements which were not used to calculate Mrel */
    131 // For each star & photcode, we are selecting the measurements to use in the average
    132 // photometry value.  This function is called several times, lowering the bar to
    133 // acceptance on each pass. The rejections at the different passes are:
    134 
    135 // 0 : only use measurements thought to be GOOD (photflags not POOR or BAD)
    136 // 1 : accept measurements thought to be POOR based on photflags
    137 // 2 : accept the measurements marked as outliers; accept images marked as outliers
    138 // 3 : accept measurements thought to be BAD based on photflags
    139 // 4 : accept the measurements outside of the instrumental magnitude limits (eg, SAT)
    140 
    141 // XXX if I'm reading this correctly, passes 0, 1, 2 are identical & accept all
    142 // non-outliers with Imag range
    14334
    14435// int print_measure_set (Average *average, SecFilt *secfilt, Measure *measure) {
     
    16152// }
    16253
    163 int print_measure_set (Average *average, SecFilt *secfilt, Measure *measure);
    164 
    165 void skip_measurements (Catalog *catalog, int pass, FlatCorrectionTable *flatcorr) {
    166 
    167   off_t i, k, m;
    168   off_t Ntot, Ntry, Nkeep, Nskip;
    169   float mag;
    170 
    171   int Nsecfilt = GetPhotcodeNsecfilt ();
    172 
    173   Ntot = Ntry = Nskip = Nkeep = 0;
    174 
    175   /* allow measures from images marked POOR and FEW */
    176   if (pass >= 3) IMAGE_BAD = ID_IMAGE_PHOTOM_NOCAL;
    177  
    178   /* allow measures marked as outliers (POOR) and off image region (AREA) */
    179   if (pass >= 3) {
    180     MEAS_BAD = ID_MEAS_NOCAL | ID_MEAS_SKIP_PHOTOM;
    181   } else {
    182     MEAS_BAD  = ID_MEAS_NOCAL | ID_MEAS_POOR_PHOTOM | ID_MEAS_SKIP_PHOTOM | ID_MEAS_AREA;
    183   }
    184 
    185   /* mark measures which should be ignored on this pass */
    186   for (i = 0; i < catalog[0].Naverage; i++) {
    187     Ntot += catalog[0].average[i].Nmeasure;
    188 
    189     if (FALSE && (catalog[0].average[i].objID == 0x46a4) && (catalog[0].average[i].catID == 0xf40e)) {
    190       fprintf (stderr, "test obj\n");
    191       print_measure_set (&catalog[0].average[i], &catalog[0].secfilt[i*Nsecfilt], catalog[0].measure);
    192     }
    193 
    194     // mark measurements for each secfilt separately
    195     int Ns;
    196     for (Ns = 0; Ns < Nphotcodes; Ns++) {
    197      
    198       int thisCode = photcodes[Ns][0].code;
    199       int Nsec = GetPhotcodeNsec(thisCode);
    200      
    201       /* star/photcodes already calibrated */
    202       if (catalog[0].found_t[Nsecfilt*i+Nsec]) continue; 
    203 
    204       m = catalog[0].average[i].measureOffset;
    205       for (k = 0; k < catalog[0].average[i].Nmeasure; k++, m++) {
    206         Ntry++;
    207 
    208         // skip measurements not related to this photcode
    209         PhotCode *code = GetPhotcodebyCode (catalog[0].measure[m].photcode);
    210         if (!code) continue;
    211         if (code->equiv != thisCode) continue;
    212 
    213         // skip measurements by time range (mark as skipped for this secfilt)
    214         // XXX note that this is a bit dangerous : some objects may never get calibrated
    215         if (TimeSelect) {
    216           if (catalog[0].measure[m].t < TSTART) goto skip;
    217           if (catalog[0].measure[m].t > TSTOP) goto skip;
    218         }
    219        
    220         // we now have a measurement relavant to this photcode (and time range)
    221 
    222         // clear SKIP for all measures at first
    223         catalog[0].measureT[m].dbFlags &= ~ID_MEAS_SKIP_PHOTOM;
    224         catalog[0].measure [m].dbFlags &= ~ID_MEAS_SKIP_PHOTOM;
    225 
    226         // skip measurements from BAD images and mosaics (not REF mags)
    227         // do NOT skip measurements without a matching image (REF mags)
    228         off_t Nim = getImageEntry (m, 0);
    229         if (Nim > -1) {
    230           if (isnan(getMcal (m, 0, MAG_CLASS_PSF))) goto skip;
    231           if (isnan(getMmos (m, 0))) goto skip;
    232         }
    233 
    234         // PASS 4 : skip measurements by inst mag limit (not REF mags)
    235         if ((pass < 4) && ImagSelect) {
    236           if (Nim > -1) {
    237             mag = PhotInst (&catalog[0].measure[m], MAG_CLASS_PSF);
    238             if (mag < ImagMin) goto skip;
    239             if (mag > ImagMax) goto skip;
    240           }
    241         }
    242 
    243         // PASS 3 : accept bad measurements (eg, SAT, CR), internal outliers
    244         if (pass < 3) {
    245           if (catalog[0].measure[m].photFlags & code->photomBadMask) goto skip;
    246           if ((catalog[0].measure[m].photcode > 10000) && (catalog[0].measure[m].photcode < 10500)) {
    247             if (catalog[0].measure[m].psfQF < 0.85) goto skip;
    248           }
    249         }
    250        
    251         // PASS 2 : (no additional cut)
    252 
    253         // PASS 1 : accept poor measurements as well (eg, POOR FIT, etc)
    254         if ((pass < 1) && (catalog[0].measure[m].photFlags & code->photomPoorMask)) goto skip;
    255 
    256         // PASS 0 : skip poor, outlier, bad measurements as well (eg, POOR FIT, etc)
    257 
    258         Nkeep ++;
    259        
    260         continue;
    261 
    262       skip:
    263         catalog[0].measure [m].dbFlags |= ID_MEAS_SKIP_PHOTOM;
    264         catalog[0].measureT[m].dbFlags |= ID_MEAS_SKIP_PHOTOM;
    265         Nskip ++;
    266       }
    267     }
    268   }
    269   if (VERBOSE) fprintf (stderr, "pass %d, Ntot: "OFF_T_FMT", Ntry: "OFF_T_FMT", Nskip: "OFF_T_FMT", Nkeep: "OFF_T_FMT"\n",
    270                         pass, Ntot, Ntry, Nskip, Nkeep);
    271 }
    272 
     54// This function is only called for the final output step.  By this point, we have
     55// propagated the mosaic and tgroup flags to each image.
    27356void setMeasureRank (Catalog *catalog) {
    27457
    27558  int i;
    27659
    277   // make these global
    278   int IMAGE_BAD  = ID_IMAGE_PHOTOM_NOCAL;
    279   int IMAGE_POOR = ID_IMAGE_PHOTOM_POOR | ID_IMAGE_PHOTOM_FEW | ID_IMAGE_PHOTOM_SKIP;
    280   int MEAS_BAD   = ID_MEAS_NOCAL        | ID_MEAS_SKIP_PHOTOM;
    281   int MEAS_POOR  = ID_MEAS_POOR_PHOTOM  | ID_MEAS_AREA;
    282 
    28360  Measure     *measure     = catalog[0].measure;
    284   MeasureTiny *measureT    = catalog[0].measureT;
    28561  char        *measureRank = catalog[0].measureRank;
    28662
     
    28965    measureRank[i] = 11; // start at a low rank
    29066
    291     // clear SKIP for all measures at first
    292     measureT[i].dbFlags &= ~ID_MEAS_SKIP_PHOTOM;
    293     measure [i].dbFlags &= ~ID_MEAS_SKIP_PHOTOM;
    294 
    295     // skip measurements without a valid photcode
     67    // measurements without a valid photcode have lowest rank (should not be used anyway)
    29668    PhotCode *code = GetPhotcodebyCode (measure[i].photcode);
    29769    if (!code) continue;
     
    29971    // measurements outside time range have poor rank
    30072    if (TimeSelect) {
    301       if (measure[i].t < TSTART)                     { measureRank[i] = 10; continue; }
    302       if (measure[i].t > TSTOP)                      { measureRank[i] = 10; continue; }
     73      if (measure[i].t < TSTART)                                        { measureRank[i] = 10; continue; }
     74      if (measure[i].t > TSTOP)                                         { measureRank[i] = 10; continue; }
    30375    }
    30476   
    305     // measurements from BAD images and mosaics (not REF mags)
    306     off_t Nim = getImageEntry (i, 0);
     77    // Nim < 0 for REF mags, imageFlags have bits for IMAGE, MOSAIC, NIGHT
     78    off_t Nim      = getImageEntry (i, 0);
    30779    int imageFlags = getImageFlags (i, 0);
    308     int mosaicFlags = getMosaicFlags (i, 0);
    30980
    31081    if (Nim > -1) {
    311       if (imageFlags  & IMAGE_BAD)                   { measureRank[i] = 9; continue; }
    312 
    313       if (mosaicFlags & IMAGE_BAD)                   { measureRank[i] = 9; continue; }
    314    
    31582      // measurements ranked by inst mag limit (not REF mags)
    31683      if (ImagSelect) {
    31784        float mag = PhotInst (&measure[i], MAG_CLASS_PSF);
    318         if (mag < ImagMin)                           { measureRank[i] = 8; continue; }
    319         if (mag > ImagMax)                           { measureRank[i] = 8; continue; }
     85        if (mag < ImagMin)                                              { measureRank[i] = 9; continue; }
     86        if (mag > ImagMax)                                              { measureRank[i] = 9; continue; }
    32087      }
    32188    }
    32289
    323     // RANK 1 : BAD photFlags
    324     if (measure[i].dbFlags & MEAS_BAD)               { measureRank[i] = 7; continue; }
    325 
    326     // RANK 3 : BAD photFlags (eg, SAT, CR), internal outliers
    327     if (measure[i].photFlags & code->photomBadMask)  { measureRank[i] = 6; continue; }
    328 
     90    // RANK 8 : Poor image
    32991    if (Nim > -1) {
    330       if (imageFlags  & IMAGE_POOR)                  { measureRank[i] = 5; continue; }
    331       if (mosaicFlags & IMAGE_POOR)                  { measureRank[i] = 5; continue; }
     92      if (imageFlags & ID_IMAGE_PHOTOM_POOR)                            { measureRank[i] = 8; continue; }
    33293    }
    33394
    334     // RANK 2 : psfQF value
    335     if (!isfinite(measure[i].psfQF) || measure[i].psfQF < 0.85) { measureRank[i] = 4; continue; }
     95    // RANK 7 : BAD photFlags (eg, SAT, CR), internal outliers
     96    if (measure[i].photFlags & code->photomBadMask)                     { measureRank[i] = 7; continue; }
     97
     98    // RANK 6 : bad psfQF value
     99    if (!isfinite(measure[i].psfQF) || measure[i].psfQF < 0.85)         { measureRank[i] = 6; continue; }
    336100       
    337     // RANK 1 : POOR photFlags
    338     if (measure[i].dbFlags & MEAS_POOR)              { measureRank[i] = 3; continue; }
     101    // RANK 5 : not in valid chip region
     102    if (measure[i].dbFlags & ID_MEAS_AREA)                              { measureRank[i] = 5; continue; }
    339103
    340     // RANK 1 : POOR photFlags
    341     if (measure[i].photFlags & code->photomPoorMask) { measureRank[i] = 2; continue; }
     104    // RANK 4 : POOR photFlags
     105    if (measure[i].photFlags & code->photomPoorMask)                    { measureRank[i] = 4; continue; }
    342106   
    343     // RANK 1 : psfQFperfect value
    344     if (!isfinite(measure[i].psfQFperf) || measure[i].psfQFperf < 0.85) { measureRank[i] = 1; continue; }
     107    // RANK 3 : bad psfQFperfect value
     108    if (!isfinite(measure[i].psfQFperf) || measure[i].psfQFperf < 0.85) { measureRank[i] = 3; continue; }
    345109       
     110    // RANK 2 : Poor mosaic
     111    if (Nim > -1) {
     112      if (imageFlags & ID_IMAGE_MOSAIC_POOR)                            { measureRank[i] = 2; continue; }
     113    }
     114
     115    // RANK 1 : Poor night
     116    if (Nim > -1) {
     117      if (imageFlags & ID_IMAGE_NIGHT_POOR)                             { measureRank[i] = 1; continue; }
     118    }
    346119    // RANK 0 : perfect measurement:
    347120    measureRank[i] = 0;
  • tags/ipp-ps1-20210510/Ohana/src/relphot/test

    • Property svn:ignore set to
      GSCregions.tbl
      dvo.photcodes
      ptolemy.rc
      tap.log
      tgroups.dat
      .dvo
      .mana
Note: See TracChangeset for help on using the changeset viewer.