IPP Software Navigation Tools IPP Links Communication Pan-STARRS Links

Changeset 33963 for trunk


Ignore:
Timestamp:
May 30, 2012, 1:46:12 PM (14 years ago)
Author:
eugene
Message:

merge changes from eam_branches/ipp-20120405

Location:
trunk
Files:
154 edited
21 copied

Legend:

Unmodified
Added
Removed
  • trunk

  • trunk/Ohana/src/addstar/Makefile

    r33719 r33963  
    2929mkcmf       : $(BIN)/mkcmf.$(ARCH)
    3030
    31 all: addstar sedstar load2mass skycells mkcmf loadwise loadsupercos dumpskycells
    32 
    33 INSTALL = addstar sedstar load2mass skycells mkcmf loadwise loadsupercos dumpskycells
     31all: addstar addstar_client sedstar load2mass skycells mkcmf loadwise loadsupercos dumpskycells
     32
     33INSTALL = addstar addstar_client sedstar load2mass skycells mkcmf loadwise loadsupercos dumpskycells
    3434
    3535# I need to fix the client/server version of addstar now that I have dropped Stars
     
    7878$(SRC)/resort_threaded.$(ARCH).o \
    7979$(SRC)/resort_unthreaded.$(ARCH).o \
     80$(SRC)/resort_unthreaded_catalogs.$(ARCH).o \
    8081$(SRC)/StarOps.$(ARCH).o \
    8182$(SRC)/ReadStarsFITS.$(ARCH).o \
     
    8990$(SRC)/update_coords.$(ARCH).o \
    9091$(SRC)/psps_ids.$(ARCH).o
     92
     93# this is the client for parallel operations
     94ADDSTAR_CLIENT = \
     95$(SRC)/ConfigInit.$(ARCH).o \
     96$(SRC)/SetSignals.$(ARCH).o \
     97$(SRC)/Shutdown.$(ARCH).o \
     98$(SRC)/SkyListForStars.$(ARCH).o \
     99$(SRC)/SkyRegionUtils.$(ARCH).o \
     100$(SRC)/build_links.$(ARCH).o \
     101$(SRC)/addstar_client.$(ARCH).o \
     102$(SRC)/args_parallel_client.$(ARCH).o \
     103$(SRC)/resort_catalog.$(ARCH).o \
     104$(SRC)/resort_threaded.$(ARCH).o \
     105$(SRC)/resort_unthreaded.$(ARCH).o \
     106$(SRC)/resort_unthreaded_catalogs.$(ARCH).o
    91107
    92108ADDSTARD = \
     
    168184$(SRC)/psps_ids.$(ARCH).o
    169185
     186# this is the client for server / client addstar operations
    170187ADDSTARC = \
    171188$(SRC)/addstarc.$(ARCH).o \
     
    220237LOAD-WISE = \
    221238$(SRC)/loadwise.$(ARCH).o \
    222 $(SRC)/loadwise_prelim_rawdata.$(ARCH).o \
     239$(SRC)/loadwise_rawdata.$(ARCH).o \
    223240$(SRC)/loadwise_ops.$(ARCH).o \
    224241$(SRC)/loadwise_star_full.$(ARCH).o \
     
    282299$(SRC)/SetSignals.$(ARCH).o \
    283300
    284 $(ADDSTARC)   : $(INC)/addstar.h
    285 $(ADDSTARD)   : $(INC)/addstar.h
    286 $(ADDSTART)   : $(INC)/addstar.h
    287 $(ADDSTAR)    : $(INC)/addstar.h
    288 $(SKYCELLS)   : $(INC)/addstar.h
    289 $(DUMPSKYCELLS): $(INC)/addstar.h
    290 $(LOAD-2MASS) : $(INC)/addstar.h $(INC)/2mass.h
    291 $(LOAD-WISE)  : $(INC)/addstar.h $(INC)/WISE.h
    292 $(MKCMF)      : $(INC)/mkcmf.h
    293 
    294 $(BIN)/addstar.$(ARCH)     : $(ADDSTAR)
    295 $(BIN)/addstard.$(ARCH)    : $(ADDSTARD)
    296 $(BIN)/addstart.$(ARCH)    : $(ADDSTART)
    297 $(BIN)/addstarc.$(ARCH)    : $(ADDSTARC)
    298 $(BIN)/mkacc-2mass.$(ARCH) : $(MKACC-2MASS)
    299 $(BIN)/sedstar.$(ARCH)     : $(SEDSTAR)
    300 $(BIN)/load2mass.$(ARCH)   : $(LOAD-2MASS)
    301 $(BIN)/loadwise.$(ARCH)    : $(LOAD-WISE)
    302 $(BIN)/loadsupercos.$(ARCH): $(LOAD-SUPERCOS)
    303 $(BIN)/skycells.$(ARCH)    : $(SKYCELLS)
    304 $(BIN)/dumpskycells.$(ARCH) : $(DUMPSKYCELLS)
    305 $(BIN)/mkcmf.$(ARCH)       : $(MKCMF)
     301$(ADDSTARC)       : $(INC)/addstar.h
     302$(ADDSTARD)       : $(INC)/addstar.h
     303$(ADDSTART)       : $(INC)/addstar.h
     304$(ADDSTAR)        : $(INC)/addstar.h
     305$(ADDSTAR_CLIENT) : $(INC)/addstar.h
     306$(SKYCELLS)       : $(INC)/addstar.h
     307$(DUMPSKYCELLS)   : $(INC)/addstar.h
     308$(LOAD-2MASS)     : $(INC)/addstar.h $(INC)/2mass.h
     309$(LOAD-WISE)      : $(INC)/addstar.h $(INC)/WISE.h
     310$(MKCMF)          : $(INC)/mkcmf.h
     311
     312$(BIN)/addstar.$(ARCH)        : $(ADDSTAR)
     313$(BIN)/addstar_client.$(ARCH) : $(ADDSTAR_CLIENT)
     314$(BIN)/addstard.$(ARCH)       : $(ADDSTARD)
     315$(BIN)/addstart.$(ARCH)       : $(ADDSTART)
     316$(BIN)/addstarc.$(ARCH)       : $(ADDSTARC)
     317$(BIN)/mkacc-2mass.$(ARCH)    : $(MKACC-2MASS)
     318$(BIN)/sedstar.$(ARCH)        : $(SEDSTAR)
     319$(BIN)/load2mass.$(ARCH)      : $(LOAD-2MASS)
     320$(BIN)/loadwise.$(ARCH)       : $(LOAD-WISE)
     321$(BIN)/loadsupercos.$(ARCH)   : $(LOAD-SUPERCOS)
     322$(BIN)/skycells.$(ARCH)       : $(SKYCELLS)
     323$(BIN)/dumpskycells.$(ARCH)   : $(DUMPSKYCELLS)
     324$(BIN)/mkcmf.$(ARCH)          : $(MKCMF)
    306325
    307326# I need to fix the client/server version of addstar now that I have dropped Stars
  • trunk/Ohana/src/addstar/include/WISE.h

    r33653 r33963  
    2121short WISE_W1, WISE_W2, WISE_W3, WISE_W4;
    2222
     23int ALLSKY;
     24
    2325AddstarClientOptions args_loadwise (int argc, char **argv, AddstarClientOptions options);
    2426
    25 int loadwise_prelim_rawdata (SkyList *skytable, char *filename, AddstarClientOptions options);
     27int loadwise_rawdata (SkyList *skytable, char *filename, AddstarClientOptions options, int ALLSKY);
    2628
    2729int getWISE_setup ();
     
    3133
    3234int getWISE_sortStars (WISE_Stars *tstars, int Ntstars);
    33 int loadwise_star_full (Stars **star, char *line, int Nmax);
     35
     36int loadwise_star_allsky (Stars **star, char *line, int Nmax);
     37int loadwise_star_prelim (Stars **star, char *line, int Nmax);
     38
    3439
    3540char *nextWISEfield (char *line);
  • trunk/Ohana/src/addstar/include/addstar.h

    r33653 r33963  
    5959typedef struct sockaddr_in SockAddress;
    6060
    61 enum {M_IMAGE, M_REFLIST, M_REFCAT, M_FAKEIMAGE, M_RESORT};
     61enum {ADDSTAR_MODE_NONE, ADDSTAR_MODE_IMAGE, ADDSTAR_MODE_REFLIST, ADDSTAR_MODE_REFCAT, ADDSTAR_MODE_FAKEIMAGE, ADDSTAR_MODE_RESORT};
    6262enum {NONE, SIMPLE_CMP, SIMPLE_CMF, SIMPLE_MEF, MOSAIC_CMP, MOSAIC_CMF, MOSAIC_MEF, MOSAIC_PHU, SDSS_OBJ};
    6363/* note: MEF implies CMF */
    6464
    6565/* globals which define database info / data sources (KEEP) */
    66 char   ImageCat[256];
     66char   ImageCat[DVO_MAX_PATH];
    6767char   GSCFILE[256];
    68 char   CATDIR[256];
     68char  *CATDIR;
    6969char   CATMODE[16];    /* raw, mef, split, mysql */
    7070char   CATFORMAT[16];  /* internal, elixir, loneos, panstarrs */
     
    132132int     OLD_RESORT;
    133133
     134int    PARALLEL;
     135int    PARALLEL_MANUAL;
     136int    PARALLEL_SERIAL;
     137int    HOST_ID;
     138char  *HOSTDIR;
     139
    134140// carries the mosaic into gstars
    135141
     
    160166/*** addstar prototypes ***/
    161167
    162 AddstarClientOptions ConfigInit   PROTO((int *argc, char **argv));
    163 AddstarClientOptions args         PROTO((int argc, char **argv, AddstarClientOptions options));
     168AddstarClientOptions ConfigInit           PROTO((int *argc, char **argv));
     169AddstarClientOptions args                 PROTO((int argc, char **argv, AddstarClientOptions options));
     170AddstarClientOptions args_parallel_client PROTO((int argc, char **argv, AddstarClientOptions options));
    164171
    165172void       AddToCalibration       PROTO((Average *average, SecFilt *secfilt, Measure *measure, Measure *new, off_t *next, off_t Nstar));
     
    216223int        replace_match          PROTO((Average *average, Measure *measure, Stars *star));
    217224int        resort_threaded        PROTO((AddstarClientOptions *options, SkyTable *sky));
    218 int        resort_unthreaded      PROTO((AddstarClientOptions *options, SkyTable *sky));
     225int        resort_unthreaded      PROTO((AddstarClientOptions *options, SkyTable *sky, int hostID, char *hostpath));
     226int        resort_unthreaded_catalogs PROTO((AddstarClientOptions *options, SkyList *skylist, int hostID, char *hostpath));
    219227void       resort_catalog         PROTO((Catalog *catalog));
    220228void       resort_catalog_old     PROTO((Catalog *catalog));
  • trunk/Ohana/src/addstar/src/ConfigInit.c

    r33653 r33963  
    125125  ScanConfig (config, "TYCHO_DIR",              "%s",  0, TYCHO_DIR);
    126126
     127  // force CATDIR to be absolute (so parallel mode will work)
     128  char tmpcatdir[DVO_MAX_PATH];
     129  GetConfig (config, "CATDIR" ,                 "%s",  0, tmpcatdir);
     130  CATDIR = abspath (tmpcatdir, DVO_MAX_PATH);
     131
    127132  GetConfig (config, "GSCFILE",                 "%s",  0, GSCFILE);
    128   GetConfig (config, "CATDIR",                  "%s",  0, CATDIR);
    129133  GetConfig (config, "PHOTCODE_FILE",           "%s",  0, MasterPhotcodeFile);
    130134  ScanConfig (config, "CATMODE",                "%s",  0, CATMODE);
  • trunk/Ohana/src/addstar/src/addstar.c

    r29938 r33963  
    3434  SkyTableSetFilenames (sky, CATDIR, "cpt");
    3535 
    36   if (options.mode == M_RESORT) {
     36  if (options.mode == ADDSTAR_MODE_RESORT) {
    3737    if (NTHREADS == 0) {
    38       resort_unthreaded (&options, sky);
     38      resort_unthreaded (&options, sky, 0, NULL);
    3939    } else {
    4040      resort_threaded (&options, sky);
     
    4747  /*** load in the new data (images, stars) ***/
    4848  switch (options.mode) {
    49     case M_IMAGE:
     49    case ADDSTAR_MODE_IMAGE:
    5050      stars = LoadStars (argv[1], &Nstars, &images, &Nimages, &options);
    5151
     
    6262      ImageOptions (&options, images, Nimages);
    6363      break;
    64     case M_REFLIST:
     64    case ADDSTAR_MODE_REFLIST:
    6565      stars = grefstars (argv[1], options.photcode, &Nstars);
    6666      skylist = SkyListForStars (sky, -1, stars, Nstars);
    6767      break;
    68     case M_RESORT:
    69     case M_REFCAT:
     68    case ADDSTAR_MODE_RESORT:
     69    case ADDSTAR_MODE_REFCAT:
    7070      skylist = SkyListByPatch (sky, -1, &UserPatch);
    7171      break;
    72     case M_FAKEIMAGE:
     72    case ADDSTAR_MODE_FAKEIMAGE:
    7373      images = fakeimage (argv[1], &Nimages, options.photcode);
    7474      ALLOCATE (skylist, SkyList, 1);
     
    137137
    138138    switch (options.mode) {
    139       case M_IMAGE:
     139      case ADDSTAR_MODE_IMAGE:
    140140        Nsubset = Nstars;
    141141        if (options.closest) {
     
    145145        }
    146146        break;
    147       case M_REFCAT:
     147      case ADDSTAR_MODE_REFCAT:
    148148        stars = greference (argv[1], skylist[0].regions[i], options.photcode, &Nstars);
    149       case M_REFLIST:
     149      case ADDSTAR_MODE_REFLIST:
    150150        subset = find_subset (skylist[0].regions[i], stars, Nstars, &Nsubset);
    151151        if (options.closest) {
     
    156156        if (Nsubset) free (subset);
    157157        break;
    158       case M_RESORT:
     158      case ADDSTAR_MODE_RESORT:
    159159        if (options.nosort == 3) catalog.sorted = FALSE;
    160160
     
    192192    dvo_catalog_free (&catalog);
    193193
    194     if (options.mode == M_REFCAT) free (stars);
     194    if (options.mode == ADDSTAR_MODE_REFCAT) free (stars);
    195195  }
    196196
     
    216216
    217217  /* add the new images and save */
    218   if (options.mode == M_IMAGE) {
     218  if (options.mode == ADDSTAR_MODE_IMAGE) {
    219219    dvo_image_addrows (&db, images, Nimages);
    220220    SetProtect (TRUE);
  • trunk/Ohana/src/addstar/src/addstarc.c

    r21153 r33963  
    2020  /* send new data to server */
    2121  switch (options.mode) {
    22     case M_IMAGE:
     22    case ADDSTAR_MODE_IMAGE:
    2323      /* load data */
    2424      stars = LoadStars (argv[1], &Nstars, &images, &Nimages, &options);
     
    4040      break;
    4141
    42     case M_REFLIST:
     42    case ADDSTAR_MODE_REFLIST:
    4343      /* load data */
    4444      stars = grefstars (argv[1], options.photcode, &Nstars);
     
    5050      break;
    5151
    52     case M_REFCAT:
     52    case ADDSTAR_MODE_REFCAT:
    5353      /* send data to server */
    5454      SendCommand (BindSocket, 5, "REFCT");
  • trunk/Ohana/src/addstar/src/addstart.c

    r25757 r33963  
    3131
    3232    switch (dataset[0].options[0].mode) {
    33       case M_IMAGE:
     33      case ADDSTAR_MODE_IMAGE:
    3434        UpdateDatabase_Image (dataset[0].options, dataset[0].images, dataset[0].Nimages, dataset[0].mosaic, dataset[0].stars, dataset[0].Nstars);
    3535        continue;
    3636
    37       case M_REFLIST:
     37      case ADDSTAR_MODE_REFLIST:
    3838        UpdateDatabase_Reflist (dataset[0].options, dataset[0].stars, dataset[0].Nstars);
    3939        continue;
    4040
    41       case M_REFCAT:
     41      case ADDSTAR_MODE_REFCAT:
    4242        UpdateDatabase_Refcat (dataset[0].options, dataset[0].patch, dataset[0].refcat);
    4343        continue;
  • trunk/Ohana/src/addstar/src/args.c

    r31669 r33963  
    2121
    2222  /* basic mode: image, list, refcat */
    23   options.mode = M_IMAGE;
     23  options.mode = ADDSTAR_MODE_IMAGE;
    2424  if ((N = get_argument (argc, argv, "-ref"))) {
    25     options.mode = M_REFLIST;
     25    options.mode = ADDSTAR_MODE_REFLIST;
    2626    remove_argument (N, &argc, argv);
    2727  }
    2828  if ((N = get_argument (argc, argv, "-cat"))) {
    29     options.mode = M_REFCAT;
     29    options.mode = ADDSTAR_MODE_REFCAT;
    3030    remove_argument (N, &argc, argv);
    3131  }
    3232  if ((N = get_argument (argc, argv, "-resort"))) {
    33     options.mode = M_RESORT;
     33    options.mode = ADDSTAR_MODE_RESORT;
    3434    remove_argument (N, &argc, argv);
    3535  }
    3636
    3737  if ((N = get_argument (argc, argv, "-fakeimage"))) {
    38     options.mode = M_FAKEIMAGE;
     38    options.mode = ADDSTAR_MODE_FAKEIMAGE;
    3939    remove_argument (N, &argc, argv);
    4040    FAKE_RA = atof (argv[N]);
     
    9898    remove_argument (N, &argc, argv);
    9999  } else {
    100       if (options.mode == M_IMAGE) goto allow;
    101       if (options.mode == M_FAKEIMAGE) goto allow;
    102       if (options.mode == M_REFLIST) goto allow;
    103       if (options.mode == M_REFCAT) {
     100      if (options.mode == ADDSTAR_MODE_IMAGE) goto allow;
     101      if (options.mode == ADDSTAR_MODE_FAKEIMAGE) goto allow;
     102      if (options.mode == ADDSTAR_MODE_REFLIST) goto allow;
     103      if (options.mode == ADDSTAR_MODE_REFCAT) {
    104104          fprintf (stderr, "you have requested uploading from a catalog to the entire sky in one pass\n");
    105105      }
    106       if (options.mode == M_RESORT) {
     106      if (options.mode == ADDSTAR_MODE_RESORT) {
    107107          fprintf (stderr, "you have requested resorting the entire sky in one pass\n");
    108108      }
     
    330330  }
    331331
    332   if ((options.mode == M_RESORT) && (argc == 1)) return (options);
     332  // XXX for the moment, make this selection manual.  it needs to be automatic
     333  // based on the state of the SkyTable
     334  PARALLEL = FALSE;
     335  if ((N = get_argument (argc, argv, "-parallel"))) {
     336    PARALLEL = TRUE;
     337    remove_argument (N, &argc, argv);
     338  }
     339  // this is a test mode : rather than launching the remote jobs and waiting for completion,
     340  // relphot will simply list the remote command and wait for the user to signal completion
     341  PARALLEL_MANUAL = FALSE;
     342  if ((N = get_argument (argc, argv, "-parallel-manual"))) {
     343    PARALLEL = TRUE; // -parallel-manual implies -parallel
     344    PARALLEL_MANUAL = TRUE;
     345    remove_argument (N, &argc, argv);
     346  }
     347  // this is a test mode : rather than launching the relphot_client jobs remotely, they are
     348  // run in serial via 'system'
     349  PARALLEL_SERIAL = FALSE;
     350  if ((N = get_argument (argc, argv, "-parallel-serial"))) {
     351    if (PARALLEL_MANUAL) {
     352      fprintf (stderr, "ERROR: cannot mix -parallel-manual and -parallel-serial\n");
     353      exit (1);
     354    }
     355    PARALLEL = TRUE; // -parallel-serial implies -parallel
     356    PARALLEL_SERIAL = TRUE;
     357    remove_argument (N, &argc, argv);
     358  }
     359  if (PARALLEL) {
     360    if (options.mode != ADDSTAR_MODE_RESORT) {
     361      fprintf (stderr, "parallel mode is only valid for -resort mode\n");
     362      exit (2);
     363    }
     364  }
     365
     366  if ((options.mode == ADDSTAR_MODE_RESORT) && (argc == 1)) return (options);
    333367  if (argc == 2) return (options);
    334368
    335   if ((options.mode == M_REFLIST) && (options.photcode == 0)) {
     369  if ((options.mode == ADDSTAR_MODE_REFLIST) && (options.photcode == 0)) {
    336370    fprintf (stderr, "photcode must be specified for -ref\n");
    337371    exit (2);
  • trunk/Ohana/src/addstar/src/args_client.c

    r18374 r33963  
    1818
    1919  /* basic mode: image, list, refcat */
    20   options.mode = M_IMAGE;
     20  options.mode = ADDSTAR_MODE_IMAGE;
    2121  if ((N = get_argument (argc, argv, "-ref"))) {
    22     options.mode = M_REFLIST;
     22    options.mode = ADDSTAR_MODE_REFLIST;
    2323    remove_argument (N, &argc, argv);
    2424  }
    2525  if ((N = get_argument (argc, argv, "-cat"))) {
    26     options.mode = M_REFCAT;
     26    options.mode = ADDSTAR_MODE_REFCAT;
    2727    remove_argument (N, &argc, argv);
    2828  }
  • trunk/Ohana/src/addstar/src/args_load2mass.c

    r24977 r33963  
    1818
    1919  /* basic mode: image, list, refcat */
    20   options.mode = M_REFCAT;
     20  options.mode = ADDSTAR_MODE_REFCAT;
    2121
    2222  /*** provide additional data ***/
  • trunk/Ohana/src/addstar/src/args_loadsupercos.c

    r33653 r33963  
    1818
    1919  /* basic mode: image, list, refcat */
    20   options.mode = M_REFCAT;
     20  options.mode = ADDSTAR_MODE_REFCAT;
    2121
    2222  /* we do not allow a subset to be extracted -- all or nothing, babe */
  • trunk/Ohana/src/addstar/src/args_loadwise.c

    r33653 r33963  
    11# include "addstar.h"
     2# include "WISE.h"
    23static void help (void);
    34
     
    1213  }
    1314
    14   // a global used by find_matches_refstars.c (value is 1 except for load2mass & loadwise)
     15  // a global used by find_matches_refstars.c (value is 1 except for loadwise & loadwise)
    1516  NREFSTAR_GROUP = 4;
    1617
     
    1819
    1920  /* basic mode: image, list, refcat */
    20   options.mode = M_REFCAT;
     21  options.mode = ADDSTAR_MODE_REFCAT;
    2122
    2223  /* we do not allow a subset to be extracted -- all or nothing, babe */
     
    5253  }
    5354
    54   /* other addstar options which cannot be used in load2mass */
     55  /* load the prelim data dump */
     56  ALLSKY = TRUE;
     57  if ((N = get_argument (argc, argv, "-prelim"))) {
     58    ALLSKY = FALSE;
     59    remove_argument (N, &argc, argv);
     60  }
     61
     62  /* other addstar options which cannot be used in loadwise */
    5563  options.photcode = 0;
    5664  options.timeref = 0;
     
    7078
    7179  if (argc < 2) {
    72     fprintf (stderr, "USAGE: load2mass [options] (wisefile) [..more files]\n");
     80    fprintf (stderr, "USAGE: loadwise [options] (wisefile) [..more files]\n");
    7381    exit (2);
    7482  }
  • trunk/Ohana/src/addstar/src/args_sedstar.c

    r18374 r33963  
    1818
    1919  /* basic mode: image, list, refcat */
    20   options.mode = M_REFCAT;
     20  options.mode = ADDSTAR_MODE_REFCAT;
    2121
    2222  /*** provide additional data ***/
  • trunk/Ohana/src/addstar/src/find_matches.c

    r33653 r33963  
    294294      catalog[0].secfilt[Nave*Nsecfilt+j].Map         = NAN;
    295295      catalog[0].secfilt[Nave*Nsecfilt+j].dM          = NAN;
     296      catalog[0].secfilt[Nave*Nsecfilt+j].Mstdev      = NAN_S_SHORT;
    296297      catalog[0].secfilt[Nave*Nsecfilt+j].Xm          = NAN_S_SHORT;
    297298      catalog[0].secfilt[Nave*Nsecfilt+j].M_20        = NAN_S_SHORT;
     
    301302      catalog[0].secfilt[Nave*Nsecfilt+j].ubercalDist = 1000;
    302303      catalog[0].secfilt[Nave*Nsecfilt+j].flags       = 0;
    303       catalog[0].secfilt[Nave*Nsecfilt+j].dummy[0]    = 0;
    304       catalog[0].secfilt[Nave*Nsecfilt+j].dummy[1]    = 0;
    305304    }
    306305
  • trunk/Ohana/src/addstar/src/find_matches_closest.c

    r33653 r33963  
    295295      catalog[0].secfilt[Nave*Nsecfilt+j].Map         = NAN;
    296296      catalog[0].secfilt[Nave*Nsecfilt+j].dM          = NAN;
     297      catalog[0].secfilt[Nave*Nsecfilt+j].Mstdev      = NAN_S_SHORT;
    297298      catalog[0].secfilt[Nave*Nsecfilt+j].Xm          = NAN_S_SHORT;
    298299      catalog[0].secfilt[Nave*Nsecfilt+j].M_20        = NAN_S_SHORT;
     
    302303      catalog[0].secfilt[Nave*Nsecfilt+j].ubercalDist = 1000;
    303304      catalog[0].secfilt[Nave*Nsecfilt+j].flags       = 0;
    304       catalog[0].secfilt[Nave*Nsecfilt+j].dummy[0]    = 0;
    305       catalog[0].secfilt[Nave*Nsecfilt+j].dummy[1]    = 0;
    306305    }
    307306
  • trunk/Ohana/src/addstar/src/loadwise.c

    r33653 r33963  
    4040  for (i = 1; i < argc; i++) {
    4141      fprintf (stderr, "loading %s\n", argv[i]);
    42       loadwise_prelim_rawdata (skylist, argv[i], options);
     42      loadwise_rawdata (skylist, argv[i], options, ALLSKY);
    4343  }
    4444  exit (0);
  • trunk/Ohana/src/addstar/src/loadwise_star_full.c

    r33653 r33963  
    33
    44int setWISE_ph_qual (Stars *star, char qual);
    5 int setWISE_var_flag (Stars *star, char qual);
    6 int setWISE_ext_flag (Stars **star, char *ptr);
     5int setWISE_var_flag_allsky (Stars *star, char qual);
     6int setWISE_ext_flag_allsky (Stars **star, char ptr);
     7int setWISE_var_flag_prelim (Stars *star, char qual);
     8int setWISE_ext_flag_prelim (Stars **star, char ptr);
    79int setWISE_cc_flag (Stars *star, char qual);
    810int setWISE_sat_flag (Stars *star, char *ptr);
    911int setWISE_blend_flag (Stars **star, char *ptr);
    1012
     13// there are slight format differences between the prelim data dump and the allsky data dump:
     14// * after ph_qual & det_bit : new field moon_lev
     15// * for each filter, after w?sigp2 : new fields w?dmag, w?ndf, w?mlq, w?mjdmin, w?mjdmax, w?mjdmean
     16// * after w4mdjmean : new fields rho12, rho23, rho34, q12, q23, q34
     17// * after k_msig_2mass : new fields best_use_cntr, ngrp
     18
    1119// fill in the data for a WISE quad star.  takes a pointer to the start of the line the
    1220// RA and DEC have already been set
    13 int loadwise_star_full (Stars **star, char *line, int Nmax) {
     21int loadwise_star_allsky (Stars **star, char *line, int Nmax) {
    1422
    1523  int i;
     
    5260  // W1
    5361  for (i = 0; i < 4; i++) {
    54       star[0][0].measure.M  = strtod (ptr, NULL); // w?mpro
     62    char *endpoint;
     63      star[i][0].measure.M  = strtod (ptr, &endpoint); // w?mpro
     64      if (endpoint == ptr) {
     65        star[i][0].measure.M  = NAN;
     66      }
    5567      ptr = nextWISEfield (ptr);
    56       star[0][0].measure.dM = strtod (ptr, NULL); // w?sigmpro
     68      star[i][0].measure.dM = strtod (ptr, &endpoint); // w?sigmpro
     69      if (endpoint == ptr) {
     70        star[i][0].measure.dM  = NAN;
     71      }
    5772      ptr = skipNbounds (ptr, '|', 2, Nmax); // skip: w?sigmpro, w?snr
    58       star[0][0].measure.psfChisq = strtod (ptr, NULL); // w?rchi2
     73      star[i][0].measure.psfChisq = strtod (ptr, NULL); // w?rchi2
    5974      ptr = nextWISEfield (ptr); // skip : w1rchi2
    6075
     
    8196
    8297  // set ext flags for all 4 measures
    83   setWISE_ext_flag (star, ptr); // ext_flg
     98  setWISE_ext_flag_allsky (star, ptr[0]); // ext_flg
    8499  ptr = nextWISEfield (ptr); // skip ext_flags
    85100
    86101  for (i = 0; i < 4; i++) {
    87       setWISE_var_flag (star[i], ptr[i]); // var_flg
     102      setWISE_var_flag_allsky (star[i], ptr[i]); // var_flg
     103  }
     104  ptr = nextWISEfield (ptr); // skip var_flags
     105
     106  for (i = 0; i < 4; i++) {
     107      setWISE_ph_qual (star[i], ptr[i]); // ph_qual
     108  }
     109
     110  ptr = skipNbounds (ptr, '|', 159, Nmax); // skip: det_bit, moon_lev, w?nm, w?m, w?cov, etc, etc.
     111
     112  for (i = 0; i < 4; i++) {
     113    ptr = skipNbounds (ptr, '|', 8, Nmax); // skip: det_bit, moon_lev, w?nm, w?m, w?cov, etc, etc.
     114
     115    // double mjdmin = strtod (ptr, NULL); // mjd min
     116    // ptr = nextWISEfield (ptr); // skip
     117    // double mjdmax = strtod (ptr, NULL); // mjd max
     118    // ptr = nextWISEfield (ptr); // skip mjd max
     119    double mjdmean = strtod (ptr, NULL); // mjd mean
     120    ptr = nextWISEfield (ptr); // skip mjd mean
     121
     122    // fprintf (stderr, "w%d mjd: %f\n", i, mjdmean);
     123
     124    // the release is based on data taken in the period 14 January 2010 to 29 April 2010
     125    if (mjdmean == 0.0) {
     126      star[i][0].measure.t = 0;
     127    } else {
     128      star[i][0].measure.t = ohana_mjd_to_sec (mjdmean);
     129    }
     130  }
     131
     132  star[0][0].measure.photcode  = WISE_W1;
     133  star[0][0].measure.detID   = 0;
     134  star[0][0].measure.imageID = 0;
     135
     136  star[1][0].measure.photcode  = WISE_W2;
     137  star[1][0].measure.detID   = 0;
     138  star[1][0].measure.imageID = 0;
     139
     140  star[2][0].measure.photcode  = WISE_W3;
     141  star[2][0].measure.detID   = 0;
     142  star[2][0].measure.imageID = 0;
     143
     144  star[3][0].measure.photcode  = WISE_W4;
     145  star[3][0].measure.detID   = 0;
     146  star[3][0].measure.imageID = 0;
     147
     148  return TRUE;
     149}
     150
     151// fill in the data for a WISE quad star.  takes a pointer to the start of the line the
     152// RA and DEC have already been set
     153int loadwise_star_prelim (Stars **star, char *line, int Nmax) {
     154
     155  int i;
     156  char *ptr;
     157
     158  if (line == NULL) Shutdown ("format error in WISE");
     159
     160  ptr = line;
     161
     162  // I can assign dRA and dDEC to dX and dY if I can consistently set posangle and pltscale
     163  star[0][0].measure.posangle = 0.0;
     164  star[0][0].measure.pltscale = 1.0;
     165
     166  ptr = skipNbounds (ptr, '|', 3, Nmax); // skip: desig, ra, dec,
     167  star[0][0].measure.dXccd = ToShortPixels(strtod (ptr, NULL)); // sig_ra
     168  ptr = nextWISEfield (ptr);
     169  star[0][0].measure.dYccd = ToShortPixels(strtod (ptr, NULL)); // sig_dec
     170  ptr = nextWISEfield (ptr);
     171
     172  // we only know a single set of values for all 4 bands
     173  for (i = 1; i < 4; i++) {
     174      star[i][0].measure.dXccd    = star[0][0].measure.dXccd;
     175      star[i][0].measure.dYccd    = star[0][0].measure.dYccd;
     176      star[i][0].measure.posangle = star[0][0].measure.posangle;
     177      star[i][0].measure.pltscale = star[0][0].measure.pltscale;
     178  }
     179  ptr = skipNbounds (ptr, '|', 5, Nmax); // skip: sig_radec, glon, glat, elon, elat
     180
     181  star[0][0].measure.Xccd = strtod (ptr, NULL); // wx
     182  ptr = nextWISEfield (ptr); // skip wx
     183  star[0][0].measure.Yccd = strtod (ptr, NULL); // wy
     184  ptr = nextWISEfield (ptr); // skip wy
     185
     186  for (i = 1; i < 4; i++) {
     187      star[i][0].measure.Xccd    = star[0][0].measure.Xccd;
     188      star[i][0].measure.Yccd    = star[0][0].measure.Yccd;
     189  }
     190  ptr = skipNbounds (ptr, '|', 4, Nmax); // skip: cntr, source_id, coadd_id, src
     191
     192  // W1
     193  for (i = 0; i < 4; i++) {
     194      star[i][0].measure.M  = strtod (ptr, NULL); // w?mpro
     195      ptr = nextWISEfield (ptr);
     196      star[i][0].measure.dM = strtod (ptr, NULL); // w?sigmpro
     197      ptr = skipNbounds (ptr, '|', 2, Nmax); // skip: w?sigmpro, w?snr
     198      star[i][0].measure.psfChisq = strtod (ptr, NULL); // w?rchi2
     199      ptr = nextWISEfield (ptr); // skip : w1rchi2
     200
     201      // init the photFlags field
     202      star[i][0].measure.photFlags = 0;
     203  }
     204
     205  ptr = nextWISEfield (ptr); // skip: rchi2
     206
     207  // set blend flags for all 4 measures
     208  setWISE_blend_flag (star, ptr); // nb & na both used here
     209  ptr = skipNbounds (ptr, '|', 2, Nmax); // skip: nb, na
     210
     211  for (i = 0; i < 4; i++) {
     212      setWISE_sat_flag (star[i], ptr); // w1sat
     213      ptr = nextWISEfield (ptr);
     214  }
     215  ptr = nextWISEfield (ptr); // skip satnum
     216
     217  for (i = 0; i < 4; i++) {
     218      setWISE_cc_flag (star[i], ptr[i]); // cc_flg
     219  }
     220  ptr = nextWISEfield (ptr); // skip cc_flags
     221
     222  // set ext flags for all 4 measures
     223  setWISE_ext_flag_prelim (star, *ptr); // ext_flg
     224  ptr = nextWISEfield (ptr); // skip ext_flags
     225
     226  for (i = 0; i < 4; i++) {
     227      setWISE_var_flag_prelim (star[i], ptr[i]); // var_flg
    88228  }
    89229  ptr = nextWISEfield (ptr); // skip var_flags
     
    150290
    151291# define FLAG_EXTENDED        0x01000000 // ext == 1
     292# define FLAG_EXT_IN_XSC      0x02000000 // ext == 1
     293# define FLAG_EXT_BY_XSC      0x04000000 // ext == 1
    152294
    153295# define FLAG_VARIABLE_LEVEL1 0x10000000 // var_flg == 1 to 4
     
    201343    case '0': break;
    202344    default:
    203       fprintf (stderr, "error!\n");
    204       exit (2);
     345      fprintf (stderr, "error in cc_flag: %c\n", qual);
    205346  }     
    206347  return (TRUE);
    207348}
    208349
    209 int setWISE_ext_flag (Stars **star, char *ptr) {
    210 
    211     int ext = atoi (ptr);
    212     if (ext == 1) {
    213         star[0][0].measure.photFlags |= FLAG_EXTENDED;
    214         star[1][0].measure.photFlags |= FLAG_EXTENDED;
    215         star[2][0].measure.photFlags |= FLAG_EXTENDED;
    216         star[3][0].measure.photFlags |= FLAG_EXTENDED;
    217     }
    218     return TRUE;
    219 }
    220 
    221 int setWISE_var_flag (Stars *star, char qual) {
    222 
    223     int value = qual - '0';
    224     assert (value >= 0);
    225     assert (value <= 9);
    226     if (value == 0) return TRUE;
    227     if (value < 5) {
     350int setWISE_ext_flag_allsky (Stars **star, char value) {
     351
     352  switch (value) {
     353    case '0':
     354      return TRUE;
     355    case '1':
     356      star[0][0].measure.photFlags |= FLAG_EXTENDED;
     357      star[1][0].measure.photFlags |= FLAG_EXTENDED;
     358      star[2][0].measure.photFlags |= FLAG_EXTENDED;
     359      star[3][0].measure.photFlags |= FLAG_EXTENDED;
     360      return TRUE;
     361    case '2':
     362      star[0][0].measure.photFlags |= FLAG_EXT_IN_XSC;
     363      star[1][0].measure.photFlags |= FLAG_EXT_IN_XSC;
     364      star[2][0].measure.photFlags |= FLAG_EXT_IN_XSC;
     365      star[3][0].measure.photFlags |= FLAG_EXT_IN_XSC;
     366      return TRUE;
     367    case '3':
     368      star[0][0].measure.photFlags |= FLAG_EXTENDED | FLAG_EXT_IN_XSC;
     369      star[1][0].measure.photFlags |= FLAG_EXTENDED | FLAG_EXT_IN_XSC;
     370      star[2][0].measure.photFlags |= FLAG_EXTENDED | FLAG_EXT_IN_XSC;
     371      star[3][0].measure.photFlags |= FLAG_EXTENDED | FLAG_EXT_IN_XSC;
     372      return TRUE;
     373    case '4':
     374      star[0][0].measure.photFlags |= FLAG_EXT_BY_XSC;
     375      star[1][0].measure.photFlags |= FLAG_EXT_BY_XSC;
     376      star[2][0].measure.photFlags |= FLAG_EXT_BY_XSC;
     377      star[3][0].measure.photFlags |= FLAG_EXT_BY_XSC;
     378      return TRUE;
     379    case '5':
     380      star[0][0].measure.photFlags |= FLAG_EXTENDED | FLAG_EXT_BY_XSC;
     381      star[1][0].measure.photFlags |= FLAG_EXTENDED | FLAG_EXT_BY_XSC;
     382      star[2][0].measure.photFlags |= FLAG_EXTENDED | FLAG_EXT_BY_XSC;
     383      star[3][0].measure.photFlags |= FLAG_EXTENDED | FLAG_EXT_BY_XSC;
     384      return TRUE;
     385    default:
     386      fprintf (stderr, "programming error\n");
     387      abort();
     388  }
     389  return TRUE;
     390}
     391
     392int setWISE_ext_flag_prelim (Stars **star, char value) {
     393
     394  switch (value) {
     395    case '0':
     396      return TRUE;
     397    case '1':
     398      star[0][0].measure.photFlags |= FLAG_EXTENDED;
     399      star[1][0].measure.photFlags |= FLAG_EXTENDED;
     400      star[2][0].measure.photFlags |= FLAG_EXTENDED;
     401      star[3][0].measure.photFlags |= FLAG_EXTENDED;
     402      return TRUE;
     403    default:
     404      fprintf (stderr, "programming error\n");
     405      abort();
     406  }
     407  return TRUE;
     408}
     409
     410// NOTE: var flag definition changed slightly between prelim & allsky
     411int setWISE_var_flag_allsky (Stars *star, char qual) {
     412
     413  switch (qual) {
     414    case 'n':
     415        return TRUE;
     416    case '0':
     417    case '1':
     418    case '2':
     419    case '3':
     420    case '4':
     421    case '5':
    228422        star[0].measure.photFlags |= FLAG_VARIABLE_LEVEL1;
    229423        return TRUE;
    230     }
    231     if (value < 8) {
     424    case '6':
     425    case '7':
    232426        star[0].measure.photFlags |= FLAG_VARIABLE_LEVEL2;
    233427        return TRUE;
    234     }
    235     star[0].measure.photFlags |= FLAG_VARIABLE_LEVEL3;
    236     return TRUE;
     428    case '8':
     429    case '9':
     430      star[0].measure.photFlags |= FLAG_VARIABLE_LEVEL3;
     431      return TRUE;
     432    default:
     433      fprintf (stderr, "programming error\n");
     434      abort();
     435  }
     436}
     437
     438int setWISE_var_flag_prelim (Stars *star, char qual) {
     439
     440  switch (qual) {
     441    case '0':
     442      return TRUE;
     443    case '1':
     444    case '2':
     445    case '3':
     446    case '4':
     447        star[0].measure.photFlags |= FLAG_VARIABLE_LEVEL1;
     448        return TRUE;
     449    case '5':
     450    case '6':
     451    case '7':
     452        star[0].measure.photFlags |= FLAG_VARIABLE_LEVEL2;
     453        return TRUE;
     454    case '8':
     455    case '9':
     456      star[0].measure.photFlags |= FLAG_VARIABLE_LEVEL3;
     457      return TRUE;
     458    default:
     459      fprintf (stderr, "programming error\n");
     460      abort();
     461  }
    237462}
    238463
     
    246471    case 'X': star[0].measure.photFlags |= FLAG_PH_X; break;
    247472    default:
    248       fprintf (stderr, "error!\n");
    249       exit (2);
     473      fprintf (stderr, "error in ph_flag: %c\n", qual);
    250474  }     
    251475  return (TRUE);
  • trunk/Ohana/src/addstar/src/resort_unthreaded.c

    r29938 r33963  
    11# include "addstar.h"
    22
    3 int resort_unthreaded (AddstarClientOptions *options, SkyTable *sky) {
    4 
    5   off_t i;
    6   off_t Naverage, Nmeasure;
    7   Catalog catalog;
     3int resort_unthreaded (AddstarClientOptions *options, SkyTable *sky, int hostID, char *hostpath) {
    84
    95  double dtime;
     
    4440  }
    4541
    46   // XXX ALLOCATE catalog[Nthreads]
    47 
    48   /* match stars to existing catalog data (or otherwise manipulate catalog data) */
    49   Naverage = Nmeasure = 0;
    50   for (i = 0; i < skylist[0].Nregions; i++) {
    51 
    52     // XXX BLOCK here for an empty thread
    53 
    54     // set the parameters which guide catalog open/load/create
    55     catalog.filename  = skylist[0].filename[i];
    56     catalog.catformat = dvo_catalog_catformat (CATFORMAT);  // set the default catformat from config data
    57     catalog.catmode   = dvo_catalog_catmode (CATMODE);      // set the default catmode from config data
    58     catalog.catflags  = LOAD_AVES | LOAD_MEAS;
    59     catalog.Nsecfilt  = GetPhotcodeNsecfilt ();
    60 
    61     // an error exit status here is a significant error (disk I/O or file access)
    62     if (!dvo_catalog_open (&catalog, skylist[0].regions[i], VERBOSE, "w")) {
    63       fprintf (stderr, "ERROR: failure to open/create catalog file %s\n", catalog.filename);
    64       exit (2);
    65     }
    66 
    67     // Naves_disk == 0 implies an empty catalog file, skip empty catalogs
    68     if (catalog.Naves_disk == 0) {
    69       dvo_catalog_unlock (&catalog);
    70       dvo_catalog_free (&catalog);
    71       continue;
    72     }
    73 
    74     // this is an overloaded value to mean 'force sort'
    75     if (options->nosort == 3) catalog.sorted = FALSE;
    76 
    77     // XXX send these to a free thread
    78 
    79     if (OLD_RESORT) {
    80       resort_catalog_old (&catalog);
    81     } else {
    82       resort_catalog (&catalog);
    83     }
    84 
    85     // XXX wait for completed threads
    86 
    87     /* report total updated values */
    88     Naverage += catalog.Naverage;
    89     Nmeasure += catalog.Nmeasure;
    90 
    91     // write out catalog, if appropriate
    92     SetProtect (TRUE);
    93     dvo_catalog_save (&catalog, VERBOSE);
    94     SetProtect (FALSE);
    95     dvo_catalog_unlock (&catalog);
    96     dvo_catalog_free (&catalog);
    97   }
     42  resort_unthreaded_catalogs (options, skylist, 0, NULL);
    9843
    9944  gettimeofday (&stop, NULL);
    10045  dtime = DTIME (stop, start);
    101   fprintf (stderr, "SUCCESS: elapsed time %9.4f sec for, "OFF_T_FMT" average, "OFF_T_FMT" measure\n", dtime, Naverage, Nmeasure);
     46  fprintf (stderr, "SUCCESS: elapsed time %9.4f sec\n", dtime);
    10247
    10348  return TRUE;
  • trunk/Ohana/src/addstar/test

    • Property svn:ignore
      •  

        old new  
        1616relphot.Mag.png
        1717relphot.Mcal.dMcal.png
         18catdir.wise.test
  • trunk/Ohana/src/dvomerge/Makefile

    r31496 r33963  
    11default: all
    22help:
    3         @echo "make options: dvomerge (default)"
     3        @echo "make options: dvomerge dvomerge_client dvoconvert (default)"
    44
    55include ../../Makefile.System
     
    1717FULL_LDFLAGS  = -lkapa -ldvo -lFITS -lohana $(BASE_LDFLAGS)
    1818
    19 dvomerge     : $(BIN)/dvomerge.$(ARCH)
    20 dvomerge     : $(BIN)/dvoconvert.$(ARCH)
     19dvomerge        : $(BIN)/dvomerge.$(ARCH)
     20dvomerge_client : $(BIN)/dvomerge_client.$(ARCH)
     21dvoconvert      : $(BIN)/dvoconvert.$(ARCH)
    2122
    22 all: dvomerge dvoconvert dvosecfilt
     23all: dvomerge dvomerge_client dvoconvert dvosecfilt
    2324
    2425#  $(SRC)/dvomergeContinue.$(ARCH).o
     
    2829$(SRC)/dvomergeUpdate.$(ARCH).o \
    2930$(SRC)/dvomergeCreate.$(ARCH).o \
     31$(SRC)/dvomergeUpdate_catalogs.$(ARCH).o \
    3032$(SRC)/dvomergeUpdate_threaded.$(ARCH).o \
    3133$(SRC)/dvomergeFromList.$(ARCH).o \
    3234$(SRC)/dvomergeImageIDs.$(ARCH).o \
    3335$(SRC)/dvo_image_merge_dbs.$(ARCH).o \
     36$(SRC)/IDmapIO.$(ARCH).o \
    3437$(SRC)/SetSignals.$(ARCH).o \
    3538$(SRC)/ConfigInit.$(ARCH).o \
     
    4144$(SRC)/LoadCatalog.$(ARCH).o \
    4245$(SRC)/build_links.$(ARCH).o \
     46$(SRC)/replace_match.$(ARCH).o \
    4347$(SRC)/merge_catalogs_new.$(ARCH).o \
    4448$(SRC)/merge_catalogs_old.$(ARCH).o
     
    4751
    4852$(BIN)/dvomerge.$(ARCH) : $(DVOMERGE)
     53
     54DVOMERGE_CLIENT = \
     55$(SRC)/dvomerge_client.$(ARCH).o \
     56$(SRC)/dvomergeUpdate_catalogs.$(ARCH).o \
     57$(SRC)/dvomergeImageIDs.$(ARCH).o \
     58$(SRC)/dvo_image_merge_dbs.$(ARCH).o \
     59$(SRC)/IDmapIO.$(ARCH).o \
     60$(SRC)/SetSignals.$(ARCH).o \
     61$(SRC)/ConfigInit.$(ARCH).o \
     62$(SRC)/Shutdown.$(ARCH).o \
     63$(SRC)/help.$(ARCH).o \
     64$(SRC)/args.$(ARCH).o \
     65$(SRC)/psps_ids.$(ARCH).o \
     66$(SRC)/SkyTablePopulatedRange.$(ARCH).o \
     67$(SRC)/LoadCatalog.$(ARCH).o \
     68$(SRC)/build_links.$(ARCH).o \
     69$(SRC)/replace_match.$(ARCH).o \
     70$(SRC)/merge_catalogs_new.$(ARCH).o \
     71$(SRC)/merge_catalogs_old.$(ARCH).o
     72
     73$(DVOMERGE_CLIENT) : $(INC)/dvomerge.h
     74
     75$(BIN)/dvomerge_client.$(ARCH) : $(DVOMERGE_CLIENT)
    4976
    5077DVOCONVERT = \
     
    99126$(BIN)/dvoverify.$(ARCH) : $(DVOVERIFY)
    100127
    101 INSTALL = dvomerge dvoconvert dvosecfilt dvorepair dvoverify
     128INSTALL = dvomerge dvomerge_client dvoconvert dvosecfilt dvorepair dvoverify
    102129
    103130# dependancy rules for binary code #########################
  • trunk/Ohana/src/dvomerge/include/dvomerge.h

    r33657 r33963  
    1717# include <glob.h>
    1818
     19# define DVO_MAX_PATH 1024
     20
     21int    PARALLEL;
     22int    PARALLEL_MANUAL;
     23int    PARALLEL_SERIAL;
     24
     25int    HOST_ID;
     26char  *HOSTDIR;
     27
     28
    1929int    VERBOSE;
    2030char   CATDIR[256];
     
    2636int    SKY_DEPTH;
    2737int    NTHREADS;
    28 char   *ALTERNATE_PHOTCODE_FILE;
     38char  *ALTERNATE_PHOTCODE_FILE;
     39int    REPLACE_BY_PHOTCODE;
    2940
    3041SkyRegion UserPatch;  // used by MODE CAT
    3142
    3243typedef struct {
    33   off_t Nmap;
    34   off_t *old;
    35   off_t *new;
     44  unsigned int Nmap;
     45  unsigned int *old;
     46  unsigned int *new;
    3647} IDmapType;
    3748
     
    5162void       dvomerge_help          PROTO((int argc, char **argv));
    5263int        dvomerge_args          PROTO((int *argc, char **argv));
     64
     65void       dvomerge_client_usage  PROTO((void));
     66void       dvomerge_client_help   PROTO((int argc, char **argv));
     67int        dvomerge_client_args   PROTO((int *argc, char **argv));
    5368
    5469void       dvoconvert_usage       PROTO((void));
     
    110125int        dvomergeFromList       PROTO((int argc, char **argv));
    111126int        dvomergeUpdate_threaded PROTO((int argc, char **argv));
     127int        dvomergeUpdate_catalogs PROTO((char *input, char *output, SkyTable *outsky, SkyList *inlist, int NsecfiltInput, int NsecfiltOutput, IDmapType *IDmap, int *secfiltMap));
     128
     129int        replace_match           PROTO((Average *average_out, Measure *measure_out, Average *average_in, Measure *measure_in));
     130
     131int        IDmapSave               PROTO((char *filename, IDmapType *IDmap));
     132IDmapType *IDmapLoad               PROTO((char *filename));
  • trunk/Ohana/src/dvomerge/src/args.c

    r33657 r33963  
    1515    remove_argument (N, argc, argv);
    1616    ALTERNATE_PHOTCODE_FILE = strcreate(argv[N]);
     17    remove_argument (N, argc, argv);
     18  }
     19
     20  /* replace measurement, don't duplicate */
     21  REPLACE_BY_PHOTCODE = FALSE;
     22  if ((N = get_argument (*argc, argv, "-replace"))) {
     23    REPLACE_BY_PHOTCODE = TRUE;
    1724    remove_argument (N, argc, argv);
    1825  }
     
    4350  }
    4451
     52  // XXX for the moment, make this selection manual.  it needs to be automatic
     53  // based on the state of the SkyTable
     54  PARALLEL = FALSE;
     55  if ((N = get_argument (*argc, argv, "-parallel"))) {
     56    PARALLEL = TRUE;
     57    remove_argument (N, argc, argv);
     58  }
     59  // this is a test mode : rather than launching the remote jobs and waiting for completion,
     60  // relphot will simply list the remote command and wait for the user to signal completion
     61  PARALLEL_MANUAL = FALSE;
     62  if ((N = get_argument (*argc, argv, "-parallel-manual"))) {
     63    PARALLEL = TRUE; // -parallel-manual implies -parallel
     64    PARALLEL_MANUAL = TRUE;
     65    remove_argument (N, argc, argv);
     66  }
     67  // this is a test mode : rather than launching the relphot_client jobs remotely, they are
     68  // run in serial via 'system'
     69  PARALLEL_SERIAL = FALSE;
     70  if ((N = get_argument (*argc, argv, "-parallel-serial"))) {
     71    if (PARALLEL_MANUAL) {
     72      fprintf (stderr, "ERROR: cannot mix -parallel-manual and -parallel-serial\n");
     73      exit (1);
     74    }
     75    PARALLEL = TRUE; // -parallel-serial implies -parallel
     76    PARALLEL_SERIAL = TRUE;
     77    remove_argument (N, argc, argv);
     78  }
     79
    4580  if ((*argc < 4) || (*argc > 6)) dvomerge_usage();
     81  return TRUE;
     82}
     83
     84/*** check for command line options ***/
     85int dvomerge_client_args (int *argc, char **argv) {
     86 
     87  int N;
     88
     89  // by definition, the client is not parallel
     90  PARALLEL = FALSE;
     91  PARALLEL_MANUAL = FALSE;
     92  PARALLEL_SERIAL = FALSE;
     93
     94  HOST_ID = 0;
     95  if ((N = get_argument (*argc, argv, "-hostID"))) {
     96    remove_argument (N, argc, argv);
     97    HOST_ID = atoi (argv[N]);
     98    remove_argument (N, argc, argv);
     99  }
     100  if (!HOST_ID) dvomerge_client_usage();
     101
     102  HOSTDIR = NULL;
     103  if ((N = get_argument (*argc, argv, "-hostdir"))) {
     104    remove_argument (N, argc, argv);
     105    HOSTDIR = strcreate (argv[N]);
     106    remove_argument (N, argc, argv);
     107  }
     108  if (!HOSTDIR) dvomerge_client_usage();
     109
     110  /* extra error messages */
     111  VERBOSE = FALSE;
     112  if ((N = get_argument (*argc, argv, "-v"))) {
     113    VERBOSE = TRUE;
     114    remove_argument (N, argc, argv);
     115  }
     116
     117  /* replace measurement, don't duplicate */
     118  REPLACE_BY_PHOTCODE = FALSE;
     119  if ((N = get_argument (*argc, argv, "-replace"))) {
     120    REPLACE_BY_PHOTCODE = TRUE;
     121    remove_argument (N, argc, argv);
     122  }
     123
     124  NTHREADS = 0;
     125  if ((N = get_argument (*argc, argv, "-threads"))) {
     126    remove_argument (N, argc, argv);
     127    NTHREADS = MAX(0, atoi(argv[N]));
     128    remove_argument (N, argc, argv);
     129  }
     130
     131  /*** provide additional data ***/
     132  /* restrict to a portion of the sky? */
     133  UserPatch.Rmin = 0;
     134  UserPatch.Rmax= 360;
     135  UserPatch.Dmin = -90;
     136  UserPatch.Dmax = +90;
     137  if ((N = get_argument (*argc, argv, "-region"))) {
     138    remove_argument (N, argc, argv);
     139    UserPatch.Rmin = atof (argv[N]);
     140    remove_argument (N, argc, argv);
     141    UserPatch.Rmax = atof (argv[N]);
     142    remove_argument (N, argc, argv);
     143    UserPatch.Dmin = atof (argv[N]);
     144    remove_argument (N, argc, argv);
     145    UserPatch.Dmax = atof (argv[N]);
     146    remove_argument (N, argc, argv);
     147  }
     148
     149  if ((*argc < 4) || (*argc > 6)) dvomerge_client_usage();
    46150  return TRUE;
    47151}
  • trunk/Ohana/src/dvomerge/src/dvo_image_merge_dbs.c

    r31450 r33963  
    11# include "dvomerge.h"
    22
     3// utility functions
    34void sort_IDmap (IDmapType *IDmap);
    4 
    5 off_t getTgtIndex (e_time start, e_time stop, short photcode, off_t *TgtIndex, e_time *TgtTimes, short *TgtCodes, off_t NimagesTgt) {
    6 
    7   // use bisection to find the starting entry by time
    8 
    9   off_t Nlo, Nhi, N;
    10 
    11   // find the last TGT before start
    12   Nlo = 0; Nhi = NimagesTgt;
    13   while (Nhi - Nlo > 10) {
    14     N = 0.5*(Nlo + Nhi);
    15     if (TgtTimes[N] < start) {
    16       Nlo = MAX(N, 0);
    17     } else {
    18       Nhi = MIN(N + 1, NimagesTgt);
    19     }
    20   }
    21 
    22   // check for the matched mosaic starting from Nlo
    23   // we may have to go much beyond Nlo since stop is not sorted
    24   // can we use a sorted version of stop to check when we are beyond the valid range??
    25   for (N = Nlo; N < NimagesTgt; N++) {
    26     if (TgtTimes[N] < start) continue;
    27     if (TgtTimes[N] > stop) return (-1);
    28     if (TgtCodes[N] != photcode) continue;
    29     return (TgtIndex[N]);
    30   }
    31   return (-1);
    32 }
    33 
    34 // sort two times vectors and an index by first time vector
    35 void SortTgtByTimes (e_time *S, off_t *I, short *C, off_t N) {
    36 
    37 # define SWAPFUNC(A,B){ e_time tmp_t; off_t tmp_i; short tmp_c;         \
    38   tmp_t = S[A]; S[A] = S[B]; S[B] = tmp_t; \
    39   tmp_i = I[A]; I[A] = I[B]; I[B] = tmp_i; \
    40   tmp_c = C[A]; C[A] = C[B]; C[B] = tmp_c; \
    41 }
    42 # define COMPARE(A,B)(S[A] < S[B])
    43 
    44   OHANA_SORT (N, COMPARE, SWAPFUNC);
    45 
    46 # undef SWAPFUNC
    47 # undef COMPARE
    48 
    49 }
     5void SortTgtByTimes (e_time *S, off_t *I, short *C, off_t N);
     6off_t getTgtIndex (e_time start, e_time stop, short photcode, off_t *TgtIndex, e_time *TgtTimes, short *TgtCodes, off_t NimagesTgt);
    507
    518// we have two tables; 'tgt' contains some exposures from 'src' : find them and match a map
     
    7128  }
    7229
    73   ALLOCATE (IDmap->old, off_t, NimagesSrc);
    74   ALLOCATE (IDmap->new, off_t, NimagesSrc);
     30  ALLOCATE (IDmap->old, unsigned int, NimagesSrc);
     31  ALLOCATE (IDmap->new, unsigned int, NimagesSrc);
    7532  IDmap->Nmap = NimagesSrc;
    7633
     
    11673  int status;
    11774 
     75  IDmap->old = NULL;
     76  IDmap->new = NULL;
     77
     78  // it is OK if there are no images in the database, but there should be no imageIDs to map...
     79  if (in->dbstate == LCK_EMPTY) {
     80    return TRUE;
     81  }
     82
    11883  images = gfits_table_get_Image (&in[0].ftable, &Nimages, &in[0].swapped);
    11984  if (!images) {
     
    12287  }
    12388
    124   ALLOCATE (IDmap->old, off_t, Nimages);
    125   ALLOCATE (IDmap->new, off_t, Nimages);
     89  ALLOCATE (IDmap->old, unsigned int, Nimages);
     90  ALLOCATE (IDmap->new, unsigned int, Nimages);
    12691  IDmap->Nmap = Nimages;
    12792
     
    157122}
    158123
    159 // XXX isn't the map just ID_new = ID_old + offset ??
     124// map this ID to the new table
     125// XXX isn't the map just ID_new = ID_old + offset ?? (probably not)
    160126off_t dvo_map_image_ID (IDmapType *IDmap, off_t oldID) {
    161127
     
    191157}
    192158
     159// given a table of detections, update their image IDs based on the new map
    193160int dvo_update_image_IDs (IDmapType *IDmap, Catalog *catalog) {
    194161
     
    198165    oldID = catalog[0].measure[i].imageID;
    199166    if (oldID == 0) continue;
     167
     168    if (!IDmap->old) {
     169      fprintf (stderr, "input database has image IDs, but no Image table\n");
     170    }
    200171
    201172    newID = dvo_map_image_ID (IDmap, oldID);
     
    225196}
    226197
     198off_t getTgtIndex (e_time start, e_time stop, short photcode, off_t *TgtIndex, e_time *TgtTimes, short *TgtCodes, off_t NimagesTgt) {
     199
     200  // use bisection to find the starting entry by time
     201
     202  off_t Nlo, Nhi, N;
     203
     204  // find the last TGT before start
     205  Nlo = 0; Nhi = NimagesTgt;
     206  while (Nhi - Nlo > 10) {
     207    N = 0.5*(Nlo + Nhi);
     208    if (TgtTimes[N] < start) {
     209      Nlo = MAX(N, 0);
     210    } else {
     211      Nhi = MIN(N + 1, NimagesTgt);
     212    }
     213  }
     214
     215  // check for the matched mosaic starting from Nlo
     216  // we may have to go much beyond Nlo since stop is not sorted
     217  // can we use a sorted version of stop to check when we are beyond the valid range??
     218  for (N = Nlo; N < NimagesTgt; N++) {
     219    if (TgtTimes[N] < start) continue;
     220    if (TgtTimes[N] > stop) return (-1);
     221    if (TgtCodes[N] != photcode) continue;
     222    return (TgtIndex[N]);
     223  }
     224  return (-1);
     225}
     226
     227// sort two times vectors and an index by first time vector
     228void SortTgtByTimes (e_time *S, off_t *I, short *C, off_t N) {
     229
     230# define SWAPFUNC(A,B){ e_time tmp_t; off_t tmp_i; short tmp_c;         \
     231  tmp_t = S[A]; S[A] = S[B]; S[B] = tmp_t; \
     232  tmp_i = I[A]; I[A] = I[B]; I[B] = tmp_i; \
     233  tmp_c = C[A]; C[A] = C[B]; C[B] = tmp_c; \
     234}
     235# define COMPARE(A,B)(S[A] < S[B])
     236
     237  OHANA_SORT (N, COMPARE, SWAPFUNC);
     238
     239# undef SWAPFUNC
     240# undef COMPARE
     241
     242}
     243
  • trunk/Ohana/src/dvomerge/src/dvomergeCreate.c

    r33657 r33963  
    124124  depth2 = insky2[0].regions[Ns].depth;
    125125
     126  SkyList *outlist = SkyListByPatch (outsky, -1, &UserPatch);
     127
    126128  // loop over the populatable output regions
    127   for (i = 0; i < outsky[0].Nregions; i++) {
    128     if (!outsky[0].regions[i].table) continue;
    129     if (VERBOSE) fprintf (stderr, "output: %s\n", outsky[0].regions[i].name);
     129  for (i = 0; i < outlist[0].Nregions; i++) {
     130    if (!outlist[0].regions[i][0].table) continue;
     131    if (VERBOSE) fprintf (stderr, "output: %s\n", outlist[0].regions[i][0].name);
    130132
    131133    // load / create output catalog
    132     LoadCatalog (&outcatalog, &outsky[0].regions[i], outsky[0].filename[i], "w", NsecfiltOutput);
     134    LoadCatalog (&outcatalog, outlist[0].regions[i], outlist[0].filename[i], "w", NsecfiltOutput);
    133135
    134136    // combine only tables at equal or larger depth
    135137     
    136138    // load in all of the tables from input1 for this region
    137     inlist = SkyListByBounds (insky1, depth1, outsky[0].regions[i].Rmin, outsky[0].regions[i].Rmax, outsky[0].regions[i].Dmin, outsky[0].regions[i].Dmax);
     139    inlist = SkyListByBounds (insky1, depth1, outlist[0].regions[i][0].Rmin + 0.01, outlist[0].regions[i][0].Rmax - 0.01, outlist[0].regions[i][0].Dmin + 0.01, outlist[0].regions[i][0].Dmax - 0.01);
    138140    for (j = 0; j < inlist[0].Nregions; j++) {
    139141      if (VERBOSE) fprintf (stderr, "input 1: %s\n", inlist[0].regions[j][0].name);
     
    149151      }
    150152      dvo_update_image_IDs (&IDmap1, &incatalog);
    151       merge_catalogs_new (&outsky[0].regions[i], &outcatalog, &incatalog, secfiltMap1);
     153      merge_catalogs_new (outlist[0].regions[i], &outcatalog, &incatalog, secfiltMap1);
    152154      dvo_catalog_unlock (&incatalog);
    153155      dvo_catalog_free (&incatalog);
     
    156158
    157159    // load in all of the tables from input2 for this region
    158     inlist = SkyListByBounds (insky2, depth2, outsky[0].regions[i].Rmin, outsky[0].regions[i].Rmax, outsky[0].regions[i].Dmin, outsky[0].regions[i].Dmax);
     160    inlist = SkyListByBounds (insky2, depth2, outlist[0].regions[i][0].Rmin + 0.01, outlist[0].regions[i][0].Rmax - 0.01, outlist[0].regions[i][0].Dmin + 0.01, outlist[0].regions[i][0].Dmax - 0.01);
    159161    for (j = 0; j < inlist[0].Nregions; j++) {
    160162      if (VERBOSE) fprintf (stderr, "input 2: %s\n", inlist[0].regions[j][0].name);
     
    170172      }
    171173      dvo_update_image_IDs (&IDmap2, &incatalog);
    172       merge_catalogs_old (&outsky[0].regions[i], &outcatalog, &incatalog, RADIUS, secfiltMap2);
     174      merge_catalogs_old (outlist[0].regions[i], &outcatalog, &incatalog, RADIUS, secfiltMap2);
    173175      dvo_catalog_unlock (&incatalog);
    174176      dvo_catalog_free (&incatalog);
     
    219221    in1DB.mode   = dvo_catalog_catmode (CATMODE);
    220222    in1DB.format = dvo_catalog_catformat (CATFORMAT);
    221     status       = dvo_image_lock (&in1DB, ImageCat, 3600.0, LCK_XCLD);  // shorter timeout?
     223    status       = dvo_image_lock (&in1DB, ImageCat, 3600.0, LCK_SOFT);  // shorter timeout?
    222224    if (!status) Shutdown ("ERROR: failure to lock image catalog %s", in1DB.filename);
    223225
    224226    // load the image table
    225     if (in1DB.dbstate == LCK_EMPTY) {
    226       Shutdown ("can't find input (1) image catalog %s", in1DB.filename);
    227     }
    228     if (!dvo_image_load (&in1DB, VERBOSE, TRUE)) {
    229       Shutdown ("can't read input (1) image catalog %s", in1DB.filename);
    230     }
    231 
     227    if (in1DB.dbstate != LCK_EMPTY) {
     228      if (!dvo_image_load (&in1DB, VERBOSE, TRUE)) {
     229        Shutdown ("can't read input (1) image catalog %s", in1DB.filename);
     230      }
     231    }
     232     
    232233    // convert database table to internal structure & add to output image db
     234    // if in1DB has no images, we will (later) insist that there are no image IDs to map
    233235    dvo_image_merge_dbs(IDmap1, &outDB, &in1DB);
    234236    dvo_image_unlock (&in1DB); // unlock input1
    235 
    236237
    237238    /*** load input2/Images.dat ***/
     
    239240    in2DB.mode   = dvo_catalog_catmode (CATMODE);
    240241    in2DB.format = dvo_catalog_catformat (CATFORMAT);
    241     status       = dvo_image_lock (&in2DB, ImageCat, 3600.0, LCK_XCLD);  // shorter timeout?
     242    status       = dvo_image_lock (&in2DB, ImageCat, 3600.0, LCK_SOFT);  // shorter timeout?
    242243    if (!status) Shutdown ("ERROR: failure to lock image catalog %s", in2DB.filename);
    243244
    244245    /* load the image table */
    245     if (in2DB.dbstate == LCK_EMPTY) {
    246       Shutdown ("can't find input (2) image catalog %s", in2DB.filename);
    247     }
    248     if (!dvo_image_load (&in2DB, VERBOSE, TRUE)) {
    249       Shutdown ("can't read input (2) image catalog %s", in2DB.filename);
     246    if (in2DB.dbstate != LCK_EMPTY) {
     247      if (!dvo_image_load (&in2DB, VERBOSE, TRUE)) {
     248        Shutdown ("can't read input (2) image catalog %s", in2DB.filename);
     249      }
    250250    }
    251251
    252252    // convert database table to internal structure & add to output image db
     253    // if in1DB has no images, we will (later) insist that there are no image IDs to map
    253254    dvo_image_merge_dbs(IDmap2, &outDB, &in2DB);
    254255    dvo_image_unlock (&in2DB); // unlock input2
  • trunk/Ohana/src/dvomerge/src/dvomergeImageIDs.c

    r29938 r33963  
    11# include "dvomerge.h"
    22
    3 /*** update the image table ***/
     3/*** generate the IDmap for the given databases, and update the output image table ***/
    44int dvomergeImagesUpdate (IDmapType *IDmap, char *input, char *output) {
    55
     
    1212  inDB.mode   = dvo_catalog_catmode (CATMODE);
    1313  inDB.format = dvo_catalog_catformat (CATFORMAT);
    14   status       = dvo_image_lock (&inDB, ImageCat, 3600.0, LCK_XCLD);  // shorter timeout?
     14  status       = dvo_image_lock (&inDB, ImageCat, 3600.0, LCK_SOFT);  // shorter timeout?
    1515  if (!status) Shutdown ("ERROR: failure to lock image catalog %s", inDB.filename);
    1616
    1717  // load the image table
    1818  if (inDB.dbstate == LCK_EMPTY) {
     19    dvo_image_unlock (&inDB); // unlock input
    1920    IDmap->Nmap = 0;
    2021    return TRUE;
     
    5253}
    5354
    54 /*** update the image table ***/
     55/*** generate the map for the given 2 databases ***/
    5556int dvomergeImagesGetMap (IDmapType *IDmap, char *input, char *output) {
    5657
     
    6364  inDB.mode   = dvo_catalog_catmode (CATMODE);
    6465  inDB.format = dvo_catalog_catformat (CATFORMAT);
    65   status       = dvo_image_lock (&inDB, ImageCat, 3600.0, LCK_XCLD);  // shorter timeout?
     66  status       = dvo_image_lock (&inDB, ImageCat, 5400.0, LCK_XCLD);  // shorter timeout?
    6667  if (!status) Shutdown ("ERROR: failure to lock image catalog %s", inDB.filename);
    6768
    6869  // load the image table
    6970  if (inDB.dbstate == LCK_EMPTY) {
     71    dvo_image_unlock (&inDB); // unlock input
    7072    IDmap->Nmap = 0;
    7173    return TRUE;
     
    7678    Shutdown ("can't read input image catalog %s", inDB.filename);
    7779  }
     80  dvo_image_unlock (&inDB); // unlock input
    7881
    7982  /*** load output/Images.dat ***/
     
    8184  outDB.mode   = dvo_catalog_catmode (CATMODE);
    8285  outDB.format = dvo_catalog_catformat (CATFORMAT);
    83   status       = dvo_image_lock (&outDB, ImageCat, 3600.0, LCK_XCLD);  // shorter timeout?
     86  status       = dvo_image_lock (&outDB, ImageCat, 5400.0, LCK_XCLD);  // shorter timeout?
    8487  if (!status) Shutdown ("ERROR: failure to lock image catalog %s", outDB.filename);
    8588
    8689  /* load the image table */
    8790  if (outDB.dbstate == LCK_EMPTY) {
    88     Shutdown ("only use -continue for an existing, partially merged database");
     91    Shutdown ("for dvomerge -continue or dvomerge_client, the output database must exist");
    8992  }
    9093  if (!dvo_image_load (&outDB, VERBOSE, TRUE)) {
    9194    Shutdown ("can't read output image catalog %s", outDB.filename);
    9295  }
     96  dvo_image_unlock (&outDB); // unlock output
    9397
    9498  // convert database table to internal structure & add to output image db
    9599  dvo_image_match_dbs(IDmap, &outDB, &inDB);
    96   dvo_image_unlock (&inDB); // unlock input
    97   dvo_image_unlock (&outDB); // unlock output
    98100
    99101  return TRUE;
  • trunk/Ohana/src/dvomerge/src/dvomergeUpdate.c

    r33657 r33963  
    44
    55  int CONTINUE;
    6   off_t i, j;
    76  SkyTable *outsky, *insky;
    8   SkyList *outlist, *inlist;
    9   Catalog incatalog, outcatalog;
     7  SkyList *inlist;
    108  char filename[256], *input, *output;
    119  IDmapType IDmap;
     
    107105  SetPhotcodeTable(NULL);
    108106
    109   // loop over the populated input regions
    110   for (i = 0; i < inlist[0].Nregions; i++) {
    111     if (!inlist[0].regions[i][0].table) continue;
    112     if (VERBOSE) fprintf (stderr, "input: %s\n", inlist[0].regions[i][0].name);
    113 
    114     // load / create output catalog (if catalog does not exist, it will be created)
    115     LoadCatalog (&incatalog, &inlist[0].regions[i][0], inlist[0].filename[i], "r", NsecfiltInput);
    116     // skip empty input catalogs
    117     if (!incatalog.Naves_disk) {
    118         dvo_catalog_unlock (&incatalog);
    119         dvo_catalog_free (&incatalog);
    120         continue;
    121     }
    122 
    123     // combine only tables at equal or larger depth
    124      
    125     // load in all of the tables from input for this region
    126     // SkyListByBounds will return neighbor catalogs if the boundaries exactly match (due to rounding).  Since the regions are not infinitely small,
    127     // compare to a slightly reduced footprint
    128     float dPos = 2.0/3600.0;
    129     outlist = SkyListByBounds (outsky, inlist[0].regions[i][0].depth, inlist[0].regions[i][0].Rmin + dPos, inlist[0].regions[i][0].Rmax - dPos, inlist[0].regions[i][0].Dmin + dPos, inlist[0].regions[i][0].Dmax - dPos);
    130     for (j = 0; j < outlist[0].Nregions; j++) {
    131       if (VERBOSE) fprintf (stderr, "output : %s\n", outlist[0].regions[j][0].name);
    132 
    133       // load input catalog
    134       LoadCatalog (&outcatalog, outlist[0].regions[j], outlist[0].filename[j], "w", NsecfiltOutput);
    135 
    136       dvo_update_image_IDs (&IDmap, &incatalog);
    137       merge_catalogs_old (&outsky[0].regions[j], &outcatalog, &incatalog, RADIUS, secfiltMap);
    138 
    139       outcatalog.catflags = LOAD_AVES | LOAD_MEAS | LOAD_MISS | LOAD_SECF;
    140 
    141       // if we receive a signal which would cause us to exit, wait until the full catalog is written
    142       SetProtect (TRUE);
    143       if (!dvo_catalog_save (&outcatalog, VERBOSE)) {
    144         fprintf (stderr, "ERROR: failed to save catalog %s\n", outlist[0].filename[j]);
    145         exit (1);
    146       }
    147       SetProtect (FALSE);
    148 
    149       dvo_catalog_unlock (&outcatalog);
    150       dvo_catalog_free (&outcatalog);
    151 
    152       fprintf (stderr, "merged %s into %s\n", inlist[0].regions[i][0].name, outlist[0].regions[j][0].name);
    153     }
    154     SkyListFree (outlist);
    155 
    156     dvo_catalog_unlock (&incatalog);
    157     dvo_catalog_free (&incatalog);
    158   }
     107  dvomergeUpdate_catalogs (input, output, outsky, inlist, NsecfiltInput, NsecfiltOutput, &IDmap, secfiltMap);
    159108
    160109  // save the output sky table copy
  • trunk/Ohana/src/dvomerge/src/dvoverify.c

    r33657 r33963  
    4444    CHECKSORTED = TRUE;
    4545    remove_argument (N, &argc, argv);
     46  }
     47
     48  if ((N = get_argument (argc, argv, "-cpt"))) {
     49    remove_argument (N, &argc, argv);
     50    char *filename = strcreate (argv[N]);
     51    remove_argument (N, &argc, argv);
     52
     53    int isBad = FALSE;
     54
     55    if (!VerifyTableFile (filename)) {
     56      fprintf (stderr, "bad average table %s\n", filename);
     57      isBad = TRUE;
     58    }
     59
     60    // change last 't' to 's':
     61    int Nlast;
     62    Nlast = strlen(filename) - 1;
     63    filename[Nlast] = 's';
     64    if (!VerifyTableFile (filename)) {
     65      fprintf (stderr, "bad secfilt table %s\n", filename);
     66      isBad = TRUE;
     67    }
     68
     69    // change last 't' to 's':
     70    Nlast = strlen(filename) - 1;
     71    filename[Nlast] = 'm';
     72    if (!VerifyTableFile (filename)) {
     73      fprintf (stderr, "bad measure table %s\n", filename);
     74      isBad = TRUE;
     75    }
     76
     77    if (isBad) exit (1);
     78    exit (0);
    4679  }
    4780
  • trunk/Ohana/src/dvomerge/src/help.c

    r30615 r33963  
    66  fprintf (stderr, "   OR: dvomerge (input) into (output) continue\n");
    77  fprintf (stderr, "   OR: dvomerge (input) into (output) from (list)\n");
     8  fprintf (stderr, "   [-region Rmin Rmax Dmin Dmax]\n");
     9  exit (2);
     10}
     11
     12void dvomerge_client_usage (void) {
     13  fprintf (stderr, "USAGE: dvomerge_client (input) into (output)\n");
    814  fprintf (stderr, "   [-region Rmin Rmax Dmin Dmax]\n");
    915  exit (2);
     
    4551  fprintf (stderr, "  -h                          : this list\n\n");
    4652  fprintf (stderr, "  -region Rmin Rmax Dmin Dmax : region to merge\n\n");
     53  fprintf (stderr, "  -replace                    : replace existing detections of the same photcode\n");
     54  fprintf (stderr, "                                (this should only be used to merge reference dbs)\n\n");
     55  exit (2);
     56}
     57
     58void dvomerge_client_help (int argc, char **argv) {
     59
     60  /* check for help request */
     61  if (get_argument (argc, argv, "-help")) goto show_help;
     62  if (get_argument (argc, argv, "-h"))    goto show_help;
     63  return;
     64
     65show_help:
     66
     67  fprintf (stderr, "USAGE\n");
     68  fprintf (stderr, "  dvomerge_client (input) into (output)\n");
     69  fprintf (stderr, "  merge DVO databases\n");
     70  fprintf (stderr, "  optional flags:\n");
     71  fprintf (stderr, "  -v                          : verbose mode\n");
     72  fprintf (stderr, "  -help                       : this list\n");
     73  fprintf (stderr, "  -h                          : this list\n\n");
     74  fprintf (stderr, "  -region Rmin Rmax Dmin Dmax : region to merge\n\n");
     75  fprintf (stderr, "  -replace                    : replace existing detections of the same photcode\n");
     76  fprintf (stderr, "                                (this should only be used to merge reference dbs)\n\n");
    4777  exit (2);
    4878}
  • trunk/Ohana/src/dvomerge/src/merge_catalogs_old.c

    r30761 r33963  
    111111  if (Nave > 1) sort_coords_index (X2, Y2, N2, Nave);
    112112
     113  if (REPLACE_BY_PHOTCODE && output[0].Nmeasure && !output[0].sorted) {
     114    fprintf (stderr, "ERROR: attempt to merge with replace into an unsorted database\n");
     115    exit (3);
     116  }
     117
     118
    113119  /* set up pointers for linked list of measure */
    114120  if (output[0].sorted && (output[0].Nmeasure >= output[0].Nmeas_disk)) {
     
    186192      offset = input[0].average[N].measureOffset + Nin;
    187193
     194      if (REPLACE_BY_PHOTCODE) {
     195        // index to first measure for this object
     196        int Mout = output[0].average[n].measureOffset; 
     197        if (replace_match(&output[0].average[n], &output[0].measure[Mout], &input[0].average[N], &input[0].measure[offset])) {
     198          input[0].found[N] = Mout;
     199          continue;
     200        }
     201      }
    188202      /* add to end of measurement list */
    189203      add_meas_link (&output[0].average[n], next_meas, Nmeas, NMEAS);
  • trunk/Ohana/src/dvomerge/test

    • Property svn:ignore set to
      catdir.test
  • trunk/Ohana/src/dvomerge/test/catdir.2mass

    • Property svn:ignore set to
      s8230
      s3730
      s6730
      n3000
      s0000
      n1500
      n6000
      n2230
      s3000
      n4500
      n5230
      s6000
      s1500
      n7500
      s2230
      n8230
      n3730
      s4500
      s0730
      Images.dat
      s5230
      n6730
      s7500
  • trunk/Ohana/src/dvosplit/src/dvosplit.c

    r33656 r33963  
    140140    char line[2048];
    141141    snprintf (line, 2048, "cp %s/Images.dat %s/Images.dat", CATDIR, OUTDIR);
    142     system (line);
     142    int status = system (line);
     143    if (status) {
     144      fprintf (stderr, "ERROR: failed to copy Images.dat\n");
     145      exit (1);
     146    }
    143147  }
    144148
  • trunk/Ohana/src/libautocode/def/image.d

    r33647 r33963  
    6969
    7070FIELD     dMagSys,          MAG_SYS_ERR,          float,          systematic photometry error
    71 FIELD     nFitAstrom,       N_FIT_ASTROM,         short,          number of stars used for astrometry cal
    72 FIELD     nFitPhotom,       N_FIT_PHOTOM,         short,          number of stars used for photometry cal
     71FIELD     nFitAstrom,       N_FIT_ASTROM,         unsigned short, number of stars used for astrometry cal
     72FIELD     nFitPhotom,       N_FIT_PHOTOM,         unsigned short, number of stars used for photometry cal
    7373
    7474FIELD     photom_map_id,    PHOTOM_MAP_ID,        unsigned int,   reference to 2D zero point map
  • trunk/Ohana/src/libautocode/def/secfilt-ps1-v3.d

    r33647 r33963  
    1616FIELD  M_80,        MAG_80,       short,      upper 20percent mag,                   millimags
    1717FIELD  ubercalDist, UBERCAL_DIST, short,      number of images from an ubercal-image
    18 FIELD  dummy,       DUMMY,        char[2],    padding
     18FIELD  Mstdev,      MAG_STDEV,    short,      standard deviation of measurements,    millimags
  • trunk/Ohana/src/libautocode/def/secfilt.d

    r33647 r33963  
    1616FIELD  M_80,        MAG_80,       short,      upper 20percent mag,                   millimags
    1717FIELD  ubercalDist, UBERCAL_DIST, short,      number of images from an ubercal-image
    18 FIELD  dummy,       DUMMY,        char[2],    padding
     18FIELD  Mstdev,      MAG_STDEV,    short,      standard deviation of measurements,    millimags
    1919
    2020# *** 20090206 : new fields : M_20, M_80; dropped dummy
  • trunk/Ohana/src/libdvo/include/dvo.h

    r33779 r33963  
    6969  NAN_U_INT   = (signed int) 0xffffffff,
    7070} DVO_INT_NAN;
     71
     72// max path length
     73# define DVO_MAX_PATH 1024
    7174
    7275/* RegImage.flag values */
     
    453456float PhotdM (PhotCode *code, Average *average, SecFilt *secfilt);
    454457
     458float PhotMstdev (PhotCode *code, Average *average, SecFilt *secfilt);
     459float PhotM20 (PhotCode *code, Average *average, SecFilt *secfilt);
     460float PhotM80 (PhotCode *code, Average *average, SecFilt *secfilt);
     461float PhotUCdist (PhotCode *code, Average *average, SecFilt *secfilt);
     462
    455463float PhotColorForCode (Average *average, SecFilt *secfilt, Measure *measure, PhotCode *code);
    456464int PhotColor (Average *average, SecFilt *secfilt, Measure *measure, int c1, int c2, double *color);
     
    516524void dvo_catalog_test (Catalog *catalog, int halt);
    517525
     526int dvo_catalog_backup (Catalog *catalog, int primary);
     527int dvo_catalog_unlink_backup (Catalog *catalog, int primary);
     528
    518529/* catmode-specific APIs */
    519530int dvo_catalog_load_raw (Catalog *catalog, int VERBOSE);
  • trunk/Ohana/src/libdvo/include/dvodb.h

    r33649 r33963  
    3232      MAG_REF,
    3333      MAG_ERR,
     34      MAG_STDEV,
    3435      MAG_AVE_ERR,
    3536      MAG_PHOT_FLAGS,
     
    3738      MAG_NCODE,
    3839      MAG_NPHOT,
     40      MAG_20,
     41      MAG_80,
     42      MAG_UC_DIST,
    3943};
    4044
     
    327331
    328332int dbExtractAveragesInitTransform (CoordTransformSystem target);
     333int dbExtractAveragesInitAve (void);
    329334int dbExtractAveragesInit (void);
    330335
  • trunk/Ohana/src/libdvo/src/HostTable.c

    r33779 r33963  
    125125
    126126  for (i = 0; i < table->Nhosts; i++) {
    127     if (table->index[table->hosts[i].hostID] == -1) {
     127    if (table->index[table->hosts[i].hostID] != -1) {
    128128      fprintf (stderr, "error: duplicate hostID %d\n", table->hosts[i].hostID);
    129129      exit (1);
     
    168168
    169169    // find the host which has finished
    170     int j;
     170    int Nout, j;
    171171    int found = FALSE;
    172172    for (j = 0; j < table->Nhosts; j++) {
     
    180180      EmptyIOBuffer (&buffer, 100, table->hosts[j].stdio[HOST_STDOUT]);
    181181      fprintf (stderr, "--- stdout from %s ---\n", table->hosts[j].hostname);
    182       write (STDOUT_FILENO, buffer.buffer, buffer.Nbuffer);
     182      Nout = write (STDOUT_FILENO, buffer.buffer, buffer.Nbuffer);
     183      if (Nout != buffer.Nbuffer) { fprintf (stderr, "(error writing log?)\n"); }
    183184      fprintf (stderr, "\n");
    184185         
     
    186187      EmptyIOBuffer (&buffer, 100, table->hosts[j].stdio[HOST_STDERR]);
    187188      fprintf (stderr, "--- stderr from %s ---\n", table->hosts[j].hostname);
    188       write (STDOUT_FILENO, buffer.buffer, buffer.Nbuffer);
     189      Nout = write (STDOUT_FILENO, buffer.buffer, buffer.Nbuffer);
     190      if (Nout != buffer.Nbuffer) { fprintf (stderr, "(error writing log?)\n"); }
    189191      fprintf (stderr, "\n");
    190192      if (WIFEXITED(status)) {
     
    271273        // if (table->hosts[i].stdout.Nbuffer > 0x10000) {
    272274        if (table->hosts[i].stdout.Nbuffer > 0x1000) {
    273           int printHead = VERBOSE || table->hosts[i].stdout.Nbuffer;
    274           if (printHead) fprintf (stdout, "--- stdout from %s ---\n", table->hosts[i].hostname);
    275           write (STDOUT_FILENO, table->hosts[i].stdout.buffer, table->hosts[i].stdout.Nbuffer);
     275          int printHead = VERBOSE || (table->hosts[i].stdout.Nbuffer > 0);
     276          if (printHead) fprintf (stdout, "--- stdout from %s --- (%d bytes, v1)\n", table->hosts[i].hostname, table->hosts[i].stdout.Nbuffer);
     277          int Nout = write (STDOUT_FILENO, table->hosts[i].stdout.buffer, table->hosts[i].stdout.Nbuffer);
     278          if (Nout != table->hosts[i].stdout.Nbuffer) { fprintf (stderr, "(error writing log?)\n"); }
    276279          FlushIOBuffer (&table->hosts[i].stdout);
    277280          if (printHead) fprintf (stdout, "\n");
     
    284287        // if (table->hosts[i].stderr.Nbuffer > 0x10000) {
    285288        if (table->hosts[i].stderr.Nbuffer > 0x1000) {
    286           int printHead = VERBOSE || table->hosts[i].stderr.Nbuffer;
    287           if (printHead) fprintf (stdout, "--- stderr from %s ---\n", table->hosts[i].hostname);
    288           write (STDOUT_FILENO, table->hosts[i].stderr.buffer, table->hosts[i].stderr.Nbuffer);
     289          int printHead = VERBOSE || (table->hosts[i].stderr.Nbuffer > 0);
     290          if (printHead) fprintf (stdout, "--- stderr from %s --- (%d bytes, v1)\n", table->hosts[i].hostname, table->hosts[i].stderr.Nbuffer);
     291          int Nout = write (STDOUT_FILENO, table->hosts[i].stderr.buffer, table->hosts[i].stderr.Nbuffer);
     292          if (Nout != table->hosts[i].stderr.Nbuffer) { fprintf (stderr, "(error writing log?)\n"); }
    289293          FlushIOBuffer (&table->hosts[i].stderr);
    290294          if (printHead) fprintf (stdout, "\n");
     
    321325        // read stdout
    322326        int printHead;
    323         printHead = VERBOSE || host->stdout.Nbuffer;
     327        printHead = VERBOSE || (host->stdout.Nbuffer > 0);
    324328        EmptyIOBuffer (&host->stdout, 100, host->stdio[HOST_STDOUT]);
    325         if (printHead) fprintf (stdout, "--- stdout from %s ---\n", host->hostname);
    326         write (STDOUT_FILENO, host->stdout.buffer, host->stdout.Nbuffer);
     329        if (printHead) fprintf (stdout, "--- stdout from %s --- (%d bytes, v2)\n", host->hostname, host->stdout.Nbuffer);
     330        int Nout = write (STDOUT_FILENO, host->stdout.buffer, host->stdout.Nbuffer);
     331        if (Nout != host->stdout.Nbuffer) { fprintf (stderr, "(error writing log?)\n"); }
    327332        FlushIOBuffer (&host->stdout);
    328333        if (printHead) fprintf (stdout, "\n");
    329334           
    330335        // read stderr
    331         printHead = VERBOSE || host->stderr.Nbuffer;
     336        printHead = VERBOSE || (host->stderr.Nbuffer > 0);
    332337        EmptyIOBuffer (&host->stderr, 100, host->stdio[HOST_STDERR]);
    333         if (printHead) fprintf (stdout, "--- stderr from %s ---\n", host->hostname);
    334         write (STDOUT_FILENO, host->stderr.buffer, host->stderr.Nbuffer);
     338        if (printHead) fprintf (stdout, "--- stderr from %s --- (%d bytes, v2)\n", host->hostname, host->stderr.Nbuffer);
     339        Nout = write (STDOUT_FILENO, host->stderr.buffer, host->stderr.Nbuffer);
     340        if (Nout != host->stderr.Nbuffer) { fprintf (stderr, "(error writing log?)\n"); }
    335341        FlushIOBuffer (&host->stderr);
    336342        if (printHead) fprintf (stdout, "\n");
  • trunk/Ohana/src/libdvo/src/dbExtractAverages.c

    r33649 r33963  
    4040int dbExtractAveragesInit () {
    4141  GetTimeFormat (&TimeReference, &TimeFormat);
     42  return (TRUE);
     43}
     44
     45int dbExtractAveragesInitAve () {
    4246  haveGalactic = FALSE;
    4347  haveEcliptic = FALSE;
     
    200204          }
    201205          break;
     206        case MAG_STDEV:
     207          value.Flt = PhotMstdev (field->photcode, average, secfilt);
     208          break;
    202209        case MAG_PHOT_FLAGS:
    203210          if ((field->photcode->type == PHOT_REF) || (field->photcode->type == PHOT_DEP)) {
     
    226233          break;
    227234
     235        case MAG_20:
     236          value.Flt = PhotM20 (field->photcode, average, secfilt);
     237          break;
     238        case MAG_80:
     239          value.Flt = PhotM80 (field->photcode, average, secfilt);
     240          break;
     241        case MAG_UC_DIST:
     242          value.Flt = PhotUCdist (field->photcode, average, secfilt);
     243          break;
    228244      }
    229245      break;
  • trunk/Ohana/src/libdvo/src/dbFields.c

    r33649 r33963  
    4646  if (!strcasecmp (string, "ncode"))     return (MAG_NCODE);
    4747  if (!strcasecmp (string, "nphot"))     return (MAG_NPHOT);
     48  if (!strcasecmp (string, "stdev"))     return (MAG_STDEV);
     49  if (!strcasecmp (string, "20"))        return (MAG_20);
     50  if (!strcasecmp (string, "80"))        return (MAG_80);
     51  if (!strcasecmp (string, "ucdist"))    return (MAG_UC_DIST);
    4852  return (MAG_NONE);
    4953}
  • trunk/Ohana/src/libdvo/src/dvo_catalog.c

    r33649 r33963  
    211211 
    212212  if (!check_file_access (catalog[0].filename, BACKUP, READWRITE, VERBOSE)) {
    213     if (VERBOSE) fprintf (stderr, "no permission to access %s\n", catalog[0].filename);
     213    fprintf (stderr, "no permission to access %s\n", catalog[0].filename);
    214214    return (FALSE);
    215215  }
     
    219219  switch (dvo_catalog_lock (catalog, catalog[0].lockmode)) {
    220220  case DVO_CAT_OPEN_FAIL:
    221     if (VERBOSE) fprintf (stderr, "can't lock file %s\n", catalog[0].filename);
     221    fprintf (stderr, "can't lock file %s\n", catalog[0].filename);
    222222    return (FALSE);
    223223  case DVO_CAT_OPEN_OK:
    224224    if (!dvo_catalog_load (catalog, VERBOSE)) {
    225       if (VERBOSE) fprintf (stderr, "failure loading catalog\n");
     225      fprintf (stderr, "failure loading catalog\n");
    226226      return (FALSE);
    227227    }
    228228    if (!dvo_catalog_check (catalog, Nsecfilt, TRUE)) {
    229       if (VERBOSE) fprintf (stderr, "can't reduce number of secondary filters\n");
     229      fprintf (stderr, "can't reduce number of secondary filters\n");
    230230      return (FALSE);
    231231    }
     
    499499}
    500500
     501// make a backup of this catalog (including the measure, secfilt, and missing tables as needed)
     502int dvo_catalog_backup (Catalog *catalog, int primary) {
     503
     504  // skip empty cpt files
     505  if (primary && !catalog->Naves_disk) {
     506    return TRUE;
     507  }
     508
     509  char tmpfilename[DVO_MAX_PATH];
     510  int status = snprintf (tmpfilename, DVO_MAX_PATH, "%s~", catalog->filename);
     511  if (status >= DVO_MAX_PATH) {
     512    fprintf (stderr, "path name too long: %s\n", catalog->filename);
     513    return FALSE;
     514  }
     515     
     516  // unlock the catalog here (closes file as well) (also closes subcat files Measure, Secfilt, Missing)
     517  if (primary) {
     518    status = dvo_catalog_unlock (catalog);
     519    if (!status) {
     520      fprintf (stderr, "failed to unlock catalog %s\n", catalog->filename);
     521      return FALSE;
     522    }
     523  }
     524
     525  status = rename (catalog->filename, tmpfilename);
     526  if (status) {
     527    fprintf (stderr, "failed to rename catalog %s\n", catalog->filename);
     528    return FALSE;
     529  }
     530     
     531  // keep the same lockmode
     532  int lockmode = catalog->lockmode;
     533
     534  // lock the new catalog file here (re-opens file as well) (does NOT open/lock the subcat files)
     535  status = dvo_catalog_lock (catalog, lockmode);
     536  if (!status) {
     537    fprintf (stderr, "failed to lock new catalog file %s\n", catalog->filename);
     538    return FALSE;
     539  }
     540
     541  if (catalog[0].catmode == DVO_MODE_SPLIT) {
     542    if (catalog[0].measure_catalog != NULL) {
     543      if (!dvo_catalog_backup (catalog[0].measure_catalog, FALSE)) {
     544        return FALSE;
     545      }
     546    }
     547    if (catalog[0].missing_catalog != NULL) {
     548      if (!dvo_catalog_backup (catalog[0].missing_catalog, FALSE)) {
     549        return FALSE;
     550      }
     551    }
     552    if (catalog[0].secfilt_catalog != NULL) {
     553      if (!dvo_catalog_backup (catalog[0].secfilt_catalog, FALSE)) {
     554        return FALSE;
     555      }
     556    }
     557  }
     558  return TRUE;
     559}
     560
     561// make a backup of this catalog (including the measure, secfilt, and missing tables as needed)
     562int dvo_catalog_unlink_backup (Catalog *catalog, int primary) {
     563
     564  if (primary && !catalog->Naves_disk) {
     565    // skip empty files (empty when read, but output may not be empty)
     566    return TRUE;
     567  }
     568
     569  char tmpfilename[DVO_MAX_PATH];
     570  int status = snprintf (tmpfilename, DVO_MAX_PATH, "%s~", catalog->filename);
     571  if (status >= DVO_MAX_PATH) {
     572    fprintf (stderr, "path name too long: %s\n", catalog->filename);
     573    return FALSE;
     574  }
     575     
     576  status = unlink (tmpfilename);
     577  if (status) {
     578    fprintf (stderr, "failed to unlink catalog %s\n", catalog->filename);
     579    return FALSE;
     580  }
     581     
     582  if (catalog[0].catmode == DVO_MODE_SPLIT) {
     583    if (catalog[0].measure_catalog != NULL) {
     584      if (!dvo_catalog_unlink_backup (catalog[0].measure_catalog, FALSE)) {
     585        return FALSE;
     586      }
     587    }
     588    if (catalog[0].missing_catalog != NULL) {
     589      if (!dvo_catalog_unlink_backup (catalog[0].missing_catalog, FALSE)) {
     590        return FALSE;
     591      }
     592    }
     593    if (catalog[0].secfilt_catalog != NULL) {
     594      if (!dvo_catalog_unlink_backup (catalog[0].secfilt_catalog, FALSE)) {
     595        return FALSE;
     596      }
     597    }
     598  }
     599  return TRUE;
     600}
     601
  • trunk/Ohana/src/libdvo/src/dvo_catalog_split.c

    r33649 r33963  
    8080  // write PHU header
    8181  if (!gfits_fwrite_header  (catalog->f, &catalog->header)) {
    82     fprintf (stderr, "can't write primary header");
     82    fprintf (stderr, "can't write primary header\n");
    8383    return (FALSE);
    8484  }
     
    8787  gfits_create_matrix (&catalog->header, &matrix);
    8888  if (!gfits_fwrite_matrix  (catalog->f, &matrix)) {
    89     fprintf (stderr, "can't write primary matrix");
     89    fprintf (stderr, "can't write primary matrix\n");
    9090    gfits_free_matrix (&matrix);
    9191    return (FALSE);
     
    9595  // write the table data
    9696  if (!gfits_fwrite_ftable_range (catalog->f, ftable, start, Nrows, Ndisk, Ntotal)) {
    97     fprintf (stderr, "can't write table data");
     97    fprintf (stderr, "can't write table data\n");
    9898    return (FALSE);
    9999  }
  • trunk/Ohana/src/libdvo/src/dvo_convert_PS1_DEV_1.c

    r33649 r33963  
    213213    // added in PS1_V3
    214214    out[i].Map         = 0;
     215    out[i].Mstdev      = 0;
    215216    out[i].ubercalDist = 0;
    216217 }
  • trunk/Ohana/src/libdvo/src/dvo_convert_PS1_DEV_2.c

    r33649 r33963  
    207207    // added in PS1_V3
    208208    out[i].Map         = 0;
     209    out[i].Mstdev      = 0;
    209210    out[i].ubercalDist = 0;
    210211 }
  • trunk/Ohana/src/libdvo/src/dvo_convert_PS1_REF.c

    r33649 r33963  
    167167    // added in PS1_V3
    168168    out[i].Map         = 0;
     169    out[i].Mstdev      = 0;
    169170    out[i].ubercalDist = 0;
    170171 }
  • trunk/Ohana/src/libdvo/src/dvo_convert_PS1_V1.c

    r33649 r33963  
    211211    // added in PS1_V3
    212212    out[i].Map         = 0;
     213    out[i].Mstdev      = 0;
    213214    out[i].ubercalDist = 0;
    214215 }
  • trunk/Ohana/src/libdvo/src/dvo_convert_PS1_V2.c

    r33649 r33963  
    214214    // added in PS1_V3
    215215    out[i].Map         = 0;
     216    out[i].Mstdev      = 0;
    216217    out[i].ubercalDist = 0;
    217218 }
  • trunk/Ohana/src/libdvo/src/dvo_convert_PS1_V3.c

    r33649 r33963  
    212212    out[i].M_20        = in[i].M_20;     
    213213    out[i].M_80        = in[i].M_80;     
     214    out[i].Mstdev      = in[i].Mstdev;     
    214215    out[i].ubercalDist = in[i].ubercalDist;     
    215216 }
     
    234235    out[i].M_20        = in[i].M_20;     
    235236    out[i].M_80        = in[i].M_80;     
     237    out[i].Mstdev      = in[i].Mstdev;     
    236238    out[i].ubercalDist = in[i].ubercalDist;     
    237239  }
  • trunk/Ohana/src/libdvo/src/dvo_convert_elixir.c

    r33649 r33963  
    222222    // added in PS1_V3
    223223    out[i].Map         = 0;
     224    out[i].Mstdev      = 0;
    224225    out[i].ubercalDist = 0;
    225226  }
  • trunk/Ohana/src/libdvo/src/dvo_convert_loneos.c

    r33649 r33963  
    215215    // added in PS1_V3
    216216    out[i].Map         = 0;
     217    out[i].Mstdev      = 0;
    217218    out[i].ubercalDist = 0;
    218219  }
  • trunk/Ohana/src/libdvo/src/dvo_convert_panstarrs_DEV_0.c

    r33649 r33963  
    222222    // added in PS1_V3
    223223    out[i].Map         = 0;
     224    out[i].Mstdev      = 0;
    224225    out[i].ubercalDist = 0;
    225226 }
  • trunk/Ohana/src/libdvo/src/dvo_convert_panstarrs_DEV_1.c

    r33649 r33963  
    222222    // added in PS1_V3
    223223    out[i].Map         = 0;
     224    out[i].Mstdev      = 0;
    224225    out[i].ubercalDist = 0;
    225226 }
  • trunk/Ohana/src/libdvo/src/dvo_photcode_ops.c

    r33649 r33963  
    476476}
    477477
     478float PhotMstdev (PhotCode *code, Average *average, SecFilt *secfilt) {
     479
     480  int Ns;
     481  float Mstdev;
     482
     483  if (code == NULL) return NAN;
     484
     485  Ns = photcodes[0].hashNsec[code[0].code];
     486  Mstdev  = (Ns == -1) ? NAN : 0.001*secfilt[Ns].Mstdev;
     487  return (Mstdev);
     488}
     489
     490float PhotM20 (PhotCode *code, Average *average, SecFilt *secfilt) {
     491
     492  int Ns;
     493  float M20;
     494
     495  if (code == NULL) return NAN;
     496
     497  Ns = photcodes[0].hashNsec[code[0].code];
     498  M20  = (Ns == -1) ? NAN : 0.001*secfilt[Ns].M_20;
     499  return (M20);
     500}
     501
     502float PhotM80 (PhotCode *code, Average *average, SecFilt *secfilt) {
     503
     504  int Ns;
     505  float M80;
     506
     507  if (code == NULL) return NAN;
     508
     509  Ns = photcodes[0].hashNsec[code[0].code];
     510  M80  = (Ns == -1) ? NAN : 0.001*secfilt[Ns].M_80;
     511  return (M80);
     512}
     513
     514float PhotUCdist (PhotCode *code, Average *average, SecFilt *secfilt) {
     515
     516  int Ns;
     517  float Muc;
     518
     519  if (code == NULL) return NAN;
     520
     521  Ns = photcodes[0].hashNsec[code[0].code];
     522  Muc  = (Ns == -1) ? NAN : secfilt[Ns].ubercalDist;
     523  return (Muc);
     524}
     525
    478526// XXX return NAN or NAN_S_SHORT? (secfilt->Xm is short)
    479527float PhotXm (PhotCode *code, Average *average, SecFilt *secfilt) {
  • trunk/Ohana/src/libdvo/src/flatcorr_io.c

    r33649 r33963  
    185185float FlatCorrectionOffset (FlatCorrectionTable *flatcorr, int ID, int X, int Y) {
    186186
     187  if (!flatcorr) return 0.0;
     188
    187189  // validate the flat_id (not out of range?)
    188190  int seq = flatcorr->IDtoSeq[ID];
  • trunk/Ohana/src/libohana/include/ohana_sort.h

    r27435 r33963  
    7373void fsortthree (float *X, float *Y, float *Z, int N);
    7474void dsortthree (double *X, double *Y, double *Z, int N);
     75void fsortfour (float *X, float *Y, float *Z, float *W, int N);
     76void dsortfour (double *X, double *Y, double *Z, double *W, int N);
    7577
    7678#endif
  • trunk/Ohana/src/libohana/src/rconnect.c

    r33779 r33963  
    6262
    6363  pid = fork ();
     64  if (pid < 0) {
     65    perror ("fork:");
     66    fprintf (stderr, "error forking child process\n");
     67    exit (3);
     68  }
    6469  if (!pid) { /* must be child process */
    6570    if (DEBUG) fprintf (stderr, "starting remote connection to %s...", hostname);
  • trunk/Ohana/src/libohana/src/sorts.c

    r27435 r33963  
    120120
    121121}
     122
     123void fsortfour (float *X, float *Y, float *Z, float *W, int N) {
     124
     125# define SWAPFUNC(A,B){ float tmp; \
     126  tmp = X[A]; X[A] = X[B]; X[B] = tmp; \
     127  tmp = Y[A]; Y[A] = Y[B]; Y[B] = tmp; \
     128  tmp = Z[A]; Z[A] = Z[B]; Z[B] = tmp; \
     129  tmp = W[A]; W[A] = W[B]; W[B] = tmp; \
     130}
     131# define COMPARE(A,B)(X[A] < X[B])
     132
     133  OHANA_SORT (N, COMPARE, SWAPFUNC);
     134
     135# undef SWAPFUNC
     136# undef COMPARE
     137
     138}
     139
     140void dsortfour (double *X, double *Y, double *Z, double *W, int N) {
     141
     142# define SWAPFUNC(A,B){ double tmp; \
     143  tmp = X[A]; X[A] = X[B]; X[B] = tmp; \
     144  tmp = Y[A]; Y[A] = Y[B]; Y[B] = tmp; \
     145  tmp = Z[A]; Z[A] = Z[B]; Z[B] = tmp; \
     146  tmp = W[A]; W[A] = W[B]; W[B] = tmp; \
     147}
     148# define COMPARE(A,B)(X[A] < X[B])
     149
     150  OHANA_SORT (N, COMPARE, SWAPFUNC);
     151
     152# undef SWAPFUNC
     153# undef COMPARE
     154
     155}
  • trunk/Ohana/src/libohana/src/string.c

    r33646 r33963  
    134134    line[i] = c;
    135135  }
     136  if (ferror(f)) {
     137    perror("scan_line: ");
     138    return EOF;
     139  }
    136140  line[i - 1] = 0;  /* this could make things crash! */
    137141
  • trunk/Ohana/src/opihi/cmd.astro

  • trunk/Ohana/src/opihi/cmd.astro/Makefile

    r33662 r33963  
    4646$(SRC)/ringflux.$(ARCH).o          \
    4747$(SRC)/petrosian.$(ARCH).o         \
     48$(SRC)/kronflux.$(ARCH).o          \
    4849$(SRC)/multifit.$(ARCH).o          \
    4950$(SRC)/objload.$(ARCH).o           \
  • trunk/Ohana/src/opihi/cmd.astro/init.c

    r33662 r33963  
    3232int ringflux                PROTO((int, char **));
    3333int petrosian               PROTO((int, char **));
     34int kronflux                PROTO((int, char **));
    3435int mkgauss                 PROTO((int, char **));
    3536int mksersic                PROTO((int, char **));
     
    8889  {1, "ringflux",    ringflux,     "mean flux in a ring"},
    8990  {1, "petrosian",   petrosian,    "petrosian parameters given radial bins"},
     91  {1, "kronflux",    kronflux,     "measure kronflux stats"},
    9092  {1, "multifit",    multifit,     "fit multi-order spectrum"},
    9193  {1, "objload",     objload,      "plot obj data on Ximage "},
  • trunk/Ohana/src/opihi/cmd.basic/Makefile

    r31635 r33963  
    4444$(SRC)/quit.$(ARCH).o        \
    4545$(SRC)/run_for.$(ARCH).o    \
     46$(SRC)/run_foreach.$(ARCH).o    \
    4647$(SRC)/run_if.$(ARCH).o     \
    4748$(SRC)/run_while.$(ARCH).o  \
  • trunk/Ohana/src/opihi/cmd.basic/init.c

    r27255 r33963  
    3131int quit            PROTO((int, char **));
    3232int run_for         PROTO((int, char **));
     33int run_foreach     PROTO((int, char **));
    3334int run_if          PROTO((int, char **));
    3435int run_while       PROTO((int, char **));
     
    8182  {1, "quit",          quit,               "exit program *"},
    8283  {1, "for",           run_for,            "for loop"},
     84  {1, "foreach",       run_foreach,        "foreach loop"},
    8385  {1, "if",            run_if,             "logical cases *"},
    8486  {1, "while",         run_while,          "while loop"},
  • trunk/Ohana/src/opihi/cmd.basic/input.c

    r7917 r33963  
    4040  fclose (infile);
    4141
     42  if (!inlist.Nlines) gprint (GP_ERR, "WARNING: input file (%s) was empty\n", argv[1]);
     43
    4244  /* process this list */
    4345  status = exec_loop (&inlist);
  • trunk/Ohana/src/opihi/cmd.basic/run_for.c

    r31667 r33963  
    55int run_for (int argc, char **argv) {
    66
    7   int ThisList, depth, i, done, status, found, NLINES, j;
     7  int N, ThisList, depth, i, done, status, found, NLINES, j;
    88  double start, end, delta;
    99  char *input, *endptr;
    1010  double value, sign;
    1111  Macro loop;
     12
     13  int Inclusive = FALSE;
     14  if ((N = get_argument (argc, argv, "-incl"))) {
     15    remove_argument (N, &argc, argv);
     16    Inclusive = TRUE;
     17  }
    1218
    1319  if ((argc != 4) && (argc != 5)) {
     
    95101  REALLOCATE (loop.line, char *, MAX (loop.Nlines, 1));
    96102
     103  if (Inclusive) end += 0.01*delta;
     104
    97105  status = TRUE;
    98106  interrupt = FALSE;
  • trunk/Ohana/src/opihi/cmd.data/dot.c

    r14181 r33963  
    33int dot (int argc, char **argv) {
    44 
    5   int kapa;
     5  int kapa, N;
    66  Graphdata graphmode;
    77  float x, y;
    88
    99  if (!style_args (&graphmode, &argc, argv, &kapa)) return FALSE;
     10
     11  /* FracPositions uses coordinates of 0-1 relative to axis range */
     12  int FracPositions = FALSE;
     13  if ((N = get_argument (argc, argv, "-frac"))) {
     14    remove_argument (N, &argc, argv);
     15    FracPositions = TRUE;
     16  }
    1017
    1118  if (argc != 3) {
     
    1522  x = atof(argv[1]);
    1623  y = atof(argv[2]);
     24
     25  if (FracPositions) {
     26    x =  x * (graphmode.xmax - graphmode.xmin) + graphmode.xmin;
     27    y =  y * (graphmode.ymax - graphmode.ymin) + graphmode.ymin;
     28  }   
    1729
    1830  /* set point style and errorbar mode (these are NOT sticky) */
  • trunk/Ohana/src/opihi/cmd.data/gridify.c

    r31450 r33963  
    55  int i, Nx, Ny, Xb, Yb, Normalize, N;
    66  float Xmin, Xmax, dX, Ymin, Ymax, dY, initValue;
    7   float *buf, *val;
     7  float *buf, *val, *cnt;
    88  int *Nval;
    9   Buffer *bf;
    109  Vector *vx, *vy, *vz;
    1110  opihi_flt *x, *y, *z;
     11
     12  Buffer *bf = NULL;
     13  Buffer *ct = NULL;
    1214
    1315  Normalize = TRUE;
     
    1517    remove_argument (N, &argc, argv);
    1618    Normalize = FALSE;
     19    if ((ct = SelectBuffer (argv[N], ANYBUFFER, TRUE)) == NULL) return (FALSE);
     20    remove_argument (N, &argc, argv);
    1721  }
    1822
     
    2428  }
    2529
    26   if (argc != 11) {
    27     gprint (GP_ERR, "USAGE: gridify x y z buffer Xmin Xmax dX Ymin Ymax dY\n");
     30  Xmin = Xmax = dX = NAN;
     31  if ((N = get_argument (argc, argv, "-x"))) {
     32    remove_argument (N, &argc, argv);
     33    Xmin = atof (argv[N]);
     34    remove_argument (N, &argc, argv);
     35    Xmax = atof (argv[N]);
     36    remove_argument (N, &argc, argv);
     37    dX   = atof (argv[N]);
     38    remove_argument (N, &argc, argv);
     39  }   
     40
     41  Ymin = Ymax = dY = NAN;
     42  if ((N = get_argument (argc, argv, "-y"))) {
     43    remove_argument (N, &argc, argv);
     44    Ymin = atof (argv[N]);
     45    remove_argument (N, &argc, argv);
     46    Ymax = atof (argv[N]);
     47    remove_argument (N, &argc, argv);
     48    dY   = atof (argv[N]);
     49    remove_argument (N, &argc, argv);
     50  }   
     51
     52  if (argc != 5) {
     53    gprint (GP_ERR, "USAGE: gridify x y z buffer [-x Xmin Xmax dX] [-y Ymin Ymax dY] [-init-value value] [-raw]\n");
    2854    return (FALSE);
    2955  }
     
    4167  REQUIRE_VECTOR_FLT (vz, FALSE);
    4268
    43   Xmin = atof (argv[5]);
    44   Xmax = atof (argv[6]);
    45   dX   = atof (argv[7]);
     69  if (isnan(dX)) {
     70    Xmin = 0;
     71    Xmax = bf[0].matrix.Naxis[0];
     72    dX = 1;
     73  }
    4674
    47   Ymin = atof (argv[8]);
    48   Ymax = atof (argv[9]);
    49   dY   = atof (argv[10]);
     75  if (isnan(dY)) {
     76    Ymin = 0;
     77    Ymax = bf[0].matrix.Naxis[1];
     78    dY = 1;
     79  }
    5080
    51   Nx = (Xmax - Xmin) / dX + 1;
    52   Ny = (Ymax - Ymin) / dY + 1;
     81  Nx = (Xmax - Xmin) / dX;
     82  Ny = (Ymax - Ymin) / dY;
    5383 
    54   gfits_free_matrix (&bf[0].matrix);
    55   gfits_free_header (&bf[0].header);
    56   CreateBuffer (bf, Nx, Ny, -32, 0.0, 1.0);
    57   strcpy (bf[0].file, "(empty)");
     84  if ((Nx != bf[0].matrix.Naxis[0]) || (Ny != bf[0].matrix.Naxis[1])) {
     85    gfits_free_matrix (&bf[0].matrix);
     86    gfits_free_header (&bf[0].header);
     87    CreateBuffer (bf, Nx, Ny, -32, 0.0, 1.0);
     88    strcpy (bf[0].file, "(empty)");
     89  }
    5890
    5991  ALLOCATE (val, float, Nx*Ny);
     
    68100    Xb = (*x - Xmin) / dX;
    69101    Yb = (*y - Ymin) / dY;
     102    if (Xb < 0) continue;
     103    if (Yb < 0) continue;
    70104    if (Xb >= Nx) continue;
    71105    if (Yb >= Ny) continue;
     
    74108  }
    75109
     110  if (!Normalize) {
     111    gfits_free_matrix (&ct[0].matrix);
     112    gfits_free_header (&ct[0].header);
     113    CreateBuffer (ct, Nx, Ny, -32, 0.0, 1.0);
     114    strcpy (ct[0].file, "(empty)");
     115
     116    buf = (float *) bf[0].matrix.buffer;
     117    cnt = (float *) ct[0].matrix.buffer;
     118    for (i = 0; i < Nx*Ny; i++) {
     119      if (Nval[i] == 0) continue;
     120      buf[i] = val[i];
     121      cnt[i] = Nval[i];
     122    }
     123    free (val);
     124    free (Nval);
     125    return TRUE;
     126  }
     127
    76128  buf = (float *) bf[0].matrix.buffer;
    77129  for (i = 0; i < Nx*Ny; i++) {
    78130    buf[i] = initValue;
    79     if (Normalize) {
    80       if (Nval[i] == 0) {
    81         continue;
    82       }
    83       buf[i] = val[i] / Nval[i];
    84     } else {
    85       buf[i] = val[i];
    86     }
     131    if (Nval[i] == 0) continue;
     132    buf[i] = val[i] / Nval[i];
    87133  }
    88134
  • trunk/Ohana/src/opihi/cmd.data/match2d.c

    r30610 r33963  
    167167  NMATCH = X1->Nelements;
    168168  ResetVector (index, OPIHI_INT, NMATCH);
     169
     170  for (i = 0; i < index->Nelements; i++) { index->elements.Int[i] = -1; }
    169171
    170172  ALLOCATE (N1, off_t, X1->Nelements);
  • trunk/Ohana/src/opihi/cmd.data/threshold.c

    r33662 r33963  
    6969    x0 = isFltX ? vecx[0].elements.Flt[Nhi] : vecy[0].elements.Int[Nhi];
    7070    x1 = isFltX ? vecx[0].elements.Flt[Nhi+1]   : vecy[0].elements.Int[Nhi+1];
    71     Xvalue = (value - y0) * (x1 - x0) / (y1 - y0) + x0;
     71    if (y0 == y1) {
     72      Xvalue = 0.5*(x0 + x1);
     73    } else {
     74      Xvalue = (value - y0) * (x1 - x0) / (y1 - y0) + x0;
     75    }   
    7276  } else {
    7377    // interpolate to value:
     
    7680    x0 = isFltX ? vecx[0].elements.Flt[Nhi-1] : vecy[0].elements.Int[Nhi-1];
    7781    x1 = isFltX ? vecx[0].elements.Flt[Nhi]   : vecy[0].elements.Int[Nhi];
    78     Xvalue = (value - y0) * (x1 - x0) / (y1 - y0) + x0;
     82    if (y0 == y1) {
     83      Xvalue = 0.5*(x0 + x1);
     84    } else {
     85      Xvalue = (value - y0) * (x1 - x0) / (y1 - y0) + x0;
     86    }
    7987  }
    8088
  • trunk/Ohana/src/opihi/cmd.data/vgroup.c

    r25757 r33963  
    11# include "data.h"
     2
     3enum {USE_MEDIAN, USE_COUNT, USE_SUM, USE_MEAN};
    24
    35int vgroup (int argc, char **argv) {
     
    2325  // }
    2426
     27  int mode = USE_MEDIAN;
     28  if ((N = get_argument (argc, argv, "-sum"))) {
     29    remove_argument (N, &argc, argv);
     30    mode = USE_SUM;
     31  }
     32  if ((N = get_argument (argc, argv, "-mean"))) {
     33    remove_argument (N, &argc, argv);
     34    mode = USE_MEAN;
     35  }
     36
     37  float binsize = NAN;
     38  if ((N = get_argument (argc, argv, "-binsize"))) {
     39    remove_argument (N, &argc, argv);
     40    binsize = atof(argv[N]);
     41    remove_argument (N, &argc, argv);
     42  }
     43
    2544  if (argc != 5) {
    26     gprint (GP_ERR, "USAGE: vbin <xin> <yin> <xout> <yout>\n");
     45    gprint (GP_ERR, "USAGE: vgroup <xin> <yin> <xout> <yout>\n");
    2746    gprint (GP_ERR, " group x,y values in bins defined by <xout>\n");
     47    gprint (GP_ERR, " by default, yout has the median of the associated input values\n");
     48    gprint (GP_ERR, " use -sum to add values in the bin\n");
     49    gprint (GP_ERR, " use <yin> = histogram count matching values\n");
     50    gprint (GP_ERR, " use -binsize to specify a fixed bin width (<xout> will define the bin center)\n");
    2851    return (FALSE);
    2952  }
    3053
    3154  if ((xin  = SelectVector (argv[1], OLDVECTOR, TRUE)) == NULL) return (FALSE);
    32   if ((yin  = SelectVector (argv[2], OLDVECTOR, TRUE)) == NULL) return (FALSE);
    3355  if ((xout = SelectVector (argv[3], OLDVECTOR, TRUE)) == NULL) return (FALSE);
    3456  if ((yout = SelectVector (argv[4], ANYVECTOR, TRUE)) == NULL) return (FALSE);
     57  yin = NULL;
     58
     59  // this should conflict with the -sum option...
     60  if (!strcmp(argv[2], "histogram")) {
     61    mode = USE_COUNT;
     62  } else {
     63    if ((yin  = SelectVector (argv[2], OLDVECTOR, TRUE)) == NULL) return (FALSE);
     64  }
    3565
    3666  // re-binning creates a float vector
     
    4171
    4272  for (i = 0; i < xout[0].Nelements - 1; i++) {
    43     xmin = xout[0].elements.Flt[i];
    44     xmax = xout[0].elements.Flt[i+1];
     73    if (isnan(binsize)) {
     74      xmin = xout[0].elements.Flt[i];
     75      xmax = xout[0].elements.Flt[i+1];
     76    } else {
     77      xmin = xout[0].elements.Flt[i] - 0.5*binsize;
     78      xmax = xout[0].elements.Flt[i] + 0.5*binsize;
     79    }
    4580
    4681    N = 0;
     
    4883      if (xin[0].elements.Flt[j] < xmin) continue;
    4984      if (xin[0].elements.Flt[j] > xmax) continue;
    50       values[N] = yin[0].elements.Flt[j];
     85      if (yin) {
     86        values[N] = yin[0].elements.Flt[j];
     87      }
    5188      N++;
    5289    }
    5390   
    54     dsort (values, N);
    55     if (N > 1) {
    56       sum = (N % 2) ? values[(int)(0.5*N)] : 0.5*(values[N/2] + values[N/2 + 1]);
    57     } else {
    58       sum = values[0];
     91    sum = NAN;
     92    switch (mode) {
     93      case USE_MEDIAN:
     94        dsort (values, N);
     95        if (N > 1) {
     96          sum = (N % 2) ? values[(int)(0.5*N)] : 0.5*(values[N/2] + values[N/2 + 1]);
     97        } else {
     98          sum = values[0];
     99        }
     100        break;
     101
     102      case USE_SUM:
     103        sum = 0.0;
     104        for (j = 0; j < N; j++) {
     105          sum += values[j];
     106        }
     107        break;
     108       
     109      case USE_COUNT:
     110        sum = N;
     111        break;
     112
     113      case USE_MEAN:
     114        sum = 0.0;
     115        for (j = 0; j < N; j++) {
     116          sum += values[j];
     117        }
     118        sum /= N;
     119        break;
    59120    }
    60 
    61     // measure the stat for this bin
    62     // sum = 0.0;
    63     // for (j = 0; j < N; j++) {
    64     //   sum += values[j];
    65     // }
    66     // sum /= N;
    67121    yout[0].elements.Flt[i] = sum;
    68122  }
  • trunk/Ohana/src/opihi/cmd.data/vstats.c

    r32632 r33963  
    144144      }     
    145145    }
    146     stdev = sqrt (var / N);
     146    stdev = sqrt (var / (N - 1));
    147147
    148148    Nmode = 0;
  • trunk/Ohana/src/opihi/cmd.data/write_vectors.c

    r33662 r33963  
    2121  FITS = NULL;
    2222  if ((N = get_argument (argc, argv, "-fits"))) {
     23    if (format) {
     24      gprint (GP_ERR, "ERROR: do not mix -fits and -format\n");
     25      free (format);
     26      return (FALSE);
     27    }
    2328    remove_argument (N, &argc, argv);
    2429    FITS = strcreate (argv[N]);
    2530    remove_argument (N, &argc, argv);
     31  }
     32
     33  /* option generate a FITS output table */
     34  int CSV = FALSE;
     35  if ((N = get_argument (argc, argv, "-csv"))) {
     36    if (format) {
     37      gprint (GP_ERR, "ERROR: do not mix -csv and -format\n");
     38      free (format);
     39      return (FALSE);
     40    }
     41    if (FITS) {
     42      gprint (GP_ERR, "ERROR: do not mix -csv and -fits\n");
     43      free (FITS);
     44      return (FALSE);
     45    }
     46    remove_argument (N, &argc, argv);
     47    CSV = TRUE;
    2648  }
    2749
     
    3052    remove_argument (N, &argc, argv);
    3153    append = TRUE;
     54  }
     55
     56  int ADD_HEADER = FALSE;
     57  if ((N = get_argument (argc, argv, "-header"))) {
     58    remove_argument (N, &argc, argv);
     59    ADD_HEADER = TRUE;
    3260  }
    3361
     
    83111
    84112  /* default output format */
     113  if (ADD_HEADER) {
     114    for (j = 0; j < Nvec; j++) {
     115      if (CSV) {
     116        fprintf (f, "%s,", vec[j][0].name);
     117      } else {
     118        if (j == 0) fprintf (f, "# ");
     119        fprintf (f, "%s ", vec[j][0].name);
     120      }
     121    }
     122    fprintf (f, "\n");
     123  }
     124
     125  /* default output format */
    85126  if (format == (char *) NULL) {
    86127    for (i = 0; i < vec[0][0].Nelements; i++) {
    87128      for (j = 0; j < Nvec; j++) {
    88129        if (vec[j][0].type == OPIHI_FLT) {
    89           fprintf (f, "%.12g ", vec[j][0].elements.Flt[i]);
     130          if (CSV) {
     131            fprintf (f, "%.12g,", vec[j][0].elements.Flt[i]);
     132          } else {
     133            fprintf (f, "%.12g ", vec[j][0].elements.Flt[i]);
     134          }
    90135        } else {
    91           fprintf (f, "%d ", vec[j][0].elements.Int[i]);
     136          if (CSV) {
     137            fprintf (f, "%d,", vec[j][0].elements.Int[i]);
     138          } else {
     139            fprintf (f, "%d ", vec[j][0].elements.Int[i]);
     140          }
    92141        }
    93142      }
  • trunk/Ohana/src/opihi/dvo/avextract.c

    r33662 r33963  
    3737  }
    3838
     39  int VERBOSE2 = FALSE;
     40  if ((N = get_argument (argc, argv, "-vv"))) {
     41    remove_argument (N, &argc, argv);
     42    VERBOSE = TRUE;
     43    VERBOSE2 = TRUE;
     44  }
     45
    3946  int PARALLEL = FALSE;
    4047  if ((N = get_argument (argc, argv, "-parallel"))) {
     
    6572      return FALSE;
    6673    }   
     74  }
     75
     76  // this is used to NOT save the results in the results file
     77  // use this option when mextract is used in a script which does its
     78  // own job of packaging the results
     79  int SKIP_RESULTS = FALSE;
     80  if ((N = get_argument (argc, argv, "-skip-results"))) {
     81    remove_argument (N, &argc, argv);
     82    SKIP_RESULTS = TRUE;
    6783  }
    6884
     
    8096    goto escape;
    8197  }
     98
     99  // init locally static variables (time refs)
     100  dbExtractAveragesInit ();
    82101
    83102  // command-line is of the form: avextract field,field, field [where (field op value)...]
     
    173192    catalog.filename = (HOST_ID || PARALLEL_LOCAL) ? hostfile : skylist[0].filename[i];
    174193    catalog.catflags = LOAD_AVES | LOAD_SECF;
    175     if (needMeasures) {
    176       catalog.catflags |= LOAD_MEAS;
    177     }
     194    catalog.catflags |= needMeasures ? LOAD_MEAS : SKIP_MEAS;
    178195    catalog.Nsecfilt = 0;
    179196
     
    181198     
    182199    // an error exit status here is a significant error
    183     if (!dvo_catalog_open (&catalog, NULL, FALSE, "r")) {
     200    if (!dvo_catalog_open (&catalog, NULL, VERBOSE2, "r")) {
    184201      gprint (GP_ERR, "ERROR: failure to open catalog file %s\n", catalog.filename);
    185202      exit (2);
     
    193210      m = catalog.average[j].measureOffset;
    194211
    195       // reset counters for saved fields, extract fields
    196       dbExtractAveragesInit ();
     212      dbExtractAveragesInitAve ();  // reset counters for saved fields (costs very little)
     213
    197214      for (n = 0; n < Nfields; n++) {
    198215        values[n] = dbExtractAverages (&catalog.average[j], &catalog.secfilt[j*Nsecfilt], &catalog.measure[m], &fields[n]);
     
    229246
    230247  // write vectors to a table (this is used by parallel dvo operations, but can be used elsewhere)
    231   if (RESULT_FILE) {
     248  if (RESULT_FILE && !SKIP_RESULTS) {
    232249    int status = WriteVectorTableFITS (RESULT_FILE, "RESULT", vec, Nreturn, FALSE, NULL);
    233     if (!status) goto escape;
     250    if (!status) {
     251      goto escape;
     252    }
    234253  }
    235254
  • trunk/Ohana/src/opihi/dvo/avmatch.c

    r33662 r33963  
    6666  if (!InitPhotcodes ()) goto escape;
    6767  Nsecfilt = GetPhotcodeNsecfilt ();
     68
     69  // init locally static variables (time refs)
     70  dbExtractAveragesInit ();
    6871
    6972  // this does all the work of re-packaging the command, calling it on the remote machines, then loading in the results
     
    129132  }
    130133
     134  // check the requested fields : are all average/secfilt entries, or do we need measures?
     135  int needMeasures = FALSE;
     136  for (i = 0; !needMeasures && (i < Nfields); i++) {
     137    if (fields[i].magMode == MAG_NONE) continue;
     138    if (fields[i].photcode == NULL) continue; // assert this?
     139    if (fields[i].photcode[0].type == PHOT_REF) needMeasures = TRUE;
     140    if (fields[i].photcode[0].type == PHOT_DEP) needMeasures = TRUE;
     141  }
     142
    131143  /* load regions which contain all supplied RA,DEC coordinates */
    132144  if ((skylist = SelectRegionsByCoordVectors (RAvec, DECvec)) == NULL) goto escape;
     
    168180    snprintf (hostfile, 1024, "%s/%s.cpt", HOSTDIR, skylist[0].regions[i]->name);
    169181    catalog.filename = HOST_ID ? hostfile : skylist[0].filename[i];
    170     catalog.catflags = LOAD_AVES | LOAD_MEAS | LOAD_SECF;
     182    catalog.catflags = LOAD_AVES | LOAD_SECF;
     183    catalog.catflags |= needMeasures ? LOAD_MEAS : SKIP_MEAS;
    171184    catalog.Nsecfilt = 0;
    172185
     
    196209
    197210      // reset counters for saved fields, extract fields
    198       dbExtractAveragesInit ();
     211      dbExtractAveragesInitAve ();
    199212      for (n = 0; n < Nfields; n++) {
    200213        values[n] = dbExtractAverages (&catalog.average[Ncat], &catalog.secfilt[Ncat*Nsecfilt], &catalog.measure[m], &fields[n]);
  • trunk/Ohana/src/opihi/dvo/dvo_client.c

    r33662 r33963  
    9898
    9999  int status = input (2, &argv[0]);
    100   if (!status) exit (2);
     100  if (!status) {
     101    fprintf (stderr, "WARNING: exit status 2 %d (%s)\n", HOST_ID, HOSTDIR);
     102    exit (2);
     103  }
    101104  exit (0);
    102105
  • trunk/Ohana/src/opihi/dvo/dvo_host_utils.c

    r33662 r33963  
    44# define PARALLEL_MANUAL 0
    55# define PARALLEL_SERIAL 0
    6 # define MAX_PATH_LENGTH 1024
    7 
    8 int HostTableLaunchJobs (HostTable *table, char *basecmd, char *options) {
     6# define DVO_MAX_PATH 1024
     7
     8# define DIE(WHO,MSG) { perror(WHO); myAbort(MSG); }
     9
     10int HostTableLaunchJobs (HostTable *table, char *basecmd, char *options, int VERBOSE) {
    911
    1012  char uniquer[12];
     
    1315  snprintf (uniquer, 12, "%05d.%05d", PID, TIME % 100000);
    1416
     17  int top_status = TRUE;
    1518  int i;
    1619  for (i = 0; i < table->Nhosts; i++) {
    1720
    1821    // ensure that the paths are absolute path names
    19     char *tmppath = abspath (table->hosts[i].pathname, MAX_PATH_LENGTH);
     22    char *tmppath = abspath (table->hosts[i].pathname, DVO_MAX_PATH);
    2023    free (table->hosts[i].pathname);
    2124    table->hosts[i].pathname = tmppath;
     
    2326    // need to save the results filename with the uniquer
    2427    // XXX a bit of a waste (but only 1024 * 60 bytes or so
    25     ALLOCATE (table->hosts[i].results, char, MAX_PATH_LENGTH);
    26     snprintf (table->hosts[i].results, MAX_PATH_LENGTH, "%s/dvo.results.%s.fits", table->hosts[i].pathname, uniquer);
    27 
    28     char commandBase[MAX_PATH_LENGTH];
    29     snprintf (commandBase, MAX_PATH_LENGTH, "dvo.command.%s.txt", uniquer);
    30     char *commandFile = abspath(commandBase, MAX_PATH_LENGTH);
     28    ALLOCATE (table->hosts[i].results, char, DVO_MAX_PATH);
     29    snprintf (table->hosts[i].results, DVO_MAX_PATH, "%s/dvo.results.%s.fits", table->hosts[i].pathname, uniquer);
     30
     31    char commandBase[DVO_MAX_PATH];
     32    snprintf (commandBase, DVO_MAX_PATH, "dvo.command.%s.txt", uniquer);
     33    char *commandFile = abspath(commandBase, DVO_MAX_PATH);
    3134
    3235    FILE *f = fopen (commandFile, "w");
    3336    fprintf (f, "%s\n", basecmd);
    34     fclose (f);
     37    if (fflush (f)) DIE("flush", "failed to flush");
     38
     39    int fd = fileno (f);
     40    if (fsync (fd)) DIE("fsync", "failed to fsync");
     41
     42    if (fclose (f)) DIE("close", "failed to close");
     43
     44    // force NFS to write the file to disk
     45    int state;
     46    f = fsetlockfile (commandFile, 0.5, LCK_XCLD, &state);
     47    fclearlockfile (commandFile, f, LCK_XCLD, &state);
    3548
    3649    char command[1024];
     
    3851    free (commandFile);
    3952
    40     if (DEBUG || PARALLEL_MANUAL) fprintf (stderr, "command: %s\n", command);
     53    if (VERBOSE) gprint (GP_ERR, "command: %s\n", command);
    4154
    4255    if (PARALLEL_MANUAL) {
     
    4760      int status = system (command);
    4861      if (status) {
    49         fprintf (stderr, "ERROR running relphot_client\n");
    50         exit (2);
     62        gprint (GP_ERR, "ERROR running relphot_client\n");
     63        top_status = FALSE;
    5164      }
    5265    } else {
     
    5568      int pid = rconnect ("ssh", table->hosts[i].hostname, command, table->hosts[i].stdio, &errorInfo, FALSE);
    5669      if (!pid) {
    57         if (DEBUG) fprintf (stderr, "failure to start %s (error %d)\n", table->hosts[i].hostname, errorInfo);
    58         exit (1);
     70        gprint (GP_ERR, "failure to start %s (error %d)\n", table->hosts[i].hostname, errorInfo);
     71        top_status = FALSE;
     72        continue;
    5973      }
    6074      table->hosts[i].pid = pid; // save for future reference
    6175    }
    6276  }
    63   return TRUE;
     77  return top_status;
    6478}
    6579
     
    86100  }
    87101
    88   char *CATDIR = abspath (tmppath, MAX_PATH_LENGTH);
     102  char *CATDIR = abspath (tmppath, DVO_MAX_PATH);
    89103  if (!CATDIR) {
    90104    gprint (GP_ERR, "failed to make an absolute path from %s (too long)\n", tmppath);
     
    126140
    127141  // launch this command remotely
    128   HostTableLaunchJobs (table, basecmd, options);
     142  HostTableLaunchJobs (table, basecmd, options, VERBOSE);
    129143  free (options);
    130144  free (basecmd);
     
    184198  return TRUE;
    185199}
     200
     201// re-gather the remote results files: this can be used in case one of the clients failed,
     202// and has since been re-run
     203int HostTableReloadResults (char *uniquer, int VERBOSE) {
     204
     205  int i;
     206
     207  // load the list of hosts
     208  SkyTable *sky = GetSkyTable();
     209  if (!sky) {
     210    gprint (GP_ERR, "failed to load sky table for database\n");
     211    return FALSE;
     212  }
     213
     214  char *CATDIR = GetCATDIR ();
     215  if (!CATDIR) {
     216    gprint (GP_ERR, "failed to get CATDIR for database\n");
     217    return FALSE;
     218  }
     219
     220  HostTable *table = HostTableLoad (CATDIR, sky->hosts);
     221  if (!table) {
     222    gprint (GP_ERR, "ERROR: failure reading Host Table %s for database %s\n", sky->hosts, CATDIR);
     223    return FALSE;
     224  }   
     225
     226  // load fields from file
     227  int    Nvec = 0;
     228  Vector **vec = NULL;
     229  for (i = 0; i < table->Nhosts; i++) {
     230    // ensure that the paths are absolute path names
     231    char *tmppath = abspath (table->hosts[i].pathname, DVO_MAX_PATH);
     232    free (table->hosts[i].pathname);
     233    table->hosts[i].pathname = tmppath;
     234
     235    // need to save the results filename with the uniquer
     236    // XXX a bit of a waste (but only 1024 * 60 bytes or so
     237    ALLOCATE (table->hosts[i].results, char, DVO_MAX_PATH);
     238    snprintf (table->hosts[i].results, DVO_MAX_PATH, "%s/dvo.results.%s.fits", table->hosts[i].pathname, uniquer);
     239
     240    int    Ninvec = 0;
     241    Vector **invec = ReadVectorTableFITS (table->hosts[i].results, "RESULT", &Ninvec);
     242    if (!invec) {
     243      // failed to read the file, now what?
     244      gprint (GP_ERR, "failed to read remote result file : %s\n", table->hosts[i].results);
     245      free (table->hosts[i].results);
     246      table->hosts[i].results = NULL;
     247      continue;
     248    }
     249    free (table->hosts[i].results);
     250    table->hosts[i].results = NULL;
     251
     252    // fprintf (stderr, "%s : %d\n", table->hosts[i].pathname, invec[0]->Nelements);
     253
     254    vec = MergeVectors (vec, &Nvec, invec, Ninvec);
     255    if (vec != invec) {
     256      FreeVectorArray (invec, Ninvec);
     257    }
     258  }
     259
     260  for (i = 0; i < Nvec; i++) {
     261    AssignVector (vec[i], vec[i]->name, ANYVECTOR, TRUE);
     262  }
     263  free (vec);
     264
     265  free (table);
     266  return TRUE;
     267}
  • trunk/Ohana/src/opihi/dvo/gstar.c

    r33662 r33963  
    116116
    117117  /* lock, load, unlock catalog */
    118   catalog.catflags = GetMeasures ? LOAD_AVES | LOAD_MEAS | LOAD_SECF : LOAD_AVES | LOAD_SECF;
     118  catalog.catflags = LOAD_AVES | LOAD_SECF;
     119  catalog.catflags |= GetMeasures ? LOAD_MEAS : SKIP_MEAS;
    119120  catalog.Nsecfilt = 0;
    120121
  • trunk/Ohana/src/opihi/dvo/hosts.c

    r33662 r33963  
    11# include "dvoshell.h"
    22# include <glob.h>
    3 # define MAX_PATH_LENGTH 1024
     3# define DVO_MAX_PATH 1024
    44
    55// functions to manage the remote hosts
     
    5959    for (i = 0; i < table->Nhosts; i++) {
    6060      pglob.gl_offs = 0;
    61       char name[MAX_PATH_LENGTH];
    62       snprintf (name, MAX_PATH_LENGTH, "%s/dvo.results.%05d.*.fits", table->hosts[i].pathname, PID);
     61      char name[DVO_MAX_PATH];
     62      snprintf (name, DVO_MAX_PATH, "%s/dvo.results.%05d.*.fits", table->hosts[i].pathname, PID);
    6363      if (VERBOSE) gprint (GP_ERR, "checking %s\n", name);
    6464      glob (name, 0, NULL, &pglob);
  • trunk/Ohana/src/opihi/dvo/mextract.c

    r33662 r33963  
    189189      }
    190190
    191       dbExtractMeasuresInitAve (); // reset counters for saved fields (costs very little
     191      dbExtractMeasuresInitAve (); // reset counters for saved fields (costs very little)
    192192
    193193      for (k = 0; (k < catalog.average[j].Nmeasure); k++, m++) {
  • trunk/Ohana/src/opihi/dvo/remote.c

    r33662 r33963  
    11# include "dvoshell.h"
    22# include <glob.h>
    3 # define MAX_PATH_LENGTH 1024
     3# define DVO_MAX_PATH 1024
    44
    55// functions to manage the remote hosts
     
    88  int N;
    99
     10  int VERBOSE = FALSE;
     11  if ((N = get_argument (argc, argv, "-v"))) {
     12    remove_argument (N, &argc, argv);
     13    VERBOSE = TRUE;
     14  }
     15
    1016  if (argc < 2) {
    1117    gprint (GP_ERR, "USAGE: remote (command)\n");
     
    1319    gprint (GP_ERR, "  options:\n");
    1420    gprint (GP_ERR, "  -v : verbose mode:\n");
     21    gprint (GP_ERR, "OR:    remote -reload (uniquer)\n");
    1522    return FALSE;
    1623  }
     
    2330  // with a set of vectors to load.
    2431
    25   int VERBOSE = FALSE;
    26   if ((N = get_argument (argc, argv, "-v"))) {
     32  if ((N = get_argument (argc, argv, "-reload"))) {
    2733    remove_argument (N, &argc, argv);
    28     VERBOSE = TRUE;
     34    if (argc != 2) {
     35      gprint (GP_ERR, "USAGE: remote -reload (uniquer)\n");
     36      gprint (GP_ERR, " (uniquer) is the element in the middle of the results file\n");
     37      gprint (GP_ERR, " eg: dvo.results.XXXXX.YYYYY.fits\n");
     38      return FALSE;
     39    }
     40    int status = HostTableReloadResults (argv[1], VERBOSE);
     41    return status;
    2942  }
    3043
  • trunk/Ohana/src/opihi/dvo/skycoverage.c

    r33662 r33963  
    22
    33// enum to define possible modes
    4 enum {COVERAGE, DENSITY, MIN_UBERCAL, MIN_DMAG_SYS, MIN_MCAL, MAX_MCAL};
     4enum {COVERAGE, DENSITY, MIN_UBERCAL, MIN_DMAG_SYS, MIN_MCAL, MAX_MCAL, MIN_TIME, MAX_TIME};
    55
    66int wordhash (char *word);
     
    2323  PhotCode *PhotcodeValue;
    2424
     25  time_t TimeReference;
     26  int TimeFormat;
     27
     28  GetTimeFormat (&TimeReference, &TimeFormat);
     29
    2530  WITH_MOSAIC = FALSE;
    2631  if ((N = get_argument (argc, argv, "+mosaic"))) {
     
    7176    remove_argument (N, &argc, argv);
    7277    mode = MIN_UBERCAL;
     78  }
     79  if ((N = get_argument (argc, argv, "-min-time"))) {
     80    remove_argument (N, &argc, argv);
     81    mode = MIN_TIME;
     82  }
     83  if ((N = get_argument (argc, argv, "-max-time"))) {
     84    remove_argument (N, &argc, argv);
     85    mode = MAX_TIME;
    7386  }
    7487  if ((N = get_argument (argc, argv, "-min-dmag-sys"))) {
     
    231244          case MIN_DMAG_SYS:
    232245          case MIN_MCAL:
    233             V[ys*Nx + xs] = 1E6;
     246          case MIN_TIME:
     247            V[ys*Nx + xs] = 1E9;
    234248            break;
    235249          case MAX_MCAL:
    236             V[ys*Nx + xs] = -1E6;
     250          case MAX_TIME:
     251            V[ys*Nx + xs] = -1E9;
    237252            break;
    238253        }
     
    247262          case MIN_MCAL:
    248263          case MAX_MCAL:
     264          case MIN_TIME:
     265          case MAX_TIME:
    249266            V[ys*Nx + xs] = NAN;
    250267            break;
     
    323340              V[ys*Nx + xs] = MAX(V[ys*Nx + xs], image[i].Mcal);
    324341              break;
     342            case MIN_TIME: {
     343              double timeVal = TimeValue (image[i].tzero, TimeReference, TimeFormat);
     344              V[ys*Nx + xs] = MIN(V[ys*Nx + xs], timeVal);
     345              break; }
     346            case MAX_TIME: {
     347              double timeVal = TimeValue (image[i].tzero, TimeReference, TimeFormat);
     348              V[ys*Nx + xs] = MAX(V[ys*Nx + xs], timeVal);
     349              break; }
    325350          }
    326351        }
  • trunk/Ohana/src/opihi/include/dvoshell.h

    r33662 r33963  
    9999dbValue      dbExtractImages        PROTO((Image *image, off_t Nimage, off_t N, dbField *field));
    100100
    101 int          HostTableLaunchJobs    PROTO((HostTable *table, char *basecmd, char *options));
     101int          HostTableLaunchJobs    PROTO((HostTable *table, char *basecmd, char *options, int VERBOSE));
    102102int          HostTableParallelOps   PROTO((int argc, char **argv, char *ResultFile, int Nelements, int VERBOSE));
    103 # endif
     103int          HostTableReloadResults PROTO((char *uniquer, int VERBOSE));
     104
     105# endif // DVOSHELL_H
  • trunk/Ohana/src/opihi/lib.shell/ListOps.c

    r33662 r33963  
    116116 
    117117  status = !strcmp (comm, "for");
     118  free (comm);
     119  return (status);
     120}
     121
     122int is_foreach_loop (char *line) {
     123
     124  int status;
     125  char *comm;
     126
     127  comm = thisword (line);
     128  if (comm == (char *) NULL) return (FALSE);
     129 
     130  status = !strcmp (comm, "foreach");
    118131  free (comm);
    119132  return (status);
     
    266279  status |= is_macro_create (line);
    267280  status |= is_for_loop (line);
     281  status |= is_foreach_loop (line);
    268282  status |= is_list_data (line);
    269283  status |= is_loop (line);
  • trunk/Ohana/src/opihi/lib.shell/VectorIO.c

    r33662 r33963  
    2020  }
    2121  if (f == (FILE *) NULL) {
    22     gprint (GP_ERR, "can't open file for write\n");
     22    gprint (GP_ERR, "can't open file for write : %s\n", filename);
    2323    return (FALSE);
    2424  }
  • trunk/Ohana/src/opihi/lib.shell/startup.c

    r27998 r33963  
    138138    if (is_script) {
    139139      /* first argument in input script, rest are argv */
     140      set_str_variable ("SCRIPT_NAME", argv[1]);
    140141      list[Nlist] = strcreate (argv[1]);
    141142      Nlist ++;
  • trunk/Ohana/src/photdbc/include/dvodist.h

    r33655 r33963  
    2727char     *dstHostname;
    2828
    29 # define MAX_PATH_LENGTH 1024
     29# define DVO_MAX_PATH 1024
    3030
    3131void          usage();
  • trunk/Ohana/src/photdbc/include/photdbc.h

    r33655 r33963  
    3030// need to get RADIUS from Config
    3131
    32 # define MAX_PATH_LENGTH 1024
     32# define DVO_MAX_PATH 1024
    3333
    3434/* global variables */
     
    3838double UNIQ_RADIUS;
    3939double DMCAL_MIN;;
    40 char   ImageCat[MAX_PATH_LENGTH];
    41 char   GSCFILE[MAX_PATH_LENGTH];
    42 char   CATDIR[MAX_PATH_LENGTH];
     40char   ImageCat[DVO_MAX_PATH];
     41char   GSCFILE[DVO_MAX_PATH];
     42char   CATDIR[DVO_MAX_PATH];
    4343char  *CATMODE;    /* raw, mef, split, mysql */
    4444char  *CATFORMAT;  /* internal, elixir, loneos, panstarrs */
    45 char   PhotCodeFile[MAX_PATH_LENGTH];
     45char   PhotCodeFile[DVO_MAX_PATH];
    4646
    4747double RMIN;
  • trunk/Ohana/src/photdbc/src/ConfigInit.c

    r33655 r33963  
    5656
    5757  WarnConfig (config, "CATDIR",                 "%s",  0, CATDIR);
    58   char *tmpcatdir = abspath (CATDIR, MAX_PATH_LENGTH);
     58  char *tmpcatdir = abspath (CATDIR, DVO_MAX_PATH);
    5959  strcpy (CATDIR, tmpcatdir);
    6060  free (tmpcatdir);
  • trunk/Ohana/src/photdbc/src/md5_ops.c

    r33655 r33963  
    6060  IOBuffer buffer;
    6161
    62   char line[MAX_PATH_LENGTH];
    63   int Nline = snprintf (line, MAX_PATH_LENGTH, "md5sum %s\n", filename);
    64   assert (Nline < MAX_PATH_LENGTH);
     62  char line[DVO_MAX_PATH];
     63  int Nline = snprintf (line, DVO_MAX_PATH, "md5sum %s\n", filename);
     64  assert (Nline < DVO_MAX_PATH);
    6565
    66   write (host->stdio[0], line, Nline);
     66  int Nout = write (host->stdio[0], line, Nline);
     67  if (Nout != Nline) {
     68    fprintf (stderr, "failed to execute md5sum\n");
     69    return FALSE;
     70  }
    6771
    6872  InitIOBuffer (&buffer, 100);
     
    7276  fprintf (stderr, "buffer: %s\n", buffer.buffer);
    7377
    74   char result[MAX_PATH_LENGTH], fileout[MAX_PATH_LENGTH];
     78  char result[DVO_MAX_PATH], fileout[DVO_MAX_PATH];
    7579  int Nscan = sscanf (buffer.buffer, "%s %s", result, fileout);
    7680  assert (Nscan == 2);
     
    8690  IOBuffer buffer, stdout_buf, stderr_buf;
    8791
    88   char line[MAX_PATH_LENGTH];
    89   int Nline = snprintf (line, MAX_PATH_LENGTH, "job md5sum %s\n", filename);
    90   assert (Nline < MAX_PATH_LENGTH);
     92  char line[DVO_MAX_PATH];
     93  int Nline = snprintf (line, DVO_MAX_PATH, "job md5sum %s\n", filename);
     94  assert (Nline < DVO_MAX_PATH);
    9195
    9296  // fprintf (stderr, "command: %s\n", line);
     
    119123  // fprintf (stderr, "result from md5sum: %s\n", stdout_buf.buffer);
    120124
    121   char result[MAX_PATH_LENGTH], fileout[MAX_PATH_LENGTH];
     125  char result[DVO_MAX_PATH], fileout[DVO_MAX_PATH];
    122126  int Nscan = sscanf (stdout_buf.buffer, "%s %s", result, fileout);
    123127  if (Nscan != 2) {
  • trunk/Ohana/src/photdbc/src/photdbc_catalogs.c

    r33655 r33963  
    2020
    2121    // set the parameters which guide catalog open/load/create
    22     char hostfile[MAX_PATH_LENGTH];
    23     snprintf (hostfile, MAX_PATH_LENGTH, "%s/%s.cpt", HOSTDIR, skylist[0].regions[i]->name);
     22    char hostfile[DVO_MAX_PATH];
     23    snprintf (hostfile, DVO_MAX_PATH, "%s/%s.cpt", HOSTDIR, skylist[0].regions[i]->name);
    2424    incatalog.filename  = hostID ? hostfile : skylist[0].filename[i];
    2525    incatalog.Nsecfilt = GetPhotcodeNsecfilt ();
     
    3939
    4040    // create output catalog filename
    41     char outfile[MAX_PATH_LENGTH];
    42     snprintf (outfile, MAX_PATH_LENGTH, "%s/%s.cpt", outroot, skylist[0].regions[i]->name);
     41    char outfile[DVO_MAX_PATH];
     42    snprintf (outfile, DVO_MAX_PATH, "%s/%s.cpt", outroot, skylist[0].regions[i]->name);
    4343    outcatalog.filename = outfile;
    4444    if (outcatalog.filename == NULL) Shutdown ("error with input catalog name");
     
    9999
    100100    // ensure that the paths are absolute path names
    101     char *tmppath = abspath (table->hosts[i].pathname, MAX_PATH_LENGTH);
     101    char *tmppath = abspath (table->hosts[i].pathname, DVO_MAX_PATH);
    102102    free (table->hosts[i].pathname);
    103103    table->hosts[i].pathname = tmppath;
    104104
    105105    // ensure that the paths are absolute path names
    106     char *tmproot = abspath (outroot, MAX_PATH_LENGTH);
     106    char *tmproot = abspath (outroot, DVO_MAX_PATH);
    107107
    108108    // options / arguments that can affect relastro_client -update-objects:
    109     char command[MAX_PATH_LENGTH];
    110     snprintf (command, MAX_PATH_LENGTH, "photdbc_client %s -hostID %d -D CATDIR %s -hostdir %s -region %f %f %f %f -D NMEAS_MIN %d -D NMEAS_MIN_FILTERED %d -D AVE_SIGMA_LIM %f -D SIGMA_MAX %f",
     109    char command[DVO_MAX_PATH];
     110    snprintf (command, DVO_MAX_PATH, "photdbc_client %s -hostID %d -D CATDIR %s -hostdir %s -region %f %f %f %f -D NMEAS_MIN %d -D NMEAS_MIN_FILTERED %d -D AVE_SIGMA_LIM %f -D SIGMA_MAX %f",
    111111              tmproot, table->hosts[i].hostID, CATDIR, table->hosts[i].pathname,
    112112              REGION.Rmin, REGION.Rmax, REGION.Dmin, REGION.Dmax,
     
    114114      );
    115115
    116     char tmpline[MAX_PATH_LENGTH];
    117     if (VERBOSE)            { snprintf (tmpline, MAX_PATH_LENGTH, "%s -v",                command);                             strcpy (command, tmpline); }
    118     if (ExcludeByInstMag)   { snprintf (tmpline, MAX_PATH_LENGTH, "%s -instmag %f %f",    command, INST_MAG_MIN, INST_MAG_MAX); strcpy (command, tmpline); }
    119     if (ExcludeByMinSigma)  { snprintf (tmpline, MAX_PATH_LENGTH, "%s -min-sigma %f",     command, SIGMA_MIN_KEEP);             strcpy (command, tmpline); }
    120     if (ExcludeByMaxMinMag) { snprintf (tmpline, MAX_PATH_LENGTH, "%s -maxminmag %f",     command, MAX_MIN_MAG);                strcpy (command, tmpline); }
    121     if (PHOTCODE_DROP_LIST) { snprintf (tmpline, MAX_PATH_LENGTH, "%s -photcode-drop %s", command, PHOTCODE_DROP_LIST);         strcpy (command, tmpline); }
    122     if (PHOTCODE_SKIP_LIST) { snprintf (tmpline, MAX_PATH_LENGTH, "%s -photcode-skip %s", command, PHOTCODE_SKIP_LIST);         strcpy (command, tmpline); }
    123     if (CATFORMAT)          { snprintf (tmpline, MAX_PATH_LENGTH, "%s -set-format %s",    command, CATFORMAT);                  strcpy (command, tmpline); }
    124     if (CATMODE)            { snprintf (tmpline, MAX_PATH_LENGTH, "%s -set-mode %s",      command, CATMODE);                    strcpy (command, tmpline); }
     116    char tmpline[DVO_MAX_PATH];
     117    if (VERBOSE)            { snprintf (tmpline, DVO_MAX_PATH, "%s -v",                command);                             strcpy (command, tmpline); }
     118    if (ExcludeByInstMag)   { snprintf (tmpline, DVO_MAX_PATH, "%s -instmag %f %f",    command, INST_MAG_MIN, INST_MAG_MAX); strcpy (command, tmpline); }
     119    if (ExcludeByMinSigma)  { snprintf (tmpline, DVO_MAX_PATH, "%s -min-sigma %f",     command, SIGMA_MIN_KEEP);                strcpy (command, tmpline); }
     120    if (ExcludeByMaxMinMag) { snprintf (tmpline, DVO_MAX_PATH, "%s -maxminmag %f",     command, MAX_MIN_MAG);                   strcpy (command, tmpline); }
     121    if (PHOTCODE_DROP_LIST) { snprintf (tmpline, DVO_MAX_PATH, "%s -photcode-drop %s", command, PHOTCODE_DROP_LIST);    strcpy (command, tmpline); }
     122    if (PHOTCODE_SKIP_LIST) { snprintf (tmpline, DVO_MAX_PATH, "%s -photcode-skip %s", command, PHOTCODE_SKIP_LIST);    strcpy (command, tmpline); }
     123    if (CATFORMAT)          { snprintf (tmpline, DVO_MAX_PATH, "%s -set-format %s",    command, CATFORMAT);                     strcpy (command, tmpline); }
     124    if (CATMODE)            { snprintf (tmpline, DVO_MAX_PATH, "%s -set-mode %s",      command, CATMODE);                       strcpy (command, tmpline); }
    125125
    126126    fprintf (stderr, "command: %s\n", command);
  • trunk/Ohana/src/relastro/include/relastro.h

    r33652 r33963  
    120120
    121121/* global variables set in parameter file */
    122 # define MAX_PATH_LENGTH 1024
    123 char   ImageCat[MAX_PATH_LENGTH];
    124 char   GSCFILE[MAX_PATH_LENGTH];
    125 char   CATDIR[MAX_PATH_LENGTH];
     122# define DVO_MAX_PATH 1024
     123char   ImageCat[DVO_MAX_PATH];
     124char   GSCFILE[DVO_MAX_PATH];
     125char   CATDIR[DVO_MAX_PATH];
    126126char   *HIGH_SPEED_DIR;
    127127char   CATMODE[16];    /* raw, mef, split, mysql */
    128128char   CATFORMAT[16];  /* internal, elixir, loneos, panstarrs */
    129 char   SKY_TABLE[MAX_PATH_LENGTH];
     129char   SKY_TABLE[DVO_MAX_PATH];
    130130int    SKY_DEPTH;  /** XXX EAM : depth of catalog tables, fix usage */
    131131
  • trunk/Ohana/src/relastro/src/ConfigInit.c

    r33652 r33963  
    3939  // force CATDIR to be absolute (so parallel mode will work)
    4040  GetConfig (config, "CATDIR",                 "%s",  0, CATDIR);
    41   char *tmpcatdir = abspath (CATDIR, MAX_PATH_LENGTH);
     41  char *tmpcatdir = abspath (CATDIR, DVO_MAX_PATH);
    4242  strcpy (CATDIR, tmpcatdir);
    4343  free (tmpcatdir);
  • trunk/Ohana/src/relastro/src/UpdateObjectOffsets.c

    r33652 r33963  
    8787
    8888    // ensure that the paths are absolute path names
    89     char *tmppath = abspath (table->hosts[i].pathname, MAX_PATH_LENGTH);
     89    char *tmppath = abspath (table->hosts[i].pathname, DVO_MAX_PATH);
    9090    free (table->hosts[i].pathname);
    9191    table->hosts[i].pathname = tmppath;
  • trunk/Ohana/src/relastro/src/args.c

    r33652 r33963  
    9898    RADIUS = atof(argv[N]);
    9999    remove_argument (N, &argc, argv);
    100     HIGH_SPEED_DIR = abspath(argv[N], MAX_PATH_LENGTH);
     100    HIGH_SPEED_DIR = abspath(argv[N], DVO_MAX_PATH);
    101101    remove_argument (N, &argc, argv);
    102102  }
  • trunk/Ohana/src/relastro/src/high_speed_catalogs.c

    r33652 r33963  
    6868    char line[2048];
    6969    snprintf (line, 2048, "cp %s/Images.dat %s/Images.dat", CATDIR, HIGH_SPEED_DIR);
    70     system (line);
     70    int status = system (line);
     71    if (status) {
     72      fprintf (stderr, "copy of Images.dat failed\n");
     73      exit (3);
     74    }
    7175  }
    7276
     
    109113
    110114    // ensure that the paths are absolute path names
    111     char *tmppath = abspath (table->hosts[i].pathname, MAX_PATH_LENGTH);
     115    char *tmppath = abspath (table->hosts[i].pathname, DVO_MAX_PATH);
    112116    free (table->hosts[i].pathname);
    113117    table->hosts[i].pathname = tmppath;
     
    125129
    126130      free (outputDir);
    127       outputDir = abspath (tableOut->hosts[index].pathname, MAX_PATH_LENGTH);
     131      outputDir = abspath (tableOut->hosts[index].pathname, DVO_MAX_PATH);
    128132    }
    129133
  • trunk/Ohana/src/relastro/src/load_catalogs.c

    r33652 r33963  
    126126
    127127    // ensure that the paths are absolute path names
    128     char *tmppath = abspath (table->hosts[i].pathname, MAX_PATH_LENGTH);
     128    char *tmppath = abspath (table->hosts[i].pathname, DVO_MAX_PATH);
    129129    free (table->hosts[i].pathname);
    130130    table->hosts[i].pathname = tmppath;
  • trunk/Ohana/src/relastro/src/relastro_objects.c

    r33652 r33963  
    109109
    110110    // ensure that the paths are absolute path names
    111     char *tmppath = abspath (table->hosts[i].pathname, MAX_PATH_LENGTH);
     111    char *tmppath = abspath (table->hosts[i].pathname, DVO_MAX_PATH);
    112112    free (table->hosts[i].pathname);
    113113    table->hosts[i].pathname = tmppath;
  • trunk/Ohana/src/relphot/Makefile

    r33651 r33963  
    4646$(SRC)/relphot_objects.$(ARCH).o         \
    4747$(SRC)/select_images.$(ARCH).o   \
     48$(SRC)/client_logger.$(ARCH).o   \
    4849$(SRC)/setExclusions.$(ARCH).o   \
    4950$(SRC)/setMrelFinal.$(ARCH).o    \
     
    7374$(SRC)/relphot_objects.$(ARCH).o         \
    7475$(SRC)/relphot_client.$(ARCH).o  \
     76$(SRC)/client_logger.$(ARCH).o   \
    7577$(SRC)/setExclusions.$(ARCH).o   \
    7678$(SRC)/setMrelFinal.$(ARCH).o    \
  • trunk/Ohana/src/relphot/include/relphot.h

    r33651 r33963  
    33# include <kapa.h>
    44# include <signal.h>
     5# include <pthread.h>
    56
    67/* # define GRID_V1 */
     
    2627  float dMcal;
    2728  float dMsys;
    28   short nFitPhotom;
     29  unsigned short nFitPhotom;
    2930  short Xm;
    3031  float secz;
    3132  float ubercalDist;
    3233  unsigned int flags;
     34  char skipCal;               // if TRUE, this mosaic is incomplete and should not be calibrated
    3335  Coords coords;
    3436} Mosaic;
     37
     38typedef enum {
     39  STATS_NONE,
     40  STATS_MEAN,
     41  STATS_MEDIAN,
     42  STATS_WT_MEAN,
     43  STATS_INNER_MEAN,
     44  STATS_INNER_WTMEAN,
     45  STATS_CHI_INNER_MEAN,
     46  STATS_CHI_INNER_WTMEAN
     47} ListStatsMode;
    3548
    3649typedef struct {
     
    4659  double total;
    4760  int    Nmeas;
     61  ListStatsMode statmode;
    4862} StatType;
    4963
     
    7993
    8094/* global variables set in parameter file */
    81 # define MAX_PATH_LENGTH 1024
    82 char   ImageCat[MAX_PATH_LENGTH];
    83 char   ImageTemplate[MAX_PATH_LENGTH];
    84 char   CatTemplate[MAX_PATH_LENGTH];
    85 char   GSCFILE[MAX_PATH_LENGTH];
     95# define DVO_MAX_PATH 1024
     96char   ImageCat[DVO_MAX_PATH];
     97char   ImageTemplate[DVO_MAX_PATH];
     98char   CatTemplate[DVO_MAX_PATH];
     99char   GSCFILE[DVO_MAX_PATH];
    86100char  *CATDIR;
    87101char   CATMODE[16];    /* raw, mef, split, mysql */
    88102char   CATFORMAT[16];  /* internal, elixir, loneos, panstarrs */
    89 char   CameraConfig[MAX_PATH_LENGTH];
     103char   CameraConfig[DVO_MAX_PATH];
    90104char   CAMERA[64];    /* eg, gpc1 */
    91 char   SKY_TABLE[MAX_PATH_LENGTH];
     105char   SKY_TABLE[DVO_MAX_PATH];
    92106int    SKY_DEPTH;  /** XXX EAM : depth of catalog tables, fix usage */
    93107
     
    111125int    PARALLEL_MANUAL;
    112126int    PARALLEL_SERIAL;
     127
     128int    NTHREADS;
    113129
    114130int    VERBOSE;
     
    141157int    PLOTDELAY;
    142158int    UpdateAverages;
     159int    ApplyOffsets;
    143160
    144161char  *PhotcodeList;
     
    194211int           args                PROTO((int argc, char **argv));
    195212int           args_client         PROTO((int argc, char **argv));
    196 int           bcatalog            PROTO((Catalog *subcatalog, Catalog *catalog));
     213int           bcatalog            PROTO((Catalog *subcatalog, Catalog *catalog, int Ncat));
    197214void          clean_images        PROTO((void));
    198215void          clean_measures      PROTO((Catalog *catalog, int Ncatalog, int final, FlatCorrectionTable *flatcorr));
     
    236253void          initMosaicBins      PROTO((Catalog *catalog, int Ncatalog, int doMosaicList));
    237254void          initMosaicGrid      PROTO((Image *image, off_t Nimage));
    238 void          initMosaics         PROTO((Image *image, off_t Nimage));
     255void          initMosaics         PROTO((Image *subset, off_t Nsubset, Image *image, char *inSubset, off_t Nimage));
    239256void          initMrel            PROTO((Catalog *catalog, int Ncatalog));
    240257void          initialize          PROTO((int argc, char **argv));
    241258void          initialize_client   PROTO((int argc, char **argv));
    242 void          initstats           PROTO((char *mode));
    243 int           liststats           PROTO((double *value, double *dvalue, int N, StatType *stats));
     259void          liststats_setmode   PROTO((StatType *stats, char *strmode));
     260int           liststats           PROTO((double *value, double *dvalue, double *wvalue, int N, StatType *stats));
    244261Catalog      *load_catalogs       PROTO((SkyList *skylist, int *Ncatalog, int hostID, char *hostpath));
    245262Catalog      *load_catalogs_parallel PROTO((SkyList *sky, int *Ncatalog));
    246263
    247264SkyList      *load_images         PROTO((FITS_DB *db, char *regionName, SkyRegion *region));
    248 Image        *select_images       PROTO((SkyList *skylist, Image *timage, off_t Ntimage, off_t **LineNumber, off_t *Nimage));
     265Image        *select_images       PROTO((SkyList *skylist, Image *timage, off_t Ntimage, char *inSubset, off_t **LineNumber, off_t *Nimage, SkyRegion *region));
    249266
    250267int           main                PROTO((int argc, char **argv));
     
    273290int           setMmos             PROTO((Catalog *catalog, int Poor, FlatCorrectionTable *flatcorr));
    274291int           setMrel             PROTO((Catalog *catalog, int Ncatalog, FlatCorrectionTable *flatcorr));
    275 void          setMrelFinal        PROTO((Catalog *catalog, FlatCorrectionTable *flatcorr));
     292void          setMrelFinal        PROTO((Catalog *catalog, FlatCorrectionTable *flatcorr, int simpleAverage));
    276293int           setMrelOutput       PROTO((Catalog *catalog, int Ncatalog, int pass, FlatCorrectionTable *flatcorr));
    277294int           setMave             PROTO((Catalog *catalog, int Ncatalog));
     
    319336int ImageSubsetSave(char *filename, ImageSubset *image, off_t Nimage);
    320337ImageSubset *ImageSubsetLoad(char *filename, off_t *nimage);
     338
     339int client_logger_init ();
     340int client_logger_message (char *format,...);
     341
  • trunk/Ohana/src/relphot/src/ConfigInit.c

    r33651 r33963  
    3535  // force CATDIR to be absolute (so parallel mode will work)
    3636  char *tmpcatdir = NULL;
    37   ALLOCATE (tmpcatdir, char, MAX_PATH_LENGTH);
     37  ALLOCATE (tmpcatdir, char, DVO_MAX_PATH);
    3838  GetConfig (config, "CATDIR",                 "%s",  0, tmpcatdir);
    39   CATDIR = abspath (tmpcatdir, MAX_PATH_LENGTH);
     39  CATDIR = abspath (tmpcatdir, DVO_MAX_PATH);
    4040  free (tmpcatdir);
    4141
  • trunk/Ohana/src/relphot/src/GridOps.c

    r33651 r33963  
    527527  double *list, *dlist;
    528528  float Msys, Mrel, Mcal, Mmos;
     529
    529530  StatType stats;
     531  liststats_setmode (&stats, STATMODE);
    530532 
    531533  if (!USE_GRID) return;
     
    595597    }
    596598
    597     liststats (list, dlist, N, &stats);
     599    liststats (list, dlist, NULL, N, &stats);
    598600    gridM[i] = stats.mean;
    599601    gridS[i] = stats.sigma;
  • trunk/Ohana/src/relphot/src/ImageOps.c

    r33651 r33963  
    4141
    4242// relationships between the measure,catalog set and the images:
    43 static IDX_T       **MeasureToImage; // image index from measure,catalog   : MeasureToImage[cat][meas] = ImageIndex
    44 static IDX_T       **ImageToCatalog; // catalog for given measure on image : ImageCatalog[ImageIndex][i] = cat (i : 0 < NonImage[ImageIndex])
    45 static IDX_T       **ImageToMeasure; // measure for given measure on image : ImageMeasure[ImageIndex][i] = cat (i : 0 < NonImage[ImageIndex])
     43static IDX_T       **MeasureToImage = NULL; // image index from measure,catalog   : MeasureToImage[cat][meas] = ImageIndex
     44static IDX_T       **ImageToCatalog = NULL; // catalog for given measure on image : ImageCatalog[ImageIndex][i] = cat (i : 0 < NonImage[ImageIndex])
     45static IDX_T       **ImageToMeasure = NULL; // measure for given measure on image : ImageMeasure[ImageIndex][i] = cat (i : 0 < NonImage[ImageIndex])
    4646
    4747// MeasureToImage was 'bin'
     
    322322  off_t i;
    323323
     324  if (!MeasureToImage) return -1;
     325
    324326  i = MeasureToImage[cat][meas];
    325327  return (i);
     
    355357  short distance;
    356358
     359  if (!MeasureToImage) return -1;
     360
    357361  i = MeasureToImage[cat][meas];
    358362  if (i == -1) return (1000);
     
    395399  float Msys, Mrel, Mmos, Mgrid, Mflat;
    396400  double *list, *dlist, *Mlist, *dMlist;
     401
    397402  StatType stats;
     403  liststats_setmode (&stats, STATMODE);
    398404
    399405  if (FREEZE_IMAGES) return;
     
    514520    }
    515521
    516     liststats (list, dlist, N, &stats);
     522    // no additional weight modification (we treat all stars on an image equally -- note an image is either ubercal-tied or not)
     523    liststats (list, dlist, NULL, N, &stats);
    517524    image[i].Mcal  = stats.mean;
    518525    image[i].dMcal = stats.error;
     
    523530
    524531    // bright end scatter
    525     liststats (Mlist, dMlist, Nbright, &stats);
     532    liststats (Mlist, dMlist, NULL, Nbright, &stats);
    526533    image[i].dMagSys = stats.sigma;
    527534
     
    556563  double *mlist, *slist, *dlist;
    557564  double MaxOffset, MaxScatter, MedOffset;
    558   StatType stats;
    559565
    560566  if (FREEZE_IMAGES) return;
     
    574580    N++;
    575581  }
    576   initstats ("MEAN");
    577   liststats (mlist, dlist, N, &stats);
     582
     583  // use a straight mean to find the global image statistics (no weighting)
     584  StatType stats;
     585  liststats_setmode (&stats, "MEAN");
     586
     587  liststats (mlist, dlist, NULL, N, &stats);
    578588  MaxOffset = MAX (IMAGE_OFFSET, 3*stats.sigma);
    579589  MedOffset = stats.median;
    580   liststats (slist, dlist, N, &stats);
     590
     591  liststats (slist, dlist, NULL, N, &stats);
    581592  MaxScatter = MAX (IMAGE_SCATTER, 2*stats.median);
    582593  fprintf (stderr, "Mrel: %f, dMrel: %f, Max Scatter: %f, Max Offset: %f\n", MedOffset, stats.median, MaxScatter, MaxOffset);
     
    599610
    600611  fprintf (stderr, "%d images marked poor\n", Nmark);
    601   initstats (STATMODE);
    602612  free (mlist);
    603613  free (slist);
     
    720730  double *list, *dlist;
    721731  float Mcal, Mmos, Mgrid;
     732
    722733  StatType stats;
    723 
    724734  bzero (&stats, sizeof (StatType));
    725735  if (FREEZE_IMAGES) return (stats);
     
    751761  }
    752762
    753   liststats (list, dlist, n, &stats);
     763  liststats_setmode (&stats, "MEAN");
     764
     765  liststats (list, dlist, NULL, n, &stats);
    754766  free (list);
    755767  free (dlist);
     
    779791  }
    780792
    781   liststats (list, dlist, n, &stats);
     793  liststats_setmode (&stats, "MEAN");
     794
     795  liststats (list, dlist, NULL, n, &stats);
    782796  free (list);
    783797  free (dlist);
     
    807821  }
    808822
    809   liststats (list, dlist, n, &stats);
     823  liststats_setmode (&stats, "MEAN");
     824
     825  liststats (list, dlist, NULL, n, &stats);
    810826  free (list);
    811827  free (dlist);
     
    835851  }
    836852
    837   liststats (list, dlist, n, &stats);
     853  liststats_setmode (&stats, "MEAN");
     854
     855  liststats (list, dlist, NULL, n, &stats);
    838856  free (list);
    839857  free (dlist);
  • trunk/Ohana/src/relphot/src/ImageSubset.c

    r33651 r33963  
    9292}
    9393
     94// STATUS is value expected for success
     95# define CHECK_STATUS(STATUS,MSG,...)                                   \
     96  if (!(STATUS)) {                                                      \
     97    fprintf (stderr, MSG, __VA_ARGS__);                                 \
     98    return FALSE;                                                       \
     99  }
     100
    94101int ImageSubsetSave(char *filename, ImageSubset *image, off_t Nimage) {
    95102
     
    167174  }
    168175
    169   gfits_fwrite_header  (f, &header);
    170   gfits_fwrite_matrix  (f, &matrix);
    171   gfits_fwrite_Theader (f, &theader);
    172   gfits_fwrite_table  (f, &ftable);
     176  int status;
     177  status = gfits_fwrite_header  (f, &header);
     178  CHECK_STATUS (status, "ERROR: cannot write header for image subset %s\n", filename);
     179
     180  status = gfits_fwrite_matrix  (f, &matrix);
     181  CHECK_STATUS (status, "ERROR: cannot write matrix for image subset %s\n", filename);
     182
     183  status = gfits_fwrite_Theader (f, &theader);
     184  CHECK_STATUS (status, "ERROR: cannot write table header for image subset %s\n", filename);
     185
     186  status = gfits_fwrite_table  (f, &ftable);
     187  CHECK_STATUS (status, "ERROR: cannot write table data for image subset %s\n", filename);
    173188
    174189  gfits_free_header (&header);
     
    177192  gfits_free_table (&ftable);
    178193
    179   fclose (f);
    180   fflush (f);
     194  int fd = fileno (f);
     195
     196  status = fflush (f);
     197  CHECK_STATUS (!status, "ERROR: cannot flush file image subset %s\n", filename);
     198
     199  status = fsync (fd);
     200  CHECK_STATUS (!status, "ERROR: cannot flush file image subset %s\n", filename);
     201
     202  status = fclose (f);
     203  CHECK_STATUS (!status, "ERROR: problem closing image subset file %s\n", filename);
    181204
    182205  return TRUE;
  • trunk/Ohana/src/relphot/src/MosaicOps.c

    r33651 r33963  
    5050  ALLOCATE (mosaic, Mosaic, NMOSAIC);
    5151
    52   ALLOCATE (MosaicToImage,  off_t *, NMOSAIC);
     52  ALLOCATE (MosaicToImage, off_t *, NMOSAIC);
    5353  ALLOCATE (MosaicN_Image, off_t,   NMOSAIC);
    5454  ALLOCATE (MosaicN_IMAGE, off_t,   NMOSAIC);
     
    9595    if (found) continue;
    9696   
    97     /* a new mosaic, define ranges */
     97    /* a new mosaic, define ranges -- preserve the original values incase this image is not used */
    9898    mosaic[Nmosaic].start = start;
    9999    mosaic[Nmosaic].stop  = stop;
    100     mosaic[Nmosaic].Mcal  = 0.0;
    101     mosaic[Nmosaic].dMcal = 0.0;
     100    mosaic[Nmosaic].Mcal  = 0.0; // note : mosaic stores only offsets relative to the original image values
     101    mosaic[Nmosaic].dMcal = 0.0; // note : at the end, mosaic.Mcal is added back to the input images
    102102    mosaic[Nmosaic].dMsys = 0.0;
    103103    mosaic[Nmosaic].Xm    = 0.0;
     
    152152}
    153153
    154 /* find mosaic frames (unique time periods & photcode name matches mosaic) */
    155 void initMosaics (Image *image, off_t Nimage) {
     154# define MARKTIME(MSG,...) { \
     155  float dtime; \
     156  gettimeofday (&stopTimer, (void *) NULL); \
     157  dtime = DTIME (stopTimer, startTimer); \
     158  fprintf (stderr, MSG, __VA_ARGS__); }
     159
     160/* find mosaic frames (unique time periods) (NOTE : we do NOT require matching photcodes...)
     161   this function will also identify the images NOT in the subset which belong to a selected mosaic
     162 */
     163void initMosaics (Image *subset, off_t Nsubset, Image *image, char *inSubset, off_t Nimage) {
    156164
    157165  off_t i, j, status, found, NMOSAIC, *MosaicN_IMAGE;
     
    159167  char *pname;
    160168
     169  struct timeval startTimer, stopTimer;
     170
    161171  if (!MOSAIC_ZEROPT) return;
     172
     173  gettimeofday (&startTimer, (void *) NULL);
    162174
    163175  /* a 'mosaic' in relphot is (unlike relastro) a virtual concept: there is no
     
    166178   */
    167179
    168   // generate a list of unique start times (these define the mosaics)
    169   ALLOCATE (startTimes, unsigned int, Nimage);
    170   for (i = 0; i < Nimage; i++) {
    171     startTimes[i] = image[i].tzero;
    172   }
    173   sort_times (startTimes, Nimage);
     180  // generate a list of all subset image start times
     181  ALLOCATE (startTimes, unsigned int, Nsubset);
     182  for (i = 0; i < Nsubset; i++) {
     183    startTimes[i] = subset[i].tzero;
     184  }
     185  sort_times (startTimes, Nsubset);
     186  MARKTIME("create array of all image obstimes: %f sec\n", dtime);
    174187 
    175188  Nmosaic = 0;
     
    178191  startTimesMosaic[0] = startTimes[0];
    179192
    180   for (i = 0; i < Nimage; i++) {
     193  // generate a list of the unique start times (these define the mosaics)
     194  for (i = 0; i < Nsubset; i++) {
    181195    if (startTimes[i] < startTimesMosaic[Nmosaic]) {
    182196      fprintf (stderr, "error?\n");
     
    192206  }
    193207  Nmosaic ++;
     208  MARKTIME("create subset array of mosaic obstimes: %f sec\n", dtime);
    194209
    195210  // now I have a list of uniq start times, and they are in order
     
    212227    mosaic[i].secz  = NAN;
    213228    mosaic[i].photcode = 0;
     229    mosaic[i].skipCal = FALSE;
     230   
     231    memset (&mosaic[i].coords, 0, sizeof(Coords));
    214232
    215233    MosaicN_IMAGE[i] = 10;
     
    219237  }
    220238
    221   ALLOCATE (ImageToMosaic, off_t, Nimage); // mosaic to which image belongs
    222 
    223   // assign each image to a mosaic
     239  int Nskip, Nmark;
     240  Nskip = Nmark = 0;
     241  // find any mosaics (startTimesMosaic) which match unselected images
    224242  for (i = 0; i < Nimage; i++) {
    225     ImageToMosaic[i] = -1;
    226 
     243    if (inSubset[i]) {
     244      Nskip ++;
     245      continue;
     246    }
     247   
    227248    /* select valid mosaic images by photcode */
    228249    pname = GetPhotcodeNamebyCode (image[i].photcode);
     250    if (!pname) continue;
    229251    status = strncmp (pname, MOSAICNAME, strlen (MOSAICNAME));
    230252    if (status) continue;
    231253
    232254    /* set image time range */
    233     // start = image[i].tzero - MAX(0.01*image[i].trate*image[i].NY, 1);
    234     // stop  = image[i].tzero + MAX(1.01*image[i].trate*image[i].NY, 1);
    235 
    236255    start = image[i].tzero;
    237256    stop  = image[i].tzero + MAX(1.01*image[i].trate*image[i].NY, 1);
    238257
     258    /* find a matching mosaic */
     259    j = findMosaic(startTimesMosaic, Nmosaic, start);
     260    if (j != -1) {
     261      // mark this mosaic as bad
     262      mosaic[j].skipCal = TRUE;
     263      Nmark ++;
     264    }
     265  }
     266  fprintf (stderr, "%d total images, %d overlap skyregion, %d do not overlap, but match overlapping mosaics\n", (int) Nimage, (int) Nskip, (int) Nmark);
     267  MARKTIME("find unselected images matching selected mosaics: %f sec\n", dtime);
     268
     269  ALLOCATE (ImageToMosaic, off_t, Nsubset); // mosaic to which image belongs
     270
     271  // assign each image to a mosaic
     272  for (i = 0; i < Nsubset; i++) {
     273    ImageToMosaic[i] = -1;
     274
     275    /* select valid mosaic images by photcode */
     276    pname = GetPhotcodeNamebyCode (subset[i].photcode);
     277    status = strncmp (pname, MOSAICNAME, strlen (MOSAICNAME));
     278    if (status) continue;
     279
     280    start = subset[i].tzero;
     281    stop  = subset[i].tzero + MAX(1.01*subset[i].trate*subset[i].NY, 1);
     282
    239283    j = findMosaic(startTimesMosaic, Nmosaic, start);
    240284    if (j == -1) {
    241       fprintf (stderr, "error?\n");
     285      fprintf (stderr, "programming error? all subset images should belong to a mosaic\n");
    242286      abort();
    243287    }
     
    268312    mosaic[j].dMsys = 0.0;
    269313    mosaic[j].Xm    = 0.0;
    270     mosaic[j].flags  = image[i].flags;
    271     mosaic[j].secz  = image[i].secz;
    272     mosaic[j].photcode = GetPhotcodeEquivCodebyCode (image[i].photcode);
     314    mosaic[j].flags  = subset[i].flags;
     315    mosaic[j].secz  = subset[i].secz;
     316    mosaic[j].photcode = GetPhotcodeEquivCodebyCode (subset[i].photcode);
    273317  }
    274318
     
    278322  free (startTimesMosaic);
    279323
    280   initMosaicGrid (image, Nimage);
    281 
    282   fprintf (stderr, "matched %d images to %d mosaics\n", (int) Nimage, (int) Nmosaic);
     324  initMosaicGrid (subset, Nsubset);
     325
     326  fprintf (stderr, "matched %d images to %d mosaics\n", (int) Nsubset, (int) Nmosaic);
    283327  return;
    284328}
    285329
    286 // use bisection to find the overlapping mosaic
     330// use bisection to find the overlapping mosaic (returns exact match)
     331// startTimes is a sorted, unique list of times
     332// start might not be in the list
    287333off_t findMosaic (unsigned int *startTimes, off_t Nmosaic, unsigned int start) {
    288334
     
    290336
    291337  // find the last mosaic before start
    292   Nlo = 0; // startTimes[Nlo] guaranteed to be <= start
    293   Nhi = Nmosaic - 1; // startTimes[Nhi] guaranteed to be >= start
    294   while (Nhi - Nlo > 10) {
     338  Nlo = 0; // first valid startTimes value
     339  Nhi = Nmosaic - 1; // last valid startTimes value
     340
     341  // if start is not in this range, return -1
     342  if (start < startTimes[Nlo]) return (-1);
     343  if (start > startTimes[Nhi]) return (-1);
     344
     345  while (Nhi - Nlo > 4) {
    295346    N = 0.5*(Nlo + Nhi);
    296347    if (startTimes[N] < start) {
     
    300351    }
    301352  }
    302 
    303   // check for the matched mosaic starting from Nlo
    304   for (N = Nlo; N < Nmosaic; N++) {
    305     if (start > startTimes[N])  continue;
    306     return (N);
     353  // we now have : startTimes[Nlo] < start <= starTimes[Nhi]
     354
     355  // find a matched mosaic starting from Nlo, or return -1
     356  for (N = Nlo; N <= Nhi; N++) {
     357    if (startTimes[N] == start) return N;
    307358  }
    308359  return (-1);
     
    394445}
    395446
     447// XXX : what about mosaics with skipCal == TRUE?
    396448void setMcalFinal () {
    397449
     
    569621}
    570622
     623typedef struct {
     624  int Nfew;
     625  int Nbad;
     626  int Ncal;
     627  int Ngrid;
     628  int Nrel;
     629  int Nsys;
     630  int Nskip;
     631  off_t Nmax;
     632  int PoorImages;
     633  double *list;
     634  double *dlist;
     635  double *Mlist;
     636  double *dMlist;
     637} SetMmosInfo;
     638
     639enum {THREAD_RUN, THREAD_DONE};
     640
     641typedef struct {
     642  int entry;
     643  int state;
     644  Catalog *catalog;
     645  Image *image;
     646  FlatCorrectionTable *flatcorr;
     647  SetMmosInfo info;
     648} ThreadInfo;
     649
     650int setMmos_mosaic (Mosaic *mosaic, off_t Nmos, Image *image, Catalog *catalog, SetMmosInfo *info, FlatCorrectionTable *flatcorr);
     651void *setMmos_worker (void *data);
     652int setMmos_threaded (Catalog *catalog, int PoorImages, FlatCorrectionTable *flatcorr);
     653
     654void SetMmosInfoInit (SetMmosInfo *info, off_t Nmax, int allocLists, int PoorImages) {
     655  info->Nfew = 0;
     656  info->Nbad = 0;
     657  info->Ncal = 0;
     658  info->Nrel = 0;
     659  info->Ngrid = 0;
     660  info->Nskip = 0;
     661  info->Nsys = 0;
     662
     663  info->Nmax = Nmax;
     664  info->PoorImages = PoorImages;
     665
     666  if (allocLists) {
     667    ALLOCATE (info->list, double, Nmax);
     668    ALLOCATE (info->dlist, double, Nmax);
     669    ALLOCATE (info->Mlist, double, Nmax);
     670    ALLOCATE (info->dMlist, double, Nmax);
     671  }
     672}
     673
     674void SetMmosInfoFree (SetMmosInfo *info) {
     675  free (info->list);
     676  free (info->dlist);
     677  free (info->Mlist);
     678  free (info->dMlist);
     679}
     680
     681void SetMmosInfoAccum (SetMmosInfo *summary, SetMmosInfo *results) {
     682  summary->Nfew  += results->Nfew ;
     683  summary->Nsys  += results->Nsys ;
     684  summary->Nbad  += results->Nbad ;
     685  summary->Ncal  += results->Ncal ;
     686  summary->Nrel  += results->Nrel ;
     687  summary->Ngrid += results->Ngrid;
     688  summary->Nskip += results->Nskip;
     689}
     690
     691static int npass_output = 0;
     692
     693// mutex to lock setMmos_worker operations
     694static pthread_mutex_t setMmos_mutex = PTHREAD_MUTEX_INITIALIZER;
     695static int nextMosaic = 0;
     696
     697// we have an array of mosaics (mosaic, Nmosaic).  we need to hand out mosaics one at a time to
     698// the worker threads as they need
     699off_t getNextMosaicForThread () {
     700
     701  pthread_mutex_lock (&setMmos_mutex);
     702  if (nextMosaic >= Nmosaic) {
     703    pthread_mutex_unlock (&setMmos_mutex);
     704    return (-1);
     705  }
     706  int thisMosaic = nextMosaic;
     707  nextMosaic ++;
     708
     709  pthread_mutex_unlock (&setMmos_mutex);
     710  return (thisMosaic);
     711}
     712
    571713int setMmos (Catalog *catalog, int PoorImages, FlatCorrectionTable *flatcorr) {
    572714
    573   off_t i, j, m, c, n, N, Nmax;
    574   int mark, bad, Nfew, Nbad, Ncal, Nrel, Ngrid, Nsys, Nbright;
    575   float Msys, Mrel, Mcal, Mgrid, Mflat;
    576   double *list, *dlist, *Mlist, *dMlist;
    577   StatType stats;
     715  off_t i, N, Nmax;
    578716  Image *image;
    579717
     
    581719  if (FREEZE_MOSAICS) return (FALSE);
    582720
     721  if (NTHREADS) {
     722    int status = setMmos_threaded (catalog, PoorImages, flatcorr);
     723    return status;
     724  }
     725
    583726  image = getimages (&N, NULL);
    584727
    585728  fprintf (stderr, "limiting negative clouds to %f\n", CLOUD_TOLERANCE);
    586 
    587   int Nsecfilt = GetPhotcodeNsecfilt ();
    588729
    589730  if (PoorImages) {
     
    597738    Nmax = MAX (Nmax, N_onMosaic[i]);
    598739  }
    599   ALLOCATE (list, double, Nmax);
    600   ALLOCATE (dlist, double, Nmax);
    601   ALLOCATE (Mlist, double, Nmax);
    602   ALLOCATE (dMlist, double, Nmax);
    603 
    604   Nfew = Nbad = Ncal = Nrel = Ngrid = Nsys = 0;
    605 
    606   for (i = 0; i < Nmosaic; i++) {
    607    
    608     /* on PoorImages run, skip good images */
    609     if (PoorImages) {
    610       bad = mosaic[i].flags & (ID_IMAGE_PHOTOM_FEW | ID_IMAGE_PHOTOM_POOR | ID_IMAGE_PHOTOM_SKIP);
    611       if (!bad) continue;
    612     }     
    613 
    614     // UBERCAL image: if this is an ubercal image, set minUbercalDist to 0:
    615     // we optionally do not recalibrate images with UBERCAL zero points
    616     if (mosaic[i].flags & ID_IMAGE_PHOTOM_UBERCAL) {
    617       mosaic[i].ubercalDist = 0;
    618       // propagate ubercalDist to the images
    619       for (j = 0; j < MosaicN_Image[i]; j++) {
    620         off_t im = MosaicToImage[i][j];
    621         image[im].ubercalDist = mosaic[i].ubercalDist;
    622         // fprintf (stderr, "%d %d %d\n", (int) i, (int) im, image[im].ubercalDist);
    623       }
    624       if (KEEP_UBERCAL) continue;
    625     }
    626 
    627     int minUbercalDist = 1000;
    628 
    629     // number of stars to measure the bright-end scatter
    630     Nbright = 0;
    631 
    632     N = 0;
    633     for (j = 0; j < N_onMosaic[i]; j++) {
    634      
    635       m = MosaicToMeasure[i][j];
    636       c = MosaicToCatalog[i][j];
    637      
    638       if (catalog[c].measureT[m].dbFlags & MEAS_BAD) {
    639           Nbad ++;
    640           continue;
    641       }
    642       Mcal  = getMcal  (m, c, flatcorr, catalog);
    643       if (isnan(Mcal)) {
    644           Ncal++;
    645           continue;
    646       }
    647       Mgrid = getMgrid (m, c);
    648       if (isnan(Mgrid)) {
    649           Ngrid ++;
    650           continue;
    651       }
    652       Mrel  = getMrel  (catalog, m, c);
    653       if (isnan(Mrel)) {
    654           Nrel ++;
    655           continue;
    656       }
    657      
    658       // image.Mcal is not supposed to include the flat-field correction, so we need to
    659       // apply that offset as well here for this image (in other words, each detection is
    660       // being compared to the model, excluding the zero point, Mcal.  The model includes
    661       // the flat-correction.  NOTE the sign of Mflat (Image.Mcal = Measure.Mcal - Mflat)
    662 
    663       Mflat = getMflat (m, c, flatcorr, catalog);
    664 
    665       n = catalog[c].measureT[m].averef;
    666       Msys = PhotSysTiny (&catalog[c].measureT[m], &catalog[c].averageT[n], &catalog[c].secfilt[n*Nsecfilt]);
    667       if (isnan(Msys)) {
    668         Nsys++;
    669         continue;
    670       }
    671 
    672       PhotCode *code = GetPhotcodebyCode (catalog[c].measureT[m].photcode);
    673       if (!code) goto skip;
    674       if (code->equiv < 1) goto skip;
    675       int Nsec = GetPhotcodeNsec (code->equiv);
    676       if (Nsec == -1) goto skip;
    677       minUbercalDist = MIN (catalog[c].secfilt[n*Nsecfilt + Nsec].ubercalDist, minUbercalDist);
    678 
    679     skip:
    680       list[N]  = Msys - Mrel - Mcal - Mgrid + Mflat;
    681       dlist[N] = MAX (catalog[c].measureT[m].dM, MIN_ERROR);
    682       if (catalog[c].measureT[m].dM < IMFIT_SYS_SIGMA_LIM) {
    683         Mlist[Nbright] = list[N];
    684         dMlist[Nbright] = dlist[N];
    685         Nbright ++;
    686       }
    687       N++;
    688     }
    689     /* N_onMosaic[i] is all measurements, N is good measurements */
    690 
    691     /* too few good measurements or too many bad measurements (skip in PoorImages run) */
    692     if (!PoorImages) {
    693       mark = (N < IMAGE_TOOFEW) || (N < IMAGE_GOOD_FRACTION*N_onMosaic[i]);
    694       if (mark) {
    695         if (VERBOSE2) { fprintf (stderr, "marked mosaic %s ("OFF_T_FMT"), ("OFF_T_FMT" < %d) || ("OFF_T_FMT" < %f*"OFF_T_FMT")\n", image[MosaicToImage[i][0]].name,  i,  N, IMAGE_TOOFEW,  N, IMAGE_GOOD_FRACTION,  N_onMosaic[i]); }
    696         mosaic[i].flags |= ID_IMAGE_PHOTOM_FEW;
    697         Nfew ++;
    698       } else {
    699         mosaic[i].flags &= ~ID_IMAGE_PHOTOM_FEW;
    700       }
    701     }
    702     liststats (list, dlist, N, &stats);
    703     if (VERBOSE2 && PoorImages) fprintf (stderr, "Mmos: %f %f %d "OFF_T_FMT"\n", stats.mean, stats.sigma, stats.Nmeas,  N);
    704 
    705     mosaic[i].Mcal  = stats.mean;
    706     mosaic[i].dMcal = stats.error;
    707     mosaic[i].nFitPhotom = N;
    708     mosaic[i].Xm    = 100.0*log10(stats.chisq);
    709 
    710     plot_setMcal (list, N, &stats, CLOUD_TOLERANCE);
    711 
    712     // bright end scatter
    713     liststats (Mlist, dMlist, Nbright, &stats);
    714     mosaic[i].dMsys = stats.sigma;
    715 
    716     if (mosaic[i].Mcal < -CLOUD_TOLERANCE) {
    717       mosaic[i].Mcal = 0.0;
    718     }
    719 
    720     // minUbercalDist calculated here is the min value for any star owned by this image
    721     // since this particular image is tied to that star, bump its distance by 1
    722     mosaic[i].ubercalDist = minUbercalDist + 1;
    723 
    724     // propagate ubercalDist to the images
    725     for (j = 0; j < MosaicN_Image[i]; j++) {
    726       off_t im = MosaicToImage[i][j];
    727       image[im].ubercalDist = mosaic[i].ubercalDist;
    728       // fprintf (stderr, "%d %d %d\n", (int) i, (int) im, image[im].ubercalDist);
    729     }
    730   }
    731   free (list);
    732   free (dlist);
    733   free (Mlist);
    734   free (dMlist);
    735 
    736   fprintf (stderr, "%d mosaics marked having too few measurements (Nbad: %d, Ncal: %d, Ngrid: %d, Nrel: %d, Nsys: %d)\n", Nfew, Nbad, Ncal, Ngrid, Nrel, Nsys);
     740
     741  SetMmosInfo info;
     742  SetMmosInfoInit (&info, Nmax, TRUE, PoorImages);
     743
     744  for (i = 0; i < Nmosaic; i++) {
     745    setMmos_mosaic (&mosaic[i], i, image, catalog, &info, flatcorr);
     746  }
     747  SetMmosInfoFree (&info);
     748
     749  npass_output ++;
     750
     751  fprintf (stderr, "%d mosaics marked having too few measurements (Nbad: %d, Ncal: %d, Ngrid: %d, Nrel: %d, Nsys: %d)\n", info.Nfew, info.Nbad, info.Ncal, info.Ngrid, info.Nrel, info.Nsys);
    737752
    738753  if (PoorImages) {
     
    744759}
    745760 
     761// 'mosaic' is a pointer to the current mosaic of interest (Nmos)
     762int setMmos_mosaic (Mosaic *myMosaic, off_t Nmos, Image *image, Catalog *catalog, SetMmosInfo *info, FlatCorrectionTable *flatcorr) {
     763
     764  Image *imageReal;
     765  off_t j, NimageReal;
     766
     767  StatType stats;
     768  liststats_setmode (&stats, STATMODE);
     769
     770  double *list   = info->list;
     771  double *dlist  = info->dlist;
     772  double *Mlist  = info->Mlist;
     773  double *dMlist = info->dMlist;
     774
     775  assert (Nmos >= 0);
     776  assert (Nmos < Nmosaic);
     777
     778  imageReal = getimages (&NimageReal, NULL);
     779
     780  /* on PoorImages run, skip good images */
     781  if (info->PoorImages) {
     782    int bad = myMosaic[0].flags & (ID_IMAGE_PHOTOM_FEW | ID_IMAGE_PHOTOM_POOR | ID_IMAGE_PHOTOM_SKIP);
     783    if (!bad) return TRUE;
     784  }     
     785
     786  // UBERCAL image: if this is an ubercal image, set minUbercalDist to 0:
     787  // we optionally do not recalibrate images with UBERCAL zero points
     788  if (myMosaic[0].flags & ID_IMAGE_PHOTOM_UBERCAL) {
     789    myMosaic[0].ubercalDist = 0;
     790    // propagate ubercalDist to the images
     791    for (j = 0; j < MosaicN_Image[Nmos]; j++) {
     792      off_t im = MosaicToImage[Nmos][j];
     793      assert (im < NimageReal);
     794      assert (im >= 0);
     795      image[im].ubercalDist = myMosaic[0].ubercalDist;
     796      // fprintf (stderr, "%d %d %d\n", (int) i, (int) im, image[im].ubercalDist);
     797    }
     798    if (KEEP_UBERCAL) return TRUE;
     799  }
     800
     801  int Nsecfilt = GetPhotcodeNsecfilt ();
     802
     803  int minUbercalDist = 1000;
     804
     805  // do not modify the calibration for mosaics with partial images loaded (skipCal TRUE)
     806  if (myMosaic[0].skipCal) {
     807    info->Nskip ++;
     808    return TRUE;
     809  }
     810
     811  int testImage = FALSE;
     812  // testImage |= (abs(myMosaic[0].start - 1324104046) < 10);
     813  // testImage |= (abs(myMosaic[0].start - 1324103823) < 10);
     814  // testImage |= (abs(myMosaic[0].start - 1323003245) < 10);
     815  // testImage |= (abs(myMosaic[0].start - 1323003069) < 10);
     816  // testImage |= (abs(myMosaic[0].start - 1323003125) < 10);
     817  // testImage |= (abs(myMosaic[0].start - 1323003300) < 10);
     818  // testImage |= (abs(myMosaic[0].start - 1323003365) < 10);
     819  // testImage |= (abs(myMosaic[0].start - 1323003191) < 10);
     820  // testImage |= (abs(myMosaic[0].start - 1323003014) < 10);
     821  // testImage |= (abs(myMosaic[0].start - 1323003484) < 10);
     822  // testImage |= (abs(myMosaic[0].start - 1323003419) < 10);
     823  // testImage |= (abs(myMosaic[0].start - 1323002949) < 10);
     824
     825  FILE *fout = NULL;
     826  if (testImage) {
     827    char filename[64];
     828    snprintf (filename, 64, "test.%05d.%02d.dat", (int) Nmos, npass_output);
     829    fout = fopen (filename, "w");
     830  }
     831
     832  // number of stars to measure the bright-end scatter
     833  int Nbright = 0;
     834
     835  int N = 0;
     836  for (j = 0; j < N_onMosaic[Nmos]; j++) {
     837    float Msys, Mrel, Mcal, Mgrid, Mflat;
     838     
     839    off_t m = MosaicToMeasure[Nmos][j];
     840    off_t c = MosaicToCatalog[Nmos][j];
     841     
     842    if (fout) {
     843      Mcal  = getMcal  (m, c, flatcorr, catalog);
     844      Mgrid = getMgrid (m, c);
     845      Mrel  = getMrel  (catalog, m, c);
     846      Mflat = getMflat (m, c, flatcorr, catalog);
     847
     848      off_t n = catalog[c].measureT[m].averef;
     849      Msys = PhotSysTiny (&catalog[c].measureT[m], &catalog[c].averageT[n], &catalog[c].secfilt[n*Nsecfilt]);
     850
     851      float delta = Msys - Mrel - Mcal - Mgrid + Mflat;
     852
     853      int isBad = (catalog[c].measureT[m].dbFlags & MEAS_BAD);
     854
     855      fprintf (fout, "%f %f : %f %f %f %f %f  : %f %d\n", catalog[c].averageT[n].R, catalog[c].averageT[n].D, Msys, Mrel, Mcal, Mgrid, Mflat, delta, isBad);
     856    }
     857
     858    if (catalog[c].measureT[m].dbFlags & MEAS_BAD) {
     859      info->Nbad ++;
     860      continue;
     861    }
     862    Mcal  = getMcal  (m, c, flatcorr, catalog);
     863    if (isnan(Mcal)) {
     864      info->Ncal++;
     865      continue;
     866    }
     867    Mgrid = getMgrid (m, c);
     868    if (isnan(Mgrid)) {
     869      info->Ngrid ++;
     870      continue;
     871    }
     872    Mrel  = getMrel  (catalog, m, c);
     873    if (isnan(Mrel)) {
     874      info->Nrel ++;
     875      continue;
     876    }
     877     
     878    // image.Mcal is not supposed to include the flat-field correction, so we need to
     879    // apply that offset as well here for this image (in other words, each detection is
     880    // being compared to the model, excluding the zero point, Mcal.  The model includes
     881    // the flat-correction.  NOTE the sign of Mflat (Image.Mcal = Measure.Mcal - Mflat)
     882
     883    Mflat = getMflat (m, c, flatcorr, catalog);
     884
     885    off_t n = catalog[c].measureT[m].averef;
     886    Msys = PhotSysTiny (&catalog[c].measureT[m], &catalog[c].averageT[n], &catalog[c].secfilt[n*Nsecfilt]);
     887    if (isnan(Msys)) {
     888      info->Nsys++;
     889      continue;
     890    }
     891
     892    PhotCode *code = GetPhotcodebyCode (catalog[c].measureT[m].photcode);
     893    if (!code) goto skip;
     894    if (code->equiv < 1) goto skip;
     895    int Nsec = GetPhotcodeNsec (code->equiv);
     896    if (Nsec == -1) goto skip;
     897    minUbercalDist = MIN (catalog[c].secfilt[n*Nsecfilt + Nsec].ubercalDist, minUbercalDist);
     898
     899  skip:
     900    assert (N < info->Nmax);
     901    assert (N >= 0);
     902    assert (Nbright < info->Nmax);
     903    assert (Nbright >= 0);
     904
     905    list[N]  = Msys - Mrel - Mcal - Mgrid + Mflat;
     906    dlist[N] = MAX (catalog[c].measureT[m].dM, MIN_ERROR);
     907    if (catalog[c].measureT[m].dM < IMFIT_SYS_SIGMA_LIM) {
     908      Mlist[Nbright] = list[N];
     909      dMlist[Nbright] = dlist[N];
     910      Nbright ++;
     911    }
     912    N++;
     913  }
     914  /* N_onMosaic[Nmos] is all measurements, N is good measurements */
     915
     916  if (fout) {
     917    fclose (fout);
     918  }
     919
     920  /* too few good measurements or too many bad measurements (skip in PoorImages run) */
     921  if (!info->PoorImages) {
     922    int mark = (N < IMAGE_TOOFEW) || (N < IMAGE_GOOD_FRACTION*N_onMosaic[Nmos]);
     923    if (mark) {
     924      if (VERBOSE2) { fprintf (stderr, "marked mosaic %s ("OFF_T_FMT"), (%d < %d) || (%d < %f*"OFF_T_FMT")\n", image[MosaicToImage[Nmos][0]].name,  Nmos,  N, IMAGE_TOOFEW,  N, IMAGE_GOOD_FRACTION,  N_onMosaic[Nmos]); }
     925      myMosaic[0].flags |= ID_IMAGE_PHOTOM_FEW;
     926      info->Nfew ++;
     927      if (testImage) {
     928        fprintf (stderr, "NOTE: *** marked test image poor : %d %d %d***\n", (int) N, (int) IMAGE_TOOFEW, (int) (IMAGE_GOOD_FRACTION*N_onMosaic[Nmos]));
     929      }
     930    } else {
     931      myMosaic[0].flags &= ~ID_IMAGE_PHOTOM_FEW;
     932    }
     933  }
     934
     935  liststats (list, dlist, NULL, N, &stats);
     936  if (VERBOSE2 && info->PoorImages) fprintf (stderr, "Mmos: %f %f %d %d\n", stats.mean, stats.sigma, stats.Nmeas, N);
     937
     938  myMosaic[0].Mcal  = stats.mean;
     939  myMosaic[0].dMcal = stats.error;
     940  myMosaic[0].nFitPhotom = N;
     941  myMosaic[0].Xm    = 100.0*log10(stats.chisq);
     942
     943  if (testImage) {
     944    fprintf (stderr, "test image %d (%d) %f %f %d ... ", (int) Nmos, myMosaic[0].start, stats.mean, stats.error, myMosaic[0].nFitPhotom);
     945  }
     946
     947  plot_setMcal (list, N, &stats, CLOUD_TOLERANCE);
     948
     949  // bright end scatter
     950  liststats (Mlist, dMlist, NULL, Nbright, &stats);
     951  myMosaic[0].dMsys = stats.sigma;
     952
     953  if (myMosaic[0].Mcal < -CLOUD_TOLERANCE) {
     954    myMosaic[0].Mcal = 0.0;
     955  }
     956
     957  if (testImage) {
     958    fprintf (stderr, "%f %f  :  %d %f\n", myMosaic[0].Mcal, myMosaic[0].dMsys, myMosaic[0].Xm, pow(10.0, 0.01*myMosaic[0].Xm));
     959  }
     960
     961  // minUbercalDist calculated here is the min value for any star owned by this image
     962  // since this particular image is tied to that star, bump its distance by 1
     963  myMosaic[0].ubercalDist = minUbercalDist + 1;
     964
     965  // propagate ubercalDist to the images
     966  for (j = 0; j < MosaicN_Image[Nmos]; j++) {
     967    off_t im = MosaicToImage[Nmos][j];
     968    image[im].ubercalDist = myMosaic[0].ubercalDist;
     969    // fprintf (stderr, "%d %d %d\n", (int) i, (int) im, image[im].ubercalDist);
     970  }
     971  return TRUE;
     972}
     973 
     974int setMmos_threaded (Catalog *catalog, int PoorImages, FlatCorrectionTable *flatcorr) {
     975
     976  int i;
     977  off_t N;
     978
     979  Image *image = getimages (&N, NULL);
     980
     981  fprintf (stderr, "limiting negative clouds to %f\n", CLOUD_TOLERANCE);
     982
     983  if (PoorImages) {
     984    // XXX use bad stars and measurements for PoorImages? or not?
     985    // IMAGE_BAD = STAR_BAD = MEAS_BAD = 0;
     986    IMAGE_BAD = 0;
     987  }
     988
     989  off_t Nmax = 0;
     990  for (i = 0; i < Nmosaic; i++) {
     991    Nmax = MAX (Nmax, N_onMosaic[i]);
     992  }
     993
     994  SetMmosInfo summary;
     995  SetMmosInfoInit (&summary, Nmax, FALSE, PoorImages);
     996
     997  pthread_attr_t attr;
     998  pthread_attr_init (&attr);
     999  pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
     1000 
     1001  pthread_t *threads;
     1002  ALLOCATE (threads, pthread_t, NTHREADS);
     1003
     1004  ThreadInfo *threadinfo;
     1005  ALLOCATE (threadinfo, ThreadInfo, NTHREADS);
     1006
     1007  // each time this function is called, we cycle through the available mosaics
     1008  // make sure we start at 0
     1009  nextMosaic = 0;;
     1010
     1011  // launch N worker threads
     1012  for (i = 0; i < NTHREADS; i++) {
     1013    threadinfo[i].entry = i;
     1014    threadinfo[i].state = THREAD_RUN;
     1015    threadinfo[i].catalog  =  catalog;
     1016    threadinfo[i].image    =    image;
     1017    threadinfo[i].flatcorr = flatcorr;
     1018    SetMmosInfoInit (&threadinfo[i].info, Nmax, FALSE, PoorImages);
     1019    pthread_create (&threads[i], NULL, setMmos_worker, &threadinfo[i]);
     1020  }
     1021  pthread_attr_destroy (&attr);
     1022
     1023  // wait until all threads have finished
     1024  while (1) {
     1025    int allDone = TRUE;
     1026    for (i = 0; i < NTHREADS; i++) {
     1027      if (threadinfo[i].state == THREAD_RUN) allDone = FALSE;
     1028    }
     1029    if (allDone) {
     1030      break;
     1031    }
     1032    usleep (500000);
     1033  }
     1034
     1035  // all threads are done, free the threads array and grab the info
     1036  free (threads);
     1037 
     1038  // report stats & summary from the threads
     1039  for (i = 0; i < NTHREADS; i++) {
     1040    fprintf (stderr, "setMmos thread %d : %d mosaics marked having too few measurements (Nbad: %d, Ncal: %d, Ngrid: %d, Nrel: %d, Nsys: %d), %d partials skipped\n",
     1041             i,
     1042             threadinfo[i].info.Nfew,
     1043             threadinfo[i].info.Nbad,
     1044             threadinfo[i].info.Ncal,
     1045             threadinfo[i].info.Ngrid,
     1046             threadinfo[i].info.Nrel,
     1047             threadinfo[i].info.Nsys,
     1048             threadinfo[i].info.Nskip);
     1049    SetMmosInfoAccum (&summary, &threadinfo[i].info);
     1050  }
     1051  fprintf (stderr, "total : %d mosaics marked having too few measurements (Nbad: %d, Ncal: %d, Ngrid: %d, Nrel: %d, Nsys: %d), %d partials skipped\n",
     1052           summary.Nfew,
     1053           summary.Nbad,
     1054           summary.Ncal,
     1055           summary.Ngrid,
     1056           summary.Nrel,
     1057           summary.Nsys,
     1058           summary.Nskip);
     1059  free (threadinfo);
     1060
     1061  npass_output ++;
     1062
     1063  if (PoorImages) {
     1064    IMAGE_BAD = ID_IMAGE_PHOTOM_POOR | ID_IMAGE_PHOTOM_FEW | ID_IMAGE_PHOTOM_SKIP;
     1065    STAR_BAD  = ID_STAR_POOR | ID_STAR_FEW;
     1066    MEAS_BAD  = ID_MEAS_NOCAL | ID_MEAS_POOR_PHOTOM | ID_MEAS_SKIP_PHOTOM | ID_MEAS_AREA;
     1067  }
     1068  return TRUE;
     1069}
     1070
     1071void *setMmos_worker (void *data) {
     1072
     1073  ThreadInfo *threadinfo = data;
     1074
     1075  SetMmosInfo results;
     1076  SetMmosInfoInit (&results, threadinfo->info.Nmax, TRUE, threadinfo->info.PoorImages); // allocate list, dlist arrays here
     1077
     1078  while (1) {
     1079
     1080    off_t i = getNextMosaicForThread();
     1081    if (i == -1) {
     1082      threadinfo->state = THREAD_DONE;
     1083      return NULL;
     1084    }
     1085
     1086    Catalog *catalog = threadinfo->catalog;
     1087    FlatCorrectionTable *flatcorr = threadinfo->flatcorr;
     1088    Image *image = threadinfo->image;
     1089
     1090    setMmos_mosaic (&mosaic[i], i, image, catalog, &results, flatcorr);
     1091    SetMmosInfoAccum (&threadinfo->info, &results);
     1092  }
     1093
     1094  SetMmosInfoFree (&results);
     1095  return NULL;
     1096}
     1097
    7461098// When we rationalize the images/mosaics, we are driving the negative cloud images back
    7471099// to 0.0.  At the same time, we make a guess to the effective impact on all other images,
     
    9551307  for (i = 0; i < Nmosaic; i++) {
    9561308    if (mosaic[i].flags & IMAGE_BAD) continue;
     1309    if (mosaic[i].skipCal) continue;
    9571310    list[n] = mosaic[i].Mcal;
    9581311    dlist[n] = 1;
     
    9601313  }
    9611314
    962   liststats (list, dlist, n, &stats);
     1315  liststats_setmode (&stats, "MEAN");
     1316
     1317  liststats (list, dlist, NULL, n, &stats);
    9631318  free (list);
    9641319  free (dlist);
     
    9811336  n = 0;
    9821337  for (i = 0; i < Nmosaic; i++) {
    983 
    9841338    if (mosaic[i].flags & IMAGE_BAD) continue;
     1339    if (mosaic[i].skipCal) continue;
    9851340    list[n] = mosaic[i].dMcal;
    9861341    dlist[n] = 1;
     
    9881343  }
    9891344
    990   liststats (list, dlist, n, &stats);
     1345  liststats_setmode (&stats, "MEAN");
     1346
     1347  liststats (list, dlist, NULL, n, &stats);
    9911348  free (list);
    9921349  free (dlist);
     
    10111368  for (i = 0; i < Nmosaic; i++) {
    10121369    if (mosaic[i].flags & IMAGE_BAD)  continue;
     1370    if (mosaic[i].skipCal) continue;
    10131371
    10141372    N = 0;
     
    10321390  // fprintf (stderr, "Nmosaic: "OFF_T_FMT", n: "OFF_T_FMT"\n",  Nmosaic,  n);
    10331391
    1034   liststats (list, dlist, n, &stats);
     1392  liststats_setmode (&stats, "MEAN");
     1393
     1394  liststats (list, dlist, NULL, n, &stats);
    10351395  free (list);
    10361396  free (dlist);
     
    10531413  n = 0;
    10541414  for (i = 0; i < Nmosaic; i++) {
    1055 
    10561415    if (mosaic[i].flags & IMAGE_BAD) continue;
     1416    if (mosaic[i].skipCal) continue;
    10571417    list[n] = pow(10.0, 0.01*mosaic[i].Xm);
    10581418    dlist[n] = 1;
     
    10601420  }
    10611421
    1062   liststats (list, dlist, n, &stats);
     1422  liststats_setmode (&stats, "MEAN");
     1423
     1424  liststats (list, dlist, NULL, n, &stats);
    10631425  free (list);
    10641426  free (dlist);
     
    10721434  double *mlist, *slist, *dlist;
    10731435  double MaxOffset, MedOffset, MaxScatter;
    1074   StatType stats;
    10751436
    10761437  if (!MOSAIC_ZEROPT) return;
     
    10851446  for (i = N = 0; i < Nmosaic; i++) {
    10861447    if (mosaic[i].flags & IMAGE_BAD) continue;
     1448    if (mosaic[i].skipCal) continue;
    10871449    mlist[N] = mosaic[i].Mcal;
    10881450    slist[N] = mosaic[i].dMcal;
     
    10901452    N++;
    10911453  }
    1092   initstats ("MEAN");
    1093   liststats (mlist, dlist, N, &stats);
     1454
     1455  StatType stats;
     1456  liststats_setmode (&stats, "MEAN");
     1457
     1458  liststats (mlist, dlist, NULL, N, &stats);
    10941459  MaxOffset = MAX (IMAGE_OFFSET, 2*stats.sigma);
    10951460  MedOffset = stats.median;
    1096   liststats (slist, dlist, N, &stats);
     1461
     1462  liststats (slist, dlist, NULL, N, &stats);
    10971463  MaxScatter = MAX (IMAGE_SCATTER, 2*stats.median);
    10981464  fprintf (stderr, "Mrel: %f, dMrel: %f, Max Scatter: %f, Max Offset: %f\n", MedOffset, stats.median, MaxScatter, MaxOffset);
     
    11021468    // if we are keeping ubercal sacrosanct, then we should not be allowed to break them...
    11031469    if (KEEP_UBERCAL && (mosaic[i].flags & ID_IMAGE_PHOTOM_UBERCAL)) continue;
     1470
     1471    if (mosaic[i].flags & (ID_IMAGE_PHOTOM_FEW | ID_IMAGE_PHOTOM_SKIP)) continue;
     1472    if (mosaic[i].skipCal) continue;
    11041473
    11051474    mark = FALSE;
     
    11211490
    11221491  fprintf (stderr, OFF_T_FMT" mosaics marked poor ("OFF_T_FMT" scatter, "OFF_T_FMT" offset)\n",  Nmark, Nscatter, Noffset);
    1123   initstats (STATMODE);
     1492
    11241493  free (mlist);
    11251494  free (slist);
  • trunk/Ohana/src/relphot/src/StarOps.c

    r33651 r33963  
    22
    33static int Nmax;
    4 static double *list;
    5 static double *dlist;
    6 
    7 // When we rationalize the images/mosaics, we are driving the negative cloud images back
    8 // to 0.0.  At the same time, we make a guess to the effective impact on all other images,
    9 // driven by the coupling of common stars.  This array carries the impact of those offsets
    10 // on each star
    11 static double *Moffset;
    12 
     4
     5typedef struct {
     6  int Nfew;
     7  int Ncode;
     8  int Nsys;
     9  int Nbad;
     10  int Ncal;
     11  int Nmos;
     12  int Ngrid;
     13  double *list;
     14  double *dlist;
     15  double *wlist;
     16  double *aplist;
     17  double *daplist;
     18} SetMrelInfo;
     19
     20enum {THREAD_RUN, THREAD_DONE};
     21
     22typedef struct {
     23  int entry;
     24  int state;
     25  Catalog *catalog;
     26  int Ncatalog;
     27  FlatCorrectionTable *flatcorr;
     28  SetMrelInfo summary;
     29} ThreadInfo;
     30
     31// ** internal functions:
     32void *setMrel_worker (void *data);
     33int setMrel_threaded (Catalog *catalog, int Ncatalog, FlatCorrectionTable *flatcorr);
     34int setMrel_catalog (Catalog *catalog, int Nc, int pass, FlatCorrectionTable *flatcorr, SetMrelInfo *results, int Nsecfilt);
     35int print_measure_set (Average *average, SecFilt *secfilt, Measure *measure);
     36
     37// we want to allocate the stats list,dlist arrays only once (or once per thread).
     38// this function finds the largest array so we can allocate that max size when needed
    1339void initMrel (Catalog *catalog, int Ncatalog) {
    1440
     
    2147    }
    2248  }
    23 
    24   ALLOCATE (list,    double, MAX (1, Nmax));
    25   ALLOCATE (dlist,   double, MAX (1, Nmax));
    26   ALLOCATE (Moffset, double, MAX (1, Nmax));
    2749
    2850
     
    4769}
    4870
    49 int setMrel (Catalog *catalog, int Ncatalog, FlatCorrectionTable *flatcorr) {
    50 
    51   off_t j, k, m;
    52   int i, N, Nfew, Nsys, Nbad, Ncal, Nmos, Ngrid;
    53   float Msys, Mcal, Mmos, Mgrid;
    54   StatType stats;
    55 
    56   int Nsecfilt = GetPhotcodeNsecfilt ();
    57   Nfew = Nsys = Nbad = Ncal = Nmos = Ngrid = 0;
    58 
    59   for (i = 0; i < Ncatalog; i++) {
    60     for (j = 0; j < catalog[i].Naverage; j++) {
    61       // XXX accumulate all secfilt values in a single pass?
    62 
    63       int minUbercalDist = 1000;
    64 
    65       int Ns;
    66       for (Ns = 0; Ns < Nphotcodes; Ns++) {
    67 
    68         int thisCode = photcodes[Ns][0].code;
    69         int Nsec = GetPhotcodeNsec(thisCode);
    70 
    71         /* calculate the average mag in this SEC photcode for a single star */
    72 
    73         // skip bad stars
    74         if (catalog[i].secfilt[Nsecfilt*j+Nsec].flags & STAR_BAD) continue;
    75 
    76         N = 0;
    77         m = catalog[i].averageT[j].measureOffset;
    78         for (k = 0; k < catalog[i].averageT[j].Nmeasure; k++, m++) {
    79 
    80           // skip measurements that do not match the current photcode
    81           PhotCode *code = GetPhotcodebyCode (catalog[i].measureT[m].photcode);
    82           if (!code) continue;
    83           if (code->equiv != thisCode) { continue; }
    84 
    85           if (catalog[i].measureT[m].dbFlags & MEAS_BAD) { Nbad ++; continue; }
    86 
    87           if (getImageEntry (m, i) < 0) {
    88             Mcal = Mmos = Mgrid = 0;
    89           } else {
    90             Mcal  = getMcal  (m, i, flatcorr, catalog);
    91             if (isnan(Mcal)) { Ncal ++; continue; }
    92             Mmos  = getMmos  (m, i);
    93             if (isnan(Mmos)) { Nmos ++; continue; }
    94             Mgrid = getMgrid (m, i);
    95             if (isnan(Mgrid)) { Ngrid++; continue; }
    96           }
    97 
    98           Msys = PhotSysTiny (&catalog[i].measureT[m], &catalog[i].averageT[j], &catalog[i].secfilt[j*Nsecfilt]);
    99           if (isnan(Msys)) { Nsys++; continue; }
    100           list[N] = Msys - Mcal - Mmos - Mgrid;
    101 
    102           int myUbercalDist = getUbercalDist(m,i);
    103           minUbercalDist = MIN(minUbercalDist, myUbercalDist);
    104 
    105           // dlist gives the error, which is used as the weight in WT_MEAN.
    106           // we can modify the resulting weight in a few ways:
    107           // 1) MIN_ERROR guarantees a floor
    108           // 2) photomErrSys is added in quadrature as a sytematic error, set per photcode
    109           // 3) UBERCAL measurements can have their weight increased by a big factor to help tie down the averages
    110           // 4) some reference photcode of some kind can be specified as fixed and have a high weight
    111           dlist[N] = MAX (hypot(catalog[i].measureT[m].dM, code->photomErrSys), MIN_ERROR);
    112 
    113           // up-weight the ubercal values (or convergence can take a long time...)
    114           if (catalog[i].measureT[m].dbFlags & ID_MEAS_PHOTOM_UBERCAL) {
    115             dlist[N] = MAX (0.1*catalog[i].measureT[m].dM, MIN_ERROR);
    116           }
    117 
    118           // tie down reference photometry if the -refcode (code) option is selected
    119           // eg, -refcode g_SDSS
    120           // this probably makes no sense in the context of multifilter analysis
    121           if (refPhotcode) {
    122             if (code->code == refPhotcode->code) {
    123               // tiny error -> large weight
    124               // dlist[N] = MAX (0.01*catalog[i].measureT[m].dM, MIN_ERROR);
    125               dlist[N] = 0.0001;
    126             }
    127           }
    128           N++;
    129         }
    130 
    131         // when performing the grid analysis, STAR_TOOFEW will be set to 1;
    132         if (N <= STAR_TOOFEW) { /* too few measurements */
    133           // fprintf (f, "%10.6f %10.6f %d %d %d\n", catalog[i].averageT[j].R, catalog[i].averageT[j].D, catalog[i].measureT[catalog[i].averageT[j].measureOffset].imageID, N, STAR_TOOFEW);
    134           catalog[i].secfilt[Nsecfilt*j+Nsec].flags |= ID_STAR_FEW;
    135           Nfew ++;
    136         } else {
    137           catalog[i].secfilt[Nsecfilt*j+Nsec].flags &= ~ID_STAR_FEW;
    138         }       
    139 
    140         liststats (list, dlist, N, &stats);
    141        
    142         catalog[i].secfilt[Nsecfilt*j+Nsec].M  = stats.mean;
    143         catalog[i].secfilt[Nsecfilt*j+Nsec].dM = stats.sigma;
    144         catalog[i].secfilt[Nsecfilt*j+Nsec].Xm = (stats.Nmeas > 1) ? 100.0*log10(stats.chisq + 1e-4) : NAN_S_SHORT;
    145        
    146         catalog[i].secfilt[Nsecfilt*j+Nsec].ubercalDist = minUbercalDist;
    147       }
    148     }
    149   }
    150   fprintf (stderr, "%d stars marked having too few measurements (Nbad: %d, Ncal: %d, Nmos: %d, Ngrid: %d, Nsys: %d)\n", Nfew, Nbad, Ncal, Nmos, Ngrid, Nsys);
    151 
    152   return (TRUE);
    153 }
    154 
    155 int print_measure_set (Average *average, SecFilt *secfilt, Measure *measure) {
    156 
    157   off_t k;
    158 
    159   int Nsecfilt = GetPhotcodeNsecfilt ();
    160 
    161   off_t m = average[0].measureOffset;
    162 
    163   for (k = 0; k < average[0].Nmeasure; k++, m++) {
    164     fprintf (stderr, "meas: %08x\n", measure[m].dbFlags);
    165   }
    166 
    167   int Ns;
    168   for (Ns = 0; Ns < Nsecfilt; Ns++) {
    169     fprintf (stderr, "secf: %08x\n", secfilt[Ns].flags);
    170   }
    171   return 1;
    172 }
    173 
    174 # define MARK_SKIP_MEAS \
    175   catalog[i].measureT[m].dbFlags |= ID_MEAS_SKIP_PHOTOM; \
    176   catalog[i].measure [m].dbFlags |= ID_MEAS_SKIP_PHOTOM;
     71void SetMrelInfoInit (SetMrelInfo *results, int allocLists) {
     72  results->Nfew  = 0;
     73  results->Ncode  = 0;
     74  results->Nsys  = 0;
     75  results->Nbad  = 0;
     76  results->Ncal  = 0;
     77  results->Nmos  = 0;
     78  results->Ngrid = 0;
     79  if (allocLists) {
     80    ALLOCATE (results->list,  double, Nmax);
     81    ALLOCATE (results->dlist, double, Nmax);
     82    ALLOCATE (results->wlist, double, Nmax);
     83  }
     84}
     85
     86void SetMrelInfoFree (SetMrelInfo *results) {
     87  free (results->list);
     88  free (results->dlist);
     89  free (results->wlist);
     90}
     91
     92void SetMrelInfoAccum (SetMrelInfo *summary, SetMrelInfo *results) {
     93  summary->Nfew  += results->Nfew ;
     94  summary->Ncode  += results->Ncode ;
     95  summary->Nsys  += results->Nsys ;
     96  summary->Nbad  += results->Nbad ;
     97  summary->Ncal  += results->Ncal ;
     98  summary->Nmos  += results->Nmos ;
     99  summary->Ngrid += results->Ngrid;
     100}
     101
     102// mutex to lock setMrel_worker operations
     103static pthread_mutex_t setMrel_mutex = PTHREAD_MUTEX_INITIALIZER;
     104static int nextCatalog = 0;
     105
     106// we have an array of catalogs (catalog, Ncatalog).  we need to hand out catalogs one at a time to
     107// the worker threads as they need
     108off_t getNextCatalogForThread (int Ncatalog) {
     109
     110  pthread_mutex_lock (&setMrel_mutex);
     111  if (nextCatalog >= Ncatalog) {
     112    pthread_mutex_unlock (&setMrel_mutex);
     113    return (-1);
     114  }
     115  int thisCatalog = nextCatalog;
     116  nextCatalog ++;
     117
     118  pthread_mutex_unlock (&setMrel_mutex);
     119  return (thisCatalog);
     120}
    177121
    178122// setMrel and setMrelOutput are extremely similar, but have slightly different implications:
     
    180124// * setMrelOutput skips stars for which there are too few good measurements
    181125// * setMrelOutput is meant to be called repeatedly, relaxing the criteria for 'good' on each pass
    182 
    183 // setMave is also similar to the above.  but:
    184 // * setMave is called by relphot -update-objects
    185 // * setMave excludes all detections with (PSF_QF < 0.85), setMrelOutput allows these for PASS > 2
    186 // * setMave updates 2MASS average flags
    187 // * setMave updates average EXT flags (PS1 and 2MASS)
     126// * setMrelOutput updates 2MASS average flags
     127// * setMrelOutput updates average EXT flags (PS1 and 2MASS)
     128
     129int setMrel (Catalog *catalog, int Ncatalog, FlatCorrectionTable *flatcorr) {
     130
     131  int i;
     132
     133  if (NTHREADS) {
     134    int status = setMrel_threaded (catalog, Ncatalog, flatcorr);
     135    return status;
     136  }
     137
     138  int Nsecfilt = GetPhotcodeNsecfilt ();
     139
     140  SetMrelInfo summary, results;
     141  SetMrelInfoInit (&summary, FALSE);
     142  SetMrelInfoInit (&results, TRUE);
     143
     144  for (i = 0; i < Ncatalog; i++) {
     145    // pass == -1 for anything other than the final pass
     146    setMrel_catalog (catalog, i, -1, flatcorr, &results, Nsecfilt);
     147    SetMrelInfoAccum (&summary, &results);
     148  }
     149  if (VERBOSE2) fprintf (stderr, "%d stars with no data in photcode, %d stars marked having too few measurements (Nbad: %d, Ncal: %d, Nmos: %d, Ngrid: %d, Nsys: %d)\n", summary.Ncode, summary.Nfew, summary.Nbad, summary.Ncal, summary.Nmos, summary.Ngrid, summary.Nsys);
     150
     151  SetMrelInfoFree (&results);
     152
     153  return (TRUE);
     154}
     155
    188156int setMrelOutput (Catalog *catalog, int Ncatalog, int pass, FlatCorrectionTable *flatcorr) {
    189157
    190   int i, N;
    191   off_t j, k, m, Nmax;
    192   float Msys, Mcal, Mmos, Mgrid, Map;
    193   double *list, *dlist, *aplist, *daplist;
     158  int i;
     159
     160  int Nsecfilt = GetPhotcodeNsecfilt ();
     161
     162  SetMrelInfo summary, results;
     163  SetMrelInfoInit (&summary, FALSE);
     164  SetMrelInfoInit (&results, TRUE); // allocates results->list,dlist,wlist
     165  ALLOCATE (results.aplist, double, Nmax);
     166  ALLOCATE (results.daplist, double, Nmax);
     167
     168  for (i = 0; i < Ncatalog; i++) {
     169    setMrel_catalog  (catalog, i, pass, flatcorr, &results, Nsecfilt); // XXX add arguments as needed for options
     170    SetMrelInfoAccum (&summary, &results);
     171  }
     172  if (VERBOSE2) fprintf (stderr, "%d stars with no data in photcode, %d stars marked having too few measurements (Nbad: %d, Ncal: %d, Nmos: %d, Ngrid: %d, Nsys: %d)\n", summary.Ncode, summary.Nfew, summary.Nbad, summary.Ncal, summary.Nmos, summary.Ngrid, summary.Nsys);
     173
     174  SetMrelInfoFree (&results);
     175  free (results.aplist);
     176  free (results.daplist);
     177  return (TRUE);
     178}
     179
     180int setMrel_threaded (Catalog *catalog, int Ncatalog, FlatCorrectionTable *flatcorr) {
     181
     182  int i;
     183
     184  SetMrelInfo summary;
     185  SetMrelInfoInit (&summary, FALSE);
     186
     187  pthread_attr_t attr;
     188  pthread_attr_init (&attr);
     189  pthread_attr_setdetachstate (&attr, PTHREAD_CREATE_DETACHED);
     190 
     191  pthread_t *threads;
     192  ALLOCATE (threads, pthread_t, NTHREADS);
     193
     194  ThreadInfo *threadinfo;
     195  ALLOCATE (threadinfo, ThreadInfo, NTHREADS);
     196
     197  // each time this function is called, we cycle through the available catalogs.
     198  // make sure we start at 0
     199  nextCatalog = 0;;
     200
     201  // launch N worker threads
     202  for (i = 0; i < NTHREADS; i++) {
     203    threadinfo[i].entry = i;
     204    threadinfo[i].state = THREAD_RUN;
     205    threadinfo[i].catalog  =  catalog;
     206    threadinfo[i].Ncatalog = Ncatalog;
     207    threadinfo[i].flatcorr = flatcorr;
     208    SetMrelInfoInit (&threadinfo[i].summary, FALSE);
     209    pthread_create (&threads[i], NULL, setMrel_worker, &threadinfo[i]);
     210  }
     211  pthread_attr_destroy (&attr);
     212
     213  // wait until all threads have finished
     214  while (1) {
     215    int allDone = TRUE;
     216    for (i = 0; i < NTHREADS; i++) {
     217      if (threadinfo[i].state == THREAD_RUN) allDone = FALSE;
     218    }
     219    if (allDone) {
     220      break;
     221    }
     222    usleep (500000);
     223  }
     224
     225  // all threads are done, free the threads array and grab the info
     226  free (threads);
     227 
     228  // report stats & summary from the threads
     229  for (i = 0; i < NTHREADS; i++) {
     230    if (VERBOSE2) fprintf (stderr, "setMrel thread %d : %d stars with no data in photcode, %d stars marked having too few measurements (Nbad: %d, Ncal: %d, Nmos: %d, Ngrid: %d, Nsys: %d)\n",
     231             i,
     232             threadinfo[i].summary.Ncode,
     233             threadinfo[i].summary.Nfew,
     234             threadinfo[i].summary.Nbad,
     235             threadinfo[i].summary.Ncal,
     236             threadinfo[i].summary.Nmos,
     237             threadinfo[i].summary.Ngrid,
     238             threadinfo[i].summary.Nsys);
     239    SetMrelInfoAccum (&summary, &threadinfo[i].summary);
     240  }
     241  if (VERBOSE2) fprintf (stderr, "total : %d stars with no data in photcode, %d stars marked having too few measurements (Nbad: %d, Ncal: %d, Nmos: %d, Ngrid: %d, Nsys: %d)\n", summary.Ncode, summary.Nfew, summary.Nbad, summary.Ncal, summary.Nmos, summary.Ngrid, summary.Nsys);
     242  free (threadinfo);
     243
     244  return TRUE;
     245}
     246
     247void *setMrel_worker (void *data) {
     248
     249  ThreadInfo *threadinfo = data;
     250
     251  int Nsecfilt = GetPhotcodeNsecfilt ();
     252
     253  SetMrelInfo results;
     254  SetMrelInfoInit (&results, TRUE); // allocate list, dlist arrays here
     255
     256  while (1) {
     257
     258    off_t i = getNextCatalogForThread(threadinfo->Ncatalog);
     259    if (i == -1) {
     260      threadinfo->state = THREAD_DONE;
     261      return NULL;
     262    }
     263
     264    Catalog *catalog = threadinfo->catalog;
     265    FlatCorrectionTable *flatcorr = threadinfo->flatcorr;
     266
     267    // pass == -1 for anything other than the final pass
     268    setMrel_catalog (catalog, i, -1, flatcorr, &results, Nsecfilt);
     269    SetMrelInfoAccum (&threadinfo->summary, &results);
     270  }
     271
     272  SetMrelInfoFree (&results);
     273  return NULL;
     274}
     275
     276# define SKIP_THIS_MEAS(REASON) {                               \
     277    catalog[Nc].measureT[m].dbFlags |= ID_MEAS_SKIP_PHOTOM;     \
     278    if (catalog[Nc].measure) {                                  \
     279      catalog[Nc].measure [m].dbFlags |= ID_MEAS_SKIP_PHOTOM;   \
     280    }                                                           \
     281    results->REASON ++;                                         \
     282    continue; }
     283
     284
     285// setMrel_catalog is used in 3 different contexts:
     286
     287// * during the main relphot iterations:
     288// ** operations only apply to measureT / averageT
     289// ** we are applying the analysis to the bright subset catalog
     290// ** we skip any stars found to be bad (STAR_BAD)
     291
     292// * during the final pass
     293// ** operations are applied to all objects
     294// ** we have special tests for PS1 extended data, 2MASS extended & good data, & synthetic photometry
     295
     296// * during the stand-alone '-averages' mode (relphot_objects)
     297// ** no image data is loaded
     298// ** we only use the provided calibration (measure.Mcal)
     299// ** we skip outlier rejection of measurements
     300
     301// set the Mrel values for the specified catalog
     302// NOTE: here 'catalog' is a pointer to a specific catalog, not the root of the array
     303int setMrel_catalog (Catalog *catalog, int Nc, int pass, FlatCorrectionTable *flatcorr, SetMrelInfo *results, int Nsecfilt) {
     304
     305  off_t j, k, m;
     306  int N;
     307  float Msys, Mcal, Mmos, Mgrid;
     308
    194309  StatType stats, apstats;
    195   int Nsec;
    196 
    197   int Nsecfilt = GetPhotcodeNsecfilt ();
    198 
    199   /* Nmeasure is now different, need to reallocate */
    200   Nmax = 0;
    201   for (i = 0; i < Ncatalog; i++) {
    202     for (j = 0; j < catalog[i].Naverage; j++) {
    203       Nmax = MAX (Nmax, catalog[i].averageT[j].Nmeasure);
    204     }
    205   }
    206   ALLOCATE (list, double, MAX (1, Nmax));
    207   ALLOCATE (dlist, double, MAX (1, Nmax));
    208 
    209   ALLOCATE (aplist, double, MAX (1, Nmax));
    210   ALLOCATE (daplist, double, MAX (1, Nmax));
    211 
    212   for (i = 0; i < Ncatalog; i++) {
    213     for (j = 0; j < catalog[i].Naverage; j++) {
    214 
    215       if (FALSE && (catalog[i].average[j].objID == 0x46a4) && (catalog[i].average[j].catID == 0xf40e)) {
    216         fprintf (stderr, "test obj\n");
    217         print_measure_set (&catalog[i].average[j], &catalog[i].secfilt[j*Nsecfilt], catalog[i].measure);
    218       }
     310  liststats_setmode (&stats, STATMODE);
     311  liststats_setmode (&apstats, STATMODE);
     312
     313  double *list    = results->list;
     314  double *dlist   = results->dlist;
     315  double *wlist   = results->wlist;
     316  double *aplist  = results->aplist;
     317  double *daplist = results->daplist;
     318
     319  SetMrelInfoInit (results, FALSE); // do not allocate list,dlist,wlist arrays
     320
     321  int isSetMrelFinal = (pass >= 0);
     322
     323  for (j = 0; j < catalog[Nc].Naverage; j++) {
     324    // XXX accumulate all secfilt values in a single pass?
     325
     326    // option for a test print
     327    if (FALSE && (catalog[Nc].average[j].objID == 0x46a4) && (catalog[Nc].average[j].catID == 0xf40e)) {
     328      fprintf (stderr, "test obj\n");
     329      print_measure_set (&catalog[Nc].average[j], &catalog[Nc].secfilt[j*Nsecfilt], catalog[Nc].measure);
     330    }
     331
     332    int GoodPS1 = FALSE;
     333    int Good2MASS = FALSE;
     334    int Galaxy2MASS = FALSE;
     335
     336    int NextPS1 = 0;
     337    int NpsfPS1 = 0;
     338
     339    int Ns;
     340    for (Ns = 0; Ns < Nphotcodes; Ns++) {
     341
     342      int thisCode = photcodes[Ns][0].code;
     343      int Nsec = GetPhotcodeNsec(thisCode);
     344
     345      /* calculate the average mag in this SEC photcode for a single star */
     346
     347      /* star/photcodes already calibrated */
     348      if ( isSetMrelFinal && catalog[Nc].found[Nsecfilt*j+Nsec]) continue; 
     349     
     350      // skip bad stars
     351      if (!isSetMrelFinal && (catalog[Nc].secfilt[Nsecfilt*j+Nsec].flags & STAR_BAD)) continue;
     352
     353      int Ncode = 0;
     354      int Next = 0;
     355      int haveSynth = FALSE;
     356
     357      int forceSynth = FALSE;
     358      int forceSynthEntry = -1;
     359
     360      int haveUbercal = FALSE;
    219361
    220362      int minUbercalDist = 1000;
    221 
    222       int Ns;
    223       for (Ns = 0; Ns < Nphotcodes; Ns++) {
    224 
    225         int thisCode = photcodes[Ns][0].code;
    226         Nsec = GetPhotcodeNsec(thisCode);
    227 
    228         /* star/photcodes already calibrated */
    229         if (catalog[i].found[Nsecfilt*j+Nsec]) continue; 
    230 
    231         int Ncode = 0;
    232         int Next = 0;
    233         int haveSynth = FALSE;
    234         int haveUbercal = FALSE;
    235         int isRefPhot = FALSE;
    236 
    237         N = 0;
    238         m = catalog[i].averageT[j].measureOffset;
    239         for (k = 0; k < catalog[i].averageT[j].Nmeasure; k++, m++) {
    240 
    241           // skip measurements that do not match the current photcode
    242           PhotCode *code = GetPhotcodebyCode (catalog[i].measureT[m].photcode);
    243           if (!code) continue;
    244           if (code->equiv != thisCode) { continue; }
    245           Ncode ++;
    246 
    247           if (catalog[i].measureT[m].dbFlags & MEAS_BAD) continue;
    248 
    249           if (getImageEntry (m, i) < 0) {
    250             // these detetions have no image (eg, ref values such as 2MASS)
    251             Mcal = Mmos = Mgrid = 0;
    252             isRefPhot = TRUE;
    253           } else {
    254             Mcal  = getMcal  (m, i, flatcorr, catalog);
    255             if (isnan(Mcal)) {
    256               MARK_SKIP_MEAS;
    257               continue;
    258             }
    259             Mmos  = getMmos  (m, i);
    260             if (isnan(Mmos)) {
    261               MARK_SKIP_MEAS;
    262               continue;
    263             }
    264             Mgrid = getMgrid (m, i);
    265             if (isnan(Mgrid)) {
    266               MARK_SKIP_MEAS;
    267               continue;
    268             }
    269           }
    270 
    271           Msys = PhotSysTiny (&catalog[i].measureT[m], &catalog[i].averageT[j], &catalog[i].secfilt[j*Nsecfilt]);
    272           if (isnan(Msys)) {
    273             if (!isRefPhot) {
    274               MARK_SKIP_MEAS;
    275             }
    276             continue;
    277           }
    278           list[N] = Msys - Mcal - Mmos - Mgrid;
    279 
    280           Map = PhotAper (&catalog[i].measure[m]);
     363   
     364      N = 0;
     365      m = catalog[Nc].averageT[j].measureOffset;
     366      for (k = 0; k < catalog[Nc].averageT[j].Nmeasure; k++, m++) {
     367
     368        // skip measurements that do not match the current photcode
     369        PhotCode *code = GetPhotcodebyCode (catalog[Nc].measureT[m].photcode);
     370        if (!code) continue;
     371        if (code->equiv != thisCode) { continue; }
     372        Ncode ++;
     373
     374        if (catalog[Nc].measureT[m].dbFlags & MEAS_BAD) SKIP_THIS_MEAS(Nbad);
     375
     376        if (getImageEntry (m, Nc) < 0) {
     377          // measurements without an image are either external reference photometry or
     378          // data for which the associated image has not been loaded (probably because of
     379          // overlaps).  Msys + measure.Mcal is our best guess of the true magnitude
     380          Mmos = Mgrid = 0;
     381          Mcal = catalog[Nc].measureT[m].Mcal; // check that this is zero for loaded REF value
     382        } else {
     383          Mcal  = getMcal  (m, Nc, flatcorr, catalog);
     384          if (isnan(Mcal))  SKIP_THIS_MEAS(Ncal);
     385          Mmos  = getMmos  (m, Nc);
     386          if (isnan(Mmos))  SKIP_THIS_MEAS(Nmos);
     387          Mgrid = getMgrid (m, Nc);
     388          if (isnan(Mgrid)) SKIP_THIS_MEAS(Ngrid);
     389        }
     390
     391        Msys = PhotSysTiny (&catalog[Nc].measureT[m], &catalog[Nc].averageT[j], &catalog[Nc].secfilt[j*Nsecfilt]);
     392        if (isnan(Msys)) SKIP_THIS_MEAS(Nsys);
     393
     394        list[N] = Msys - Mcal - Mmos - Mgrid;
     395
     396        int myUbercalDist = getUbercalDist(m,Nc);
     397        minUbercalDist = MIN(minUbercalDist, myUbercalDist);
     398
     399        if (isSetMrelFinal) {
     400          float Map = PhotAper (&catalog[Nc].measure[m]);
    281401          aplist[N] = Map - Mcal - Mmos - Mgrid;
    282402
    283           int myUbercalDist = getUbercalDist(m,i);
    284           minUbercalDist = MIN(minUbercalDist, myUbercalDist);
    285 
    286           // count the extended detections
    287           if ((catalog[i].measure[m].photcode >= 10000) && (catalog[i].measure[m].photcode <= 10500)) {
    288             if (!isnan(catalog[i].measure[m].Map)) {
    289               if (catalog[i].measure[m].M - catalog[i].measure[m].Map > 0.5) {
     403          // special options for PS1 data
     404          if ((catalog[Nc].measure[m].photcode >= 10000) && (catalog[Nc].measure[m].photcode <= 10500)) {
     405            // count the extended detections
     406            if (!isnan(catalog[Nc].measure[m].Map)) {
     407              if (catalog[Nc].measure[m].M - catalog[Nc].measure[m].Map > 0.5) {
    290408                Next ++;
     409                NextPS1 ++;
     410              } else {
     411                NpsfPS1 ++;
    291412              }
    292413            }
    293414          }
    294415          // count extended detections for 2MASS (XXX NOTE hardwired photcodes 2011, 2012, 2013)
    295           if ((catalog[i].measure[m].photcode >= 2011) && (catalog[i].measure[m].photcode <= 2013)) {
    296             if (catalog[i].measure[m].photFlags & 0x00c00000) {
     416          if ((catalog[Nc].measure[m].photcode >= 2011) && (catalog[Nc].measure[m].photcode <= 2013)) {
     417            if (catalog[Nc].measure[m].photFlags & 0x00c00000) {
    297418              Next ++;
     419              Galaxy2MASS = TRUE;
    298420            }
    299             if ((pass == 0) && !(catalog[i].measure[m].photFlags & 0x00000007)) {
    300               // detections without one of these bits should only be used in PASS_1
    301               MARK_SKIP_MEAS;
    302               continue;
    303             }
    304           }
    305           // ignore SYNTH photocdes until PASS == 4 (where we also accept saturated stars)
    306           if ((catalog[i].measure[m].photcode >= 3001) && (catalog[i].measure[m].photcode <= 3005)) {
    307             if (pass < 4) {
    308               MARK_SKIP_MEAS;
    309               continue;
    310             }
    311             haveSynth = TRUE;
    312           }
    313 
    314           // dlist gives the error, which is used as the weight in WT_MEAN.
    315           // we can modify the resulting weight in a few ways:
    316           // 1) MIN_ERROR guarantees a floor
    317           // 2) photomErrSys is added in quadrature as a sytematic error, set per photcode
    318           // 3) UBERCAL measurements can have their weight increased by a big factor to help tie down the averages
    319           // 4) some reference photcode of some kind can be specified as fixed and have a high weight
    320           dlist[N] = MAX (hypot(catalog[i].measureT[m].dM, code->photomErrSys), MIN_ERROR);
    321 
    322           // up-weight the ubercal values (or convergence can take a long time...) (XXX make this optional?)
    323           if (catalog[i].measureT[m].dbFlags & ID_MEAS_PHOTOM_UBERCAL) {
    324             dlist[N] = MAX (0.1*catalog[i].measureT[m].dM, MIN_ERROR);
    325             haveUbercal = TRUE;
    326           }
    327 
    328           // tie down reference photometry if the -refcode (code) option is selected
    329           // eg, -refcode g_SDSS
    330           // this probably makes no sense in the context of multifilter analysis
    331           if (refPhotcode) {
    332             if (code->code == refPhotcode->code) {
    333               // tiny error -> large weight
    334               // dlist[N] = MAX (0.01*catalog[i].measureT[m].dM, MIN_ERROR);
    335               dlist[N] = 0.0001;
    336             }
    337           }
    338           N++;
    339         }
    340         if (N < 1) continue;
    341 
    342         for (m = 0; m < N; m++) {
    343           daplist[m] = dlist[m];
    344         }
    345 
    346         // XXX force WT_MEAN or MEAN here?
    347         liststats (list, dlist, N, &stats);
    348         liststats (aplist, daplist, N, &apstats);
    349         catalog[i].found[Nsecfilt*j+Nsec] = TRUE;
    350         switch (pass) {
    351           case 0:
    352             catalog[i].secfilt[Nsecfilt*j+Nsec].flags |= ID_PHOTOM_PASS_0;
    353             break;
    354           case 1:
    355             catalog[i].secfilt[Nsecfilt*j+Nsec].flags |= ID_PHOTOM_PASS_1;
    356             break;
    357           case 2:
    358             catalog[i].secfilt[Nsecfilt*j+Nsec].flags |= ID_PHOTOM_PASS_2;
    359             break;
    360           case 3:
    361             catalog[i].secfilt[Nsecfilt*j+Nsec].flags |= ID_PHOTOM_PASS_3;
    362             break;
    363           case 4:
    364             catalog[i].secfilt[Nsecfilt*j+Nsec].flags |= ID_PHOTOM_PASS_4;
    365             break;
    366         }
    367 
    368         if (haveSynth) {
    369           catalog[i].secfilt[Nsecfilt*j+Nsec].flags |= ID_SECF_USE_SYNTH;
    370         }       
    371         if (haveUbercal) {
    372           catalog[i].secfilt[Nsecfilt*j+Nsec].flags |= ID_SECF_USE_UBERCAL;
    373         }       
    374 
    375         /* use sigma or error in dM for output? */
    376         catalog[i].secfilt[Nsecfilt*j+Nsec].M  = stats.mean;
    377         catalog[i].secfilt[Nsecfilt*j+Nsec].Map = apstats.mean;
    378         catalog[i].secfilt[Nsecfilt*j+Nsec].dM = MAX (stats.error, stats.sigma);
    379         catalog[i].secfilt[Nsecfilt*j+Nsec].Xm = (stats.Nmeas > 1) ? 100.0*log10(stats.chisq) : NAN_S_SHORT;
    380         catalog[i].secfilt[Nsecfilt*j+Nsec].Ncode = Ncode;
    381         catalog[i].secfilt[Nsecfilt*j+Nsec].Nused = stats.Nmeas;
    382 
    383         catalog[i].secfilt[Nsecfilt*j+Nsec].M_80 = 1000 * stats.Upper80;
    384         catalog[i].secfilt[Nsecfilt*j+Nsec].M_20 = 1000 * stats.Lower20;
    385         catalog[i].secfilt[Nsecfilt*j+Nsec].ubercalDist = minUbercalDist;
    386 
    387         if ((Next > 0) && (Next > 0.5*N)) {
    388           catalog[i].secfilt[Nsecfilt*j+Nsec].flags |= ID_SECF_OBJ_EXT;
    389         }
    390       }
    391     }
    392   }
    393 
    394   free (list);
    395   free (dlist);
    396 
    397   free (aplist);
    398   free (daplist);
    399   return (TRUE);
    400 }
    401 
    402 /* grab Nsec for named photcode */
    403 # define NAMED_PHOTCODE_NSEC(MY_NSEC,NAME)      \
    404   short MY_NSEC = -1;                           \
    405   {                                             \
    406   PhotCode *code = GetPhotcodebyName (NAME);    \
    407   if (code) {                                   \
    408     MY_NSEC = GetPhotcodeNsec (code->equiv);    \
    409   } }
    410 
    411 // For each average object, set the average mags based on existing equiv photometry.
    412 // NOTE: this function operates on the real Measure & Average structures, not the
    413 // MeasureTiny & AverageTiny structures
    414 // NOTE: this function is called on the remote machine -- make sure any (global) options
    415 // are passed to the relphot_client program
    416 int setMave (Catalog *catalog, int Ncatalog) {
    417 
    418   off_t j, k, m, Nmax;
    419   int i, Ns, Nsecfilt, N, Nc;
    420   float Msys;
    421   double *list, *dlist;
    422   StatType stats;
    423   DVOAverageFlags flagBits;
    424 
    425   flagBits = ID_OBJ_EXT | ID_OBJ_EXT_ALT | ID_OBJ_GOOD | ID_OBJ_GOOD_ALT;
    426 
    427   // pre-allocate a list for stats purposes
    428   Nmax = 0;
    429   for (i = 0; i < Ncatalog; i++) {
    430     for (j = 0; j < catalog[i].Naverage; j++) {
    431       Nmax = MAX (Nmax, catalog[i].average[j].Nmeasure);
    432     }
    433   }
    434   ALLOCATE (list, double, MAX (1, Nmax));
    435   ALLOCATE (dlist, double, MAX (1, Nmax));
    436 
    437   Nsecfilt = GetPhotcodeNsecfilt ();
    438 
    439   // we want to raise some bits on the 2MASS (JHK) secfilt flags, if we have 2MASS data
    440   NAMED_PHOTCODE_NSEC (Nsec_J, "2MASS_J");
    441   NAMED_PHOTCODE_NSEC (Nsec_H, "2MASS_H");
    442   NAMED_PHOTCODE_NSEC (Nsec_K, "2MASS_K");
    443 
    444   for (i = 0; i < Ncatalog; i++) {
    445     for (j = 0; j < catalog[i].Naverage; j++) {
    446 
    447       // update average photometry for each of the average filters
    448 
    449       // XXX Note that this would be faster if we had an array of results and accumulated
    450       // them in a single pass
    451 
    452       int Next = 0;
    453 
    454       for (Ns = 0; Ns < Nsecfilt; Ns++) {
    455 
    456         PhotCode *code = GetPhotcodebyNsec (Ns);
    457         Nc = code[0].code;
    458        
    459         N = 0;
    460         m = catalog[i].average[j].measureOffset;
    461         for (k = 0; k < catalog[i].average[j].Nmeasure; k++, m++) {
    462           if (catalog[i].measure[m].dbFlags & MEAS_BAD) continue;
    463           if (GetPhotcodeEquivCodebyCode (catalog[i].measure[m].photcode) != Nc) continue;
    464 
    465           Msys = PhotSys (&catalog[i].measure[m], &catalog[i].average[j], &catalog[i].secfilt[j*Nsecfilt]);
    466           if (isnan(Msys)) continue;
    467 
    468           // reject POOR detections (PSF_QF < 0.85) and count extended detections
    469           // XXX only apply this filter for psphot data from GPC1 for now...
    470           if ((catalog[i].measure[m].photcode > 10000) && (catalog[i].measure[m].photcode < 10500)) {
    471             if (catalog[i].measure[m].psfQual < 0.85) continue;
    472             if (!isnan(catalog[i].measure[m].Map)) {
    473               if (catalog[i].measure[m].M - catalog[i].measure[m].Map > 0.5) {
    474                 Next ++;
     421            if (pass == 0) {
     422              if (catalog[Nc].measure[m].photFlags & 0x00000007) {
     423                Good2MASS = TRUE;
     424              } else {
     425                // detections without one of these bits should only be used in PASS_1
     426                SKIP_THIS_MEAS(Nbad);
     427                continue;
    475428              }
    476429            }
    477430          }
    478431
    479           // XXX make it optional to apply Mcal (do I need an extra field for advisory Mcal?)
    480           list[N] = Msys - catalog[i].measure[m].Mcal;
    481           dlist[N] = MAX (catalog[i].measure[m].dM, MIN_ERROR);
    482           N++;
    483         }
    484         if (N < 1) continue;
    485 
    486         liststats (list, dlist, N, &stats);
    487 
    488         /* use sigma or error in dM for output? */
    489         catalog[i].secfilt[Nsecfilt*j+Ns].M  = stats.mean;
    490         catalog[i].secfilt[Nsecfilt*j+Ns].dM = MAX (stats.error, stats.sigma);
    491         catalog[i].secfilt[Nsecfilt*j+Ns].Xm = (stats.Nmeas > 1) ? 100.0*log10(stats.chisq) : NAN_S_SHORT;
    492         catalog[i].secfilt[Nsecfilt*j+Ns].Ncode = N;
    493         catalog[i].secfilt[Nsecfilt*j+Ns].Nused = stats.Nmeas;
    494 
    495         catalog[i].secfilt[Nsecfilt*j+Ns].M_80 = 1000 * stats.Upper80;
    496         catalog[i].secfilt[Nsecfilt*j+Ns].M_20 = 1000 * stats.Lower20;
    497 
    498         if ((Next > 0) && (Next > 0.5*N)) {
    499           catalog[i].secfilt[Nsecfilt*j+Ns].flags |= ID_SECF_OBJ_EXT;
    500         }
    501       }
    502 
    503       // update average flags based on the detection stats. 
    504 
    505       int Galaxy2MASS = FALSE; // best guess for galaxy based on 2MASS J measurements (gal_contam == measure.flags[0x00400000 | 0x00800000])
    506       int goodPS1 = FALSE;     // true if any PS1 measurements have psfQual > 0.85
    507       int good2MASS = FALSE;   // true if 2MASS J measurements have significant detections
    508       int nEXT = 0;
    509       int nPSF = 0;     // number of PS1 PSF vs EXT measurements
    510       int have2MASS = FALSE;
    511      
    512       // count, flag good and extended detections
    513       m = catalog[i].average[j].measureOffset;
    514       for (k = 0; k < catalog[i].average[j].Nmeasure; k++, m++) {
    515 
    516         // PS1 data :
    517         if ((catalog[i].measure[m].photcode >= 10000) && (catalog[i].measure[m].photcode <= 10500)) {
    518           if (catalog[i].measure[m].psfQual > 0.85) {
    519             goodPS1 = TRUE;
    520             if (!isnan(catalog[i].measure[m].Map)) {
    521               if (catalog[i].measure[m].M - catalog[i].measure[m].Map > 0.5) {
    522                 nEXT ++;
    523               } else {
    524                 nPSF ++;
     432          // Blindly accepth the SYNTH mags if we are above saturation, otherwise,
     433          // ignore SYNTH photcodes until PASS == 4 (where we also accept saturated stars)
     434          if ((catalog[Nc].measure[m].photcode >= 3001) && (catalog[Nc].measure[m].photcode <= 3005)) {
     435            // something of a hack: force object to use synth values if synth mags >>
     436            // saturation (3pi instrumental mags < -15)
     437            float MaxMagForceSynth = NAN;
     438            switch (catalog[Nc].measure[m].photcode) {
     439              case 3001:
     440                MaxMagForceSynth = 13.64;
     441                break;
     442              case 3002:
     443                MaxMagForceSynth = 13.76;
     444                break;
     445              case 3003:
     446                MaxMagForceSynth = 13.74;
     447                break;
     448              case 3004:
     449                MaxMagForceSynth = 12.94;
     450                break;
     451              case 3005:
     452                MaxMagForceSynth = 12.01;
     453                break;
     454            }
     455            if (catalog[Nc].measureT[m].M < MaxMagForceSynth) {
     456              forceSynth = TRUE;
     457              forceSynthEntry = N;
     458            } else {
     459              if (pass < 4) {
     460                SKIP_THIS_MEAS(Nbad);
     461                continue;
    525462              }
     463              haveSynth = TRUE;
    526464            }
    527465          }
    528466        }
    529          
    530         // 2MASS data J-band flags
    531         if (catalog[i].measure[m].photcode == 2011) {
    532           // only need to do this once (always have JHK triplet; galaxy flag is same for all 3)
    533           have2MASS = TRUE;
    534           if (catalog[i].measure[m].photFlags & 0x00c00000) {
    535             Galaxy2MASS = TRUE;
     467
     468        // dlist gives the error per measurement, wlist gives the weight
     469        // we can modify the error and weight in a few ways:
     470        // 1) MIN_ERROR guarantees a floor
     471        // 2) photomErrSys is added in quadrature as a sytematic error, set per photcode
     472        // 3) UBERCAL measurements can have their weight increased by a big factor to help tie down the averages
     473        // 4) some reference photcode of some kind can be specified as fixed and have a high weight
     474        dlist[N] = MAX (hypot(catalog[Nc].measureT[m].dM, code->photomErrSys), MIN_ERROR);
     475        wlist[N] = 1.0;
     476
     477        // up-weight the ubercal values (or convergence can take a long time...)
     478        if (catalog[Nc].measureT[m].dbFlags & ID_MEAS_PHOTOM_UBERCAL) {
     479          wlist[N] = 10.0;
     480        }
     481
     482        // tie down reference photometry if the -refcode (code) option is selected
     483        // eg, -refcode g_SDSS
     484        // this probably makes no sense in the context of multifilter analysis
     485        if (refPhotcode) {
     486          if (code->code == refPhotcode->code) {
     487            wlist[N] = 100.0;
    536488          }
    537           if (catalog[i].measure[m].photFlags & 0x00000007) {
    538             good2MASS = TRUE;
    539             if (Nsec_J > -1) catalog[i].secfilt[j*Nsecfilt + Nsec_J].flags |= ID_PHOTOM_PASS_0;
    540           } else {
    541             if (Nsec_J > -1) catalog[i].secfilt[j*Nsecfilt + Nsec_J].flags |= ID_PHOTOM_PASS_1;
    542           }
    543         } 
    544         // 2MASS data H-band flags
    545         if (catalog[i].measure[m].photcode == 2012) {
    546           if (catalog[i].measure[m].photFlags & 0x00000007) {
    547             good2MASS = TRUE;
    548             if (Nsec_H > -1) catalog[i].secfilt[j*Nsecfilt + Nsec_H].flags |= ID_PHOTOM_PASS_0;
    549           } else {
    550             if (Nsec_H > -1) catalog[i].secfilt[j*Nsecfilt + Nsec_H].flags |= ID_PHOTOM_PASS_1;
    551           }
    552         } 
    553         // 2MASS data K-band flags
    554         if (catalog[i].measure[m].photcode == 2013) {
    555           if (catalog[i].measure[m].photFlags & 0x00000007) {
    556             good2MASS = TRUE;
    557             if (Nsec_K > -1) catalog[i].secfilt[j*Nsecfilt + Nsec_K].flags |= ID_PHOTOM_PASS_0;
    558           } else {
    559             if (Nsec_K > -1) catalog[i].secfilt[j*Nsecfilt + Nsec_K].flags |= ID_PHOTOM_PASS_1;
    560           }
    561         } 
    562       }
     489        }
     490        N++;
     491      }
     492
     493      int Nminmeas = isSetMrelFinal ? 1 : STAR_TOOFEW + 1;
     494
     495      // when performing the grid analysis, STAR_TOOFEW should be set to 1;
     496      if (N < Nminmeas) { /* too few measurements */
     497        // fprintf (f, "%10.6f %10.6f %d %d %d\n", catalog[Nc].averageT[j].R, catalog[Nc].averageT[j].D, catalog[Nc].measureT[catalog[Nc].averageT[j].measureOffset].imageID, N, STAR_TOOFEW);
     498        catalog[Nc].secfilt[Nsecfilt*j+Nsec].flags |= ID_STAR_FEW;
     499        if (Ncode == 0) {
     500          results->Ncode ++;
     501        } else {
     502          results->Nfew ++;
     503        }
     504        continue;
     505      } else {
     506        catalog[Nc].secfilt[Nsecfilt*j+Nsec].flags &= ~ID_STAR_FEW;
     507      }
     508
     509      if (forceSynth) {
     510        // use the single SYNTH value instead of the other mags here
     511        myAssert ((forceSynthEntry < N) && (forceSynthEntry >= 0), "programming error");
     512        list[0]  = list[forceSynthEntry];
     513        dlist[0] = dlist[forceSynthEntry];
     514        wlist[0] = wlist[forceSynthEntry];
     515        N = 1;
     516      }
     517      liststats (list, dlist, wlist, N, &stats);
     518
     519      catalog[Nc].secfilt[Nsecfilt*j+Nsec].M  = stats.mean;
     520      catalog[Nc].secfilt[Nsecfilt*j+Nsec].dM = stats.error;
     521      catalog[Nc].secfilt[Nsecfilt*j+Nsec].Xm = (stats.Nmeas > 1) ? 100.0*log10(stats.chisq + 1e-4) : NAN_S_SHORT;
     522
     523      // when running -averages, we have no information about the images, so we cannot set this
     524      if (minUbercalDist > -1) {
     525        catalog[Nc].secfilt[Nsecfilt*j+Nsec].ubercalDist = minUbercalDist;
     526      }
     527
     528      if (isSetMrelFinal) {
     529        catalog[Nc].found[Nsecfilt*j+Nsec] = TRUE;
     530
     531        catalog[Nc].secfilt[Nsecfilt*j+Nsec].Mstdev = 1000.0*stats.sigma; // Mstdev is in millimags (not enough space for more precision)
     532        catalog[Nc].secfilt[Nsecfilt*j+Nsec].Ncode = Ncode;
     533        catalog[Nc].secfilt[Nsecfilt*j+Nsec].Nused = stats.Nmeas;
     534
     535        catalog[Nc].secfilt[Nsecfilt*j+Nsec].M_80 = 1000 * stats.Upper80;
     536        catalog[Nc].secfilt[Nsecfilt*j+Nsec].M_20 = 1000 * stats.Lower20;
     537
     538        // NOTE : use the modified weight for apmags as well as psf mags
     539        liststats (aplist, daplist, wlist, N, &apstats);
     540
     541        catalog[Nc].secfilt[Nsecfilt*j+Nsec].Map  = apstats.mean;
     542
     543        // NOTE: for 2MASS measurements, Next should be 1, as should N
     544        if ((Next > 0) && (Next > 0.5*N)) {
     545          catalog[Nc].secfilt[Nsecfilt*j+Nsec].flags |= ID_SECF_OBJ_EXT;
     546        }
     547
     548        switch (pass) {
     549          case 0:
     550            catalog[Nc].secfilt[Nsecfilt*j+Nsec].flags |= ID_PHOTOM_PASS_0;
     551            GoodPS1 = TRUE;
     552            break;
     553          case 1:
     554            catalog[Nc].secfilt[Nsecfilt*j+Nsec].flags |= ID_PHOTOM_PASS_1;
     555            GoodPS1 = TRUE;
     556            break;
     557          case 2:
     558            catalog[Nc].secfilt[Nsecfilt*j+Nsec].flags |= ID_PHOTOM_PASS_2;
     559            GoodPS1 = TRUE;
     560            break;
     561          case 3:
     562            catalog[Nc].secfilt[Nsecfilt*j+Nsec].flags |= ID_PHOTOM_PASS_3;
     563            break;
     564          case 4:
     565            catalog[Nc].secfilt[Nsecfilt*j+Nsec].flags |= ID_PHOTOM_PASS_4;
     566            break;
     567        }
     568        if (haveSynth) {
     569          catalog[Nc].secfilt[Nsecfilt*j+Nsec].flags |= ID_SECF_USE_SYNTH;
     570        }       
     571        if (haveUbercal) {
     572          catalog[Nc].secfilt[Nsecfilt*j+Nsec].flags |= ID_SECF_USE_UBERCAL;
     573        }       
     574      }
     575    }
     576
     577    if (isSetMrelFinal) {
     578      DVOAverageFlags flagBits = ID_OBJ_EXT | ID_OBJ_EXT_ALT | ID_OBJ_GOOD | ID_OBJ_GOOD_ALT;
    563579
    564580      // we attempt to set a few flags here; reset those bits before trying:
    565       catalog[i].average[j].flags &= ~flagBits;
    566 
    567       // XXX set the secfilt bits?
    568       if (nEXT && (nEXT > nPSF)) {
    569         catalog[i].average[j].flags |= ID_OBJ_EXT;
    570       }
    571       if (goodPS1) {
    572         catalog[i].average[j].flags |= ID_OBJ_GOOD;
     581      catalog[Nc].average[j].flags &= ~flagBits;
     582
     583      if (NextPS1 && (NextPS1 > NpsfPS1)) {
     584        catalog[Nc].average[j].flags |= ID_OBJ_EXT;
     585      }
     586      if (GoodPS1) {
     587        catalog[Nc].average[j].flags |= ID_OBJ_GOOD;
    573588      }
    574589      if (Galaxy2MASS) {
    575         catalog[i].average[j].flags |= ID_OBJ_EXT_ALT;
    576         if (Nsec_J > -1) catalog[i].secfilt[j*Nsecfilt + Nsec_J].flags |= ID_SECF_OBJ_EXT;
    577         if (Nsec_H > -1) catalog[i].secfilt[j*Nsecfilt + Nsec_H].flags |= ID_SECF_OBJ_EXT;
    578         if (Nsec_K > -1) catalog[i].secfilt[j*Nsecfilt + Nsec_K].flags |= ID_SECF_OBJ_EXT;
    579       }
    580       if (good2MASS) {
    581         catalog[i].average[j].flags |= ID_OBJ_GOOD_ALT;
    582       }
    583     }
    584   }
    585 
    586   free (list);
    587   free (dlist);
     590        catalog[Nc].average[j].flags |= ID_OBJ_EXT_ALT;
     591      }
     592      if (Good2MASS) {
     593        catalog[Nc].average[j].flags |= ID_OBJ_GOOD_ALT;
     594      }
     595    }
     596  }
    588597  return (TRUE);
     598}
     599
     600int print_measure_set (Average *average, SecFilt *secfilt, Measure *measure) {
     601
     602  off_t k;
     603
     604  int Nsecfilt = GetPhotcodeNsecfilt ();
     605
     606  off_t m = average[0].measureOffset;
     607
     608  for (k = 0; k < average[0].Nmeasure; k++, m++) {
     609    fprintf (stderr, "meas: %08x\n", measure[m].dbFlags);
     610  }
     611
     612  int Ns;
     613  for (Ns = 0; Ns < Nsecfilt; Ns++) {
     614    fprintf (stderr, "secf: %08x\n", secfilt[Ns].flags);
     615  }
     616  return 1;
    589617}
    590618
     
    612640        if (isnan(Mgrid)) continue;
    613641
     642        // note that measurements for which the image is not selected will not be modified
     643        // (that is a good thing! -- we keep a prior calibration)
     644
    614645        // set the output calibration
    615646        catalog[i].measure[m].Mcal = Mcal + Mmos + Mgrid;
     
    630661  double Chisq, MaxScatter, MaxChisq;
    631662  double *xlist, *slist, *dlist;
     663
    632664  StatType stats;
     665  liststats_setmode (&stats, "MEAN");
    633666
    634667  if (VERBOSE) fprintf (stderr, "marking poor stars\n");
     
    644677  int Nsecfilt = GetPhotcodeNsecfilt ();
    645678
    646   // XX int oldPLOTSTUFF = PLOTSTUFF;
    647   // XX PLOTSTUFF = TRUE;
    648   // XX plot_chisq (catalog, Ncatalog);
    649   // XX PLOTSTUFF = oldPLOTSTUFF;
    650 
    651679  // eliminate bad stars using the stats for a single secfilt at a time
    652   // XXX DEP replace average.flags with secfilt flags
    653680  for (Ns = 0; Ns < Nphotcodes; Ns ++) {
    654681   
     
    669696    }
    670697 
    671     initstats ("MEAN");
    672     liststats (xlist, dlist, Ntot, &stats);
     698    liststats (xlist, dlist, NULL, Ntot, &stats);
    673699    MaxChisq = MAX (STAR_CHISQ, 2*stats.median);
    674     liststats (slist, dlist, Ntot, &stats);
     700
     701    liststats (slist, dlist, NULL, Ntot, &stats);
    675702    MaxScatter = MAX (STAR_SCATTER, 2*stats.median);
    676703    fprintf (stderr, "Max Scatter: %f, Max Chisq: %f\n", MaxScatter, MaxChisq);
     
    696723    }
    697724    fprintf (stderr, "%d stars marked variable (%d scat, %d nan, %d chi), %d total\n", Ndel, Nscat, Nnan, Nchi, Nave);
    698     initstats (STATMODE);
    699725  }
    700726  free (xlist);
     
    702728  free (dlist);
    703729}
     730
     731// clean_measures examines the stats for a single star.  It measures the INNER 50% mean
     732// and sigma, it then re-measures the mean and sigma using all stars with NSIGMA_CLIP (3)
     733// sigma of the INNER 50% mean.  it then flags any measurements which are more than
     734// NSIGMA_REJECT (5) sigma of the mean
    704735
    705736# define NSIGMA_CLIP 3.0
     
    712743  double *tlist, *list, *dlist;
    713744  float Msys, Mcal, Mmos, Mgrid;
    714   StatType stats;
    715745  int Ncal, Nmos, Ngrid, Nfew;
    716746
     
    732762  /* it makes no sense to mark 3-sigma outliers with <5 measurements */
    733763  TOOFEW = MAX (5, STAR_TOOFEW);
     764
     765  // stats structures for inner and full stats
     766  StatType instats, stats;
     767  liststats_setmode (&instats, "INNER_MEAN");
     768  liststats_setmode (&stats, "MEAN");
    734769
    735770  Ndel = Nave = 0;
     
    779814
    780815        // calculated mean of inner 50%
    781         initstats ("INNER_MEAN");
    782         liststats (list, dlist, N, &stats);
    783         stats.sigma = MAX (MIN_ERROR, stats.sigma); /* if measurements agree too well, sigma -> 0.0 */
     816        liststats (list, dlist, NULL, N, &instats);
     817        instats.sigma = MAX (MIN_ERROR, instats.sigma); /* if measurements agree too well, sigma -> 0.0 */
    784818
    785819        // ignore entries > 3sigma from inner mean
    786820        for (k = m = 0; k < N; k++) {
    787           if (fabs (list[k] - stats.median) < NSIGMA_CLIP*stats.sigma) {
     821          if (fabs (list[k] - instats.median) < NSIGMA_CLIP*instats.sigma) {
    788822            list[m] = list[k];
    789823            m++;
     
    791825        }
    792826        // recalculate the mean & sigma of the accepted measurements
    793         initstats ("MEAN");
    794         liststats (list, dlist, m, &stats);
     827        liststats (list, dlist, NULL, m, &stats);
    795828        stats.sigma = MAX (MIN_ERROR, stats.sigma);
    796829
     
    841874    }
    842875  }
    843   initstats (STATMODE);
    844876  if (VERBOSE) fprintf (stderr, OFF_T_FMT" measures marked poor, "OFF_T_FMT" total\n", Ndel, Nave);
     877
    845878  free (list);
    846879  free (dlist);
    847880  free (ilist);
    848881  free (tlist);
    849 
    850 
    851882}
    852883
     
    898929  }
    899930
    900   // fprintf (stderr, "N1: %d, N2: %d, N3: %d, N4: %d, N0: %d\n", N1, N2, N3, N4, N0);
    901   liststats (list, dlist, n, &stats);
     931  liststats_setmode (&stats, "MEAN");
     932
     933  liststats (list, dlist, NULL, n, &stats);
    902934  free (list);
    903935  free (dlist);
     
    938970  }
    939971
    940   liststats (list, dlist, n, &stats);
     972  liststats_setmode (&stats, "MEAN");
     973
     974  liststats (list, dlist, NULL, n, &stats);
    941975  free (list);
    942976  free (dlist);
     
    9771011  }
    9781012
    979   liststats (list, dlist, n, &stats);
     1013  liststats_setmode (&stats, "MEAN");
     1014
     1015  liststats (list, dlist, NULL, n, &stats);
    9801016  free (list);
    9811017  free (dlist);
  • trunk/Ohana/src/relphot/src/args.c

    r33651 r33963  
    7474  }
    7575
     76  NTHREADS = 0;
     77  if ((N = get_argument (argc, argv, "-threads"))) {
     78    remove_argument (N, &argc, argv);
     79    NTHREADS = atof (argv[N]);
     80    remove_argument (N, &argc, argv);
     81  }
     82
    7683  // XXX for the moment, make this selection manual.  it needs to be automatic
    7784  // based on the state of the SkyTable
     
    300307  }
    301308
     309  ApplyOffsets = FALSE;
     310  if ((N = get_argument (argc, argv, "-apply-offsets"))) {
     311    remove_argument (N, &argc, argv);
     312    ApplyOffsets = TRUE;
     313  }
     314
    302315  if (UpdateAverages && (argc == 1)) return TRUE;
    303316  if (argc != 2) relphot_usage ();
     
    331344  }
    332345  if (!HOSTDIR) relphot_client_usage();
    333 
    334   // CATDIR[0] = 0;
    335   // if ((N = get_argument (argc, argv, "-catdir"))) {
    336   //   remove_argument (N, &argc, argv);
    337   //   strcpy (CATDIR, argv[N]);
    338   //   remove_argument (N, &argc, argv);
    339   // }
    340   // if (!CATDIR[0]) relphot_client_usage();
    341346
    342347  IMAGES = NULL; // used in -update mode
  • trunk/Ohana/src/relphot/src/bcatalog.c

    r33651 r33963  
    33int LimitDensityCatalog_ByNmeasure (Catalog *subcatalog, Catalog *oldcatalog);
    44
    5 int bcatalog (Catalog *subcatalog, Catalog *catalog) {
     5int bcatalog (Catalog *subcatalog, Catalog *catalog, int Ncat) {
    66 
    77  off_t i, j, offset;
     
    7474        subcatalog[0].secfilt[Nsecfilt*Naverage+Nsec].Map    = NAN;
    7575        subcatalog[0].secfilt[Nsecfilt*Naverage+Nsec].dM     = NAN;
     76        subcatalog[0].secfilt[Nsecfilt*Naverage+Nsec].Mstdev = NAN_S_SHORT;
    7677        subcatalog[0].secfilt[Nsecfilt*Naverage+Nsec].Xm     = NAN;
    7778        subcatalog[0].secfilt[Nsecfilt*Naverage+Nsec].M_20   = NAN_S_SHORT;
     
    158159      subcatalog[0].measureT[Nmeasure].averef = Naverage;
    159160      if (RESET) {
    160         if (!KEEP_UBERCAL) {
    161           subcatalog[0].measureT[Nmeasure].Mcal = 0;
    162           subcatalog[0].measureT[Nmeasure].dbFlags &= ~ID_MEAS_PHOTOM_UBERCAL;
     161        // only reset Mcal for measures with a matching image
     162        // do not reset Mcal for ubercal images unless explicitly requested
     163        if (subcatalog[0].measureT[Nmeasure].dbFlags & ID_MEAS_PHOTOM_UBERCAL) {
     164          if (!KEEP_UBERCAL) {
     165            subcatalog[0].measureT[Nmeasure].Mcal = 0.0;
     166            subcatalog[0].measureT[Nmeasure].dbFlags &= ~ID_MEAS_PHOTOM_UBERCAL;
     167          }
     168        } else {
     169          if (getImageEntry (Nmeasure, Ncat) >= 0) {
     170            subcatalog[0].measureT[Nmeasure].Mcal = 0.0;
     171          }
    163172        }
    164173        subcatalog[0].measureT[Nmeasure].dbFlags &= ~PHOTOM_FLAGS;
  • trunk/Ohana/src/relphot/src/global_stats.c

    r33651 r33963  
    11# include "relphot.h"
     2
     3# define MARKTIME(MSG,...) { \
     4  float dtime; \
     5  gettimeofday (&stopTimer, (void *) NULL); \
     6  dtime = DTIME (stopTimer, startTimer); \
     7  fprintf (stderr, MSG, __VA_ARGS__); }
    28
    39void global_stats (Catalog *catalog, int Ncatalog, FlatCorrectionTable *flatcorr) {
     
    511  StatType stN, stX, stS, imN, imX, imM, imD, msM, msX, msN, msD;
    612
    7   initstats ("MEAN");
     13  // struct timeval startTimer, stopTimer;
    814
    915  fprintf (stderr, "\n");
    1016  fprintf (stderr, "STATS            median     mean    sigma      min      max   Nmeas\n");
     17
     18  // gettimeofday (&startTimer, (void *) NULL);
    1119
    1220  int Ns;
     
    1725    int seccode = photcodes[Ns][0].code;
    1826
     27    // MARKTIME("start star stats: %f sec\n", dtime);
    1928    stN = statsStarN (catalog, Ncatalog, Nsec, seccode, flatcorr);
     29    // MARKTIME("done star N: %f sec\n", dtime);
    2030    stX = statsStarX (catalog, Ncatalog, Nsec);
     31    // MARKTIME("done star X: %f sec\n", dtime);
    2132    stS = statsStarS (catalog, Ncatalog, Nsec);
     33    // MARKTIME("done star S: %f sec\n", dtime);
    2234 
    2335    fprintf (stderr, "   --- stats for %s ---\n", photcodes[Ns][0].name);
     
    4658  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);
    4759  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);
    48  
    49 
    50   initstats (STATMODE);
    51 
    5260}
    5361
  • trunk/Ohana/src/relphot/src/initialize.c

    r33651 r33963  
    1212    PhotcodeList = strcreate (argv[1]);
    1313    photcodes = ParsePhotcodeList (PhotcodeList, &Nphotcodes, TRUE); // require SEC photcodes
    14   }
     14  } else {
     15    char tmpline1[256];
     16    int Ns;
     17    Nphotcodes = GetPhotcodeNsecfilt ();
     18    ALLOCATE (photcodes, PhotCode *, Nphotcodes);
     19    ALLOCATE (PhotcodeList, char, 256);
     20    for (Ns = 0; Ns < Nphotcodes; Ns++) {
     21      photcodes[Ns] = GetPhotcodebyNsec (Ns);
     22      if (Ns > 0) {
     23        snprintf (tmpline1, 256, "%s,%s", PhotcodeList, photcodes[Ns][0].name);
     24      } else {
     25        snprintf (tmpline1, 256, "%s", photcodes[Ns][0].name);
     26      }
     27      strcpy (PhotcodeList, tmpline1);
     28    }
     29  }   
     30   
    1531  if (USE_GRID && (Nphotcodes > 1)) {
    1632    fprintf (stderr, "grid correction analysis currently can only operate on a single photcode\n");
    1733    exit (1);
    1834  }
    19 
    20   initstats (STATMODE);
    2135
    2236  IMAGE_BAD = ID_IMAGE_PHOTOM_POOR | ID_IMAGE_PHOTOM_FEW | ID_IMAGE_PHOTOM_SKIP;
  • trunk/Ohana/src/relphot/src/liststats.c

    r33651 r33963  
    11# include "relphot.h"
    22
    3 enum {M_MEAN, M_MEDIAN, M_WT_MEAN, M_INNER_MEAN,
    4       M_INNER_WTMEAN, M_CHI_INNER_MEAN, M_CHI_INNER_WTMEAN};
     3void liststats_setmode (StatType *stats, char *strmode) {
    54
    6 static int statmode;
     5  stats->statmode = -1;
     6  if (!strcmp (strmode, "MEAN"))             { stats->statmode = STATS_MEAN; return; }
     7  if (!strcmp (strmode, "MEDIAN"))           { stats->statmode = STATS_MEDIAN; return; }
     8  if (!strcmp (strmode, "WT_MEAN"))          { stats->statmode = STATS_WT_MEAN; return; }
     9  if (!strcmp (strmode, "INNER_MEAN"))       { stats->statmode = STATS_INNER_MEAN; return; }
     10  if (!strcmp (strmode, "INNER_WTMEAN"))     { stats->statmode = STATS_INNER_WTMEAN; return; }
     11  if (!strcmp (strmode, "CHI_INNER_MEAN"))   { stats->statmode = STATS_CHI_INNER_MEAN; return; }
     12  if (!strcmp (strmode, "CHI_INNER_WTMEAN")) { stats->statmode = STATS_CHI_INNER_WTMEAN; return; }
    713
    8 void initstats (char *mode) {
    9 
    10   statmode = -1;
    11   if (!strcmp (mode, "MEAN")) statmode = M_MEAN;
    12   if (!strcmp (mode, "MEDIAN")) statmode = M_MEDIAN;
    13   if (!strcmp (mode, "WT_MEAN")) statmode = M_WT_MEAN;
    14   if (!strcmp (mode, "INNER_MEAN")) statmode = M_INNER_MEAN;
    15   if (!strcmp (mode, "INNER_WTMEAN")) statmode = M_INNER_WTMEAN;
    16   if (!strcmp (mode, "CHI_INNER_MEAN")) statmode = M_CHI_INNER_MEAN;
    17   if (!strcmp (mode, "CHI_INNER_WTMEAN")) statmode = M_CHI_INNER_WTMEAN;
    18 
    19   if (statmode == -1) {
    20     fprintf (stderr, "ERROR: invalid stats mode: %s\n", mode);
    21     exit (1);
    22   }
     14  fprintf (stderr, "ERROR: invalid stats mode: %s\n", strmode);
     15  exit (1);
    2316}
    2417
    25 int liststats (double *value, double *dvalue, int N, StatType *stats) {
     18int liststats (double *value, double *dvalue, double *weight, int N, StatType *stats) {
    2619 
    27   int i, ks, ke, Nm;
    28   double Mo, dMo, M, dM, X2, dS, *chi;
     20  int i, ks, ke;
     21  double Mo, dMo, M, dM, Nm, X2, dS, R, W, *chi;
     22
     23  myAssert (stats->statmode != STATS_NONE, "programming error, liststats mode not set");
    2924
    3025  ke = ks = dMo = 0;
     
    3732  if (N < 1) return (FALSE);
    3833
    39   dsortpair (value, dvalue, N);
    40   stats[0].median = value[(int)(0.5*N)];
    41   stats[0].min    = value[0];
    42   stats[0].max    = value[N-1];
    4334  int N80 = MIN (N-1, 0.8*N);
    4435  int N20 = MAX (0, 0.2*N);
     36
     37  if (weight) {
     38    dsortthree (value, dvalue, weight, N);
     39  } else {
     40    dsortpair (value, dvalue, N);
     41  }
     42
     43  // these values do not depend on the errors or weighting scheme
     44  stats[0].median  = value[(int)(0.5*N)];
     45  stats[0].min     = value[0];
     46  stats[0].max     = value[N-1];
    4547  stats[0].Upper80 = value[N80];
    4648  stats[0].Lower20 = value[N20];
    4749
    48   switch (statmode) {
    49   case M_MEDIAN:
    50     ks = 0;
    51     ke = N;
    52     Mo = stats[0].median;
    53     Nm = N;
    54     goto chisq;
    55     break;
    56   case M_MEAN:
    57   case M_WT_MEAN:
    58     ks = 0;
    59     ke = N;
    60     break;
    61   case M_INNER_MEAN:
    62   case M_INNER_WTMEAN:
    63   case M_CHI_INNER_MEAN:
    64   case M_CHI_INNER_WTMEAN:
    65     ks = 0.25*N + 0.50;
    66     ke = 0.75*N + 0.25;
    67     if (N <= 3) {
     50  switch (stats->statmode) {
     51    case STATS_MEDIAN:
    6852      ks = 0;
    6953      ke = N;
    70     }
    71     break;
     54      Mo = stats[0].median;
     55      Nm = N;
     56      goto chisq;
     57      break;
     58    case STATS_MEAN:
     59    case STATS_WT_MEAN:
     60      ks = 0;
     61      ke = N;
     62      break;
     63    case STATS_INNER_MEAN:
     64    case STATS_INNER_WTMEAN:
     65    case STATS_CHI_INNER_MEAN:
     66    case STATS_CHI_INNER_WTMEAN:
     67      ks = 0.25*N + 0.50;
     68      ke = 0.75*N + 0.25;
     69      if (N <= 3) {
     70        ks = 0;
     71        ke = N;
     72      }
     73      break;
     74    case STATS_NONE:
     75      myAbort ("undefined stats");
    7276  }   
    7377
    74   if ((statmode == M_CHI_INNER_MEAN) || (statmode == M_CHI_INNER_WTMEAN)) {
     78  // for these two modes, I need a vector of the chi-square contribution
     79  // I'm actually just using chisq to get the correct sorting order
     80  if ((stats->statmode == STATS_CHI_INNER_MEAN) || (stats->statmode == STATS_CHI_INNER_WTMEAN)) {
    7581    ALLOCATE (chi, double, N);
    7682    for (i = 0; i < N; i++) {
    7783      chi[i] = (value[i] - stats[0].median) / dvalue[i];
    7884    }
    79     dsortthree (chi, value, dvalue, N);
     85    if (weight) {
     86      dsortfour (chi, value, dvalue, weight, N);
     87    } else {
     88      dsortthree (chi, value, dvalue, N);
     89    }
    8090    free (chi);
    8191  }
    8292
    83   /* calculating the per-star offset based on the weighted average */
    84   M = dM = Nm = 0;
    85   if ((statmode == M_WT_MEAN) || (statmode == M_INNER_WTMEAN) || (statmode == M_CHI_INNER_WTMEAN)) {
    86     for (i = ks; i < ke; i++) {
    87       M   += value[i] / SQ (dvalue[i]);
    88       dM  += 1.0 / SQ (dvalue[i]);
    89       Nm  ++; 
    90     }   
    91     Mo = M / dM;
    92     dMo = sqrt (1.0 / dM);
     93  int WeightedMean = FALSE;
     94  WeightedMean |= (stats->statmode == STATS_WT_MEAN);
     95  WeightedMean |= (stats->statmode == STATS_INNER_WTMEAN);
     96  WeightedMean |= (stats->statmode == STATS_CHI_INNER_WTMEAN);
     97
     98  /* calculating the per-star offset based on the desired weighting scheme */
     99  M = dM = Nm = W = R = 0;
     100  if (weight) {
     101    // the weight value is multiplied by whichever nominal weighting scheme is provided
     102    // thus the user should set weight to 1.0 for nominal weight, and 100 for heavy weight (or so)
     103    // and 0.01 for under-weight
     104    if (WeightedMean) {
     105      for (i = ks; i < ke; i++) {
     106        M  += value[i] * weight[i] / SQ(dvalue[i]);
     107        W  +=            weight[i] / SQ(dvalue[i]);
     108        dM += SQ (weight[i] / dvalue[i]);
     109        R  += weight[i] / SQ(dvalue[i]);
     110        Nm += 1.0; 
     111      }
     112      Mo  = M / W;
     113      dMo = sqrt (dM) / R;
     114    } else {
     115      for (i = ks; i < ke; i++) {
     116        M  += value[i] * weight[i];
     117        W  +=            weight[i];
     118        dM += SQ (weight[i] * dvalue[i]);
     119        R  += weight[i];
     120        Nm += 1.0; 
     121      }
     122      Mo  = M / W;
     123      dMo = sqrt (dM) / R;
     124    }
    93125  } else {
    94     for (i = ks; i < ke; i++) {
    95       M   += value[i];
    96       dM  += SQ (dvalue[i]);
    97       Nm  ++; 
    98     }   
    99     Mo = M / (double) Nm;
    100     dMo = sqrt (dM / (double) Nm);
     126    // NULL weight vector is supplied, revert to standard form (above reverts if weight[i] == 1)
     127    if (WeightedMean) {
     128      // weighted by inverse-variance
     129      for (i = ks; i < ke; i++) {
     130        M   += value[i] / SQ (dvalue[i]);
     131        dM  += 1.0 / SQ (dvalue[i]);
     132        Nm  += 1.0; 
     133      }
     134      Mo = M / dM;
     135      dMo = sqrt (1.0 / dM);
     136    } else {
     137      // pure un-weighted
     138      for (i = ks; i < ke; i++) {
     139        M   += value[i];
     140        dM  += SQ (dvalue[i]);
     141        Nm  += 1.0; 
     142      }
     143      Mo = M / Nm;
     144      dMo = sqrt (dM) / Nm;
     145    }
    101146  }
    102147
     
    111156  }
    112157  X2 = X2 / (Nm - 1);
    113   dS = sqrt (dS / Nm);
     158  dS = sqrt (dS / (Nm - 1));
    114159
    115160  stats[0].mean  = Mo;
     
    122167}
    123168
     169// we could define the weight to be the only scale factor:
     170// \mu      = \sum (value_i * weight_i) / \sum (weight_i)
     171// \sigma^2 = (1/R) \sum (weight_i^2 \sigma_i^2)
     172// R = \sum (weight_i^2)
     173
     174// or, we could define the weight to be a scale factor times the inverse error:
     175// \mu      = \sum (value_i * weight_i / sigma_i) / \sum (weight_i)
     176// \sigma^2 = (1/R) \sum (weight_i^2 \sigma_i^2)
     177// R = \sum (weight_i^2)
  • trunk/Ohana/src/relphot/src/load_catalogs.c

    r33651 r33963  
    6868
    6969    // select only the brighter stars
    70     bcatalog (&catalog[i], &tcatalog);
     70    bcatalog (&catalog[i], &tcatalog, i);
    7171    dvo_catalog_unlock (&tcatalog);
    7272    dvo_catalog_free (&tcatalog);
     
    123123
    124124    // ensure that the paths are absolute path names
    125     char *tmppath = abspath (table->hosts[i].pathname, MAX_PATH_LENGTH);
     125    char *tmppath = abspath (table->hosts[i].pathname, DVO_MAX_PATH);
    126126    free (table->hosts[i].pathname);
    127127    table->hosts[i].pathname = tmppath;
     
    190190  }
    191191  if (!PARALLEL_MANUAL && !PARALLEL_SERIAL) {
    192     HostTableWaitJobsGetIO (table, __FILE__, __LINE__, VERBOSE);
     192    // if any one of the remote jobs fails, we should fail and exit
     193    int status = HostTableWaitJobsGetIO (table, __FILE__, __LINE__, VERBOSE);
     194    if (!status) {
     195      fprintf (stderr, "at least one remote client job failed to load data, exiting\n");
     196      exit (3);
     197    }
    193198  }
    194199
  • trunk/Ohana/src/relphot/src/load_images.c

    r33651 r33963  
    1515  off_t     *LineNumber;
    1616  struct timeval start, stop;
     17  char *inSubset;
    1718
    1819  SkyTable *sky = NULL;
     
    3435  MARKTIME("read image table: %f sec\n", dtime);
    3536
     37  // allocate and init an array to identify the images included in the subset
     38  ALLOCATE (inSubset, char, Nimage);
     39  memset (inSubset, 0, Nimage);
     40
    3641  // determine the populated SkyRegions overlapping the requested area
    3742
     
    4550    // select the images which overlap the selected sky regions
    4651    // 'subset' points to a new copy of the data (different from 'image')
    47     subset = select_images (skylist, image, Nimage, &LineNumber, &Nsubset);
     52    subset = select_images (skylist, image, Nimage, inSubset, &LineNumber, &Nsubset, NULL);
    4853    MARKTIME("selected %d overlapping images: %f sec\n", (int) Nsubset, dtime);
    4954  } else {
     
    5459      skylist = SkyListByPatch (sky, -1, &subregion);
    5560
    56       subregion.Rmin = region[0].Rmin; subregion.Rmax = 360.0;
    57       SkyList *extraList = SkyListByPatch (sky, -1, &subregion);
    58 
    5961      // select the images which overlap the selected sky regions
    6062      // 'subset' points to a new copy of the data (different from 'image')
    61       subset = select_images (skylist, image, Nimage, &LineNumber, &Nsubset);
     63      subset = select_images (skylist, image, Nimage, inSubset, &LineNumber, &Nsubset, &subregion);
    6264      MARKTIME("selected %d overlapping images: %f sec\n", (int) Nsubset, dtime);
    6365
     
    6668      off_t *LineNumberExtra, i;
    6769
    68       subsetExtra = select_images (extraList, image, Nimage, &LineNumberExtra, &NsubsetExtra);
     70      subregion.Rmin = region[0].Rmin; subregion.Rmax = 360.0;
     71      SkyList *extraList = SkyListByPatch (sky, -1, &subregion);
     72
     73      subsetExtra = select_images (extraList, image, Nimage, inSubset, &LineNumberExtra, &NsubsetExtra, &subregion);
    6974      MARKTIME("selected %d overlapping images: %f sec\n", (int) Nsubset, dtime);
    7075
     
    8388      // select the images which overlap the selected sky regions
    8489      // 'subset' points to a new copy of the data (different from 'image')
    85       subset = select_images (skylist, image, Nimage, &LineNumber, &Nsubset);
     90      subset = select_images (skylist, image, Nimage, inSubset, &LineNumber, &Nsubset, region);
    8691      MARKTIME("selected %d overlapping images: %f sec\n", (int) Nsubset, dtime);
    8792    }
    8893  }
    8994
     95# if (1)
     96  FILE *ftest = fopen ("skydump.dat", "w");
     97  int i;
     98  for (i = 0; i < skylist[0].Nregions; i++) {
     99    fprintf (ftest, "%s : %f %f : %f %f\n", skylist[0].regions[i][0].name, skylist[0].regions[i][0].Rmin, skylist[0].regions[i][0].Rmax, skylist[0].regions[i][0].Dmin, skylist[0].regions[i][0].Dmax);
     100  }
     101  fclose (ftest);
     102# endif
     103
     104  // match chips to mosaics (if applicable)
     105  initMosaics (subset, Nsubset, image, inSubset, Nimage);
     106  MARKTIME("init mosaics: %f sec\n", dtime);
     107 
    90108  // save the subset of images in the static reference in ImageOps, set up indexes
    91109  initImages (subset, LineNumber, Nsubset);
    92110  MARKTIME("init images: %f sec\n", dtime);
    93111
    94   // match chips to mosaics (if applicable)
    95   initMosaics (subset, Nsubset);
    96   MARKTIME("init mosaics: %f sec\n", dtime);
    97  
    98112  return (skylist);
    99113}
  • trunk/Ohana/src/relphot/src/reload_catalogs.c

    r33651 r33963  
    8686    TIMESTAMP(time4);
    8787
    88     setMrelFinal (&catalog, flatcorr);
     88    initMrel (&catalog, 1);
     89    setMrelFinal (&catalog, flatcorr, FALSE);
    8990    TIMESTAMP(time5);
    9091
     
    104105    freeGridBins (1);
    105106    TIMESTAMP(time7);
     107
     108    if (hostID) {
     109      client_logger_message ("updated catalog file %s\n", catalog.filename);
     110    }
    106111  }
    107112
     
    119124int reload_catalogs_parallel (SkyList *sky) {
    120125
    121   off_t Nimage;
    122   ImageSubset *image = getimages_subset (&Nimage);
    123 
    124   // write out the subset table of image information
     126  // name of image subset file:
    125127  char imageFile[512];
    126128  snprintf (imageFile, 512, "%s/Images.subset.dat", CATDIR);
    127   if (!ImageSubsetSave (imageFile, image, Nimage)) {
    128     fprintf (stderr, "failed to write image subset\n");
    129     exit (1);
    130   }
    131   free (image);
     129
     130  // the ApplyOffsets option re-uses an existing Images.subset.dat file
     131  if (!ApplyOffsets) {
     132    off_t Nimage;
     133    ImageSubset *image = getimages_subset (&Nimage);
     134    if (!ImageSubsetSave (imageFile, image, Nimage)) {
     135      fprintf (stderr, "failed to write image subset\n");
     136      exit (1);
     137    }
     138    free (image);
     139  } else {
     140    // load the current sky table (layout of all SkyRegions)
     141    SkyTable *skytable = SkyTableLoadOptimal (CATDIR, SKY_TABLE, GSCFILE, TRUE, SKY_DEPTH, VERBOSE);
     142    // XXX kind of hackish...
     143    ALLOCATE (sky, SkyList, 1);
     144    strcpy (sky->hosts, skytable->hosts);
     145  }
    132146
    133147  // now launch the relphot_client jobs to the parallel hosts
     
    140154
    141155    // ensure that the paths are absolute path names
    142     char *tmppath = abspath (table->hosts[i].pathname, MAX_PATH_LENGTH);
     156    char *tmppath = abspath (table->hosts[i].pathname, DVO_MAX_PATH);
    143157    free (table->hosts[i].pathname);
    144158    table->hosts[i].pathname = tmppath;
     
    201215  }
    202216  if (!PARALLEL_MANUAL && !PARALLEL_SERIAL) {
    203     HostTableWaitJobsGetIO (table, __FILE__, __LINE__, VERBOSE);
     217    int status = HostTableWaitJobsGetIO (table, __FILE__, __LINE__, VERBOSE);
     218    if (!status) {
     219      fprintf (stderr, "at least one remote client job failed to load data, exiting\n");
     220      exit (3);
     221    }
    204222  }
    205223  return (TRUE);
  • trunk/Ohana/src/relphot/src/relphot.c

    r33651 r33963  
    2323  if (UpdateAverages) {
    2424    relphot_objects (0, NULL);
     25    exit (0);
     26  }
     27
     28  if (ApplyOffsets) {
     29    // re-run this step from a previous attempt (assumes an existing Images.subset.dat file)
     30    if (!PARALLEL) {
     31      fprintf (stderr, "-apply-offsets only makes sense in an parallel context\n");
     32      exit (2);
     33    }
     34    reload_catalogs (NULL, NULL, 0, NULL);
    2535    exit (0);
    2636  }
     
    121131        plot_scatter (catalog, Ncatalog, flatcorr);
    122132      }
    123       setMrel  (catalog, Ncatalog, flatcorr);
     133      setMrel  (catalog, Ncatalog, flatcorr); // threaded
    124134      if (PLOTSTUFF) {
    125135        plot_scatter (catalog, Ncatalog, flatcorr);
     
    128138      setMmos  (catalog, FALSE, flatcorr);
    129139      setMgrid (catalog, flatcorr);
     140      MARKTIME("-- set Mrel, Mcal, Mmos, Mgrid : %f sec\n", dtime);
    130141   
    131142      if (PLOTSTUFF) {
     
    139150      // if (i < NLOOP - 1) rationalize_mosaics (catalog, Ncatalog);
    140151      // if (i % 6 == 1) rationalize_images ();
    141       if (i % 6 == 2) clean_measures (catalog, Ncatalog, FALSE, flatcorr);
    142       if (i % 6 == 3) clean_stars (catalog, Ncatalog);
    143       if (i % 6 == 5) clean_mosaics ();
    144       if (i % 6 == 5) clean_images ();
     152
     153      // NOTE : in the past, I was not iterating enough before cleaning.  make sure we do
     154      // at least 8 loops first -- that should get the systematic errors down to the ~1%
     155      // level, even in cases where we have an even split between photometric data and
     156      // data with 1 mag of extinction.
     157
     158      if ((i > 8) && (i % 8 == 2)) clean_measures (catalog, Ncatalog, FALSE, flatcorr);
     159      if ((i > 8) && (i % 8 == 3)) clean_stars (catalog, Ncatalog);
     160      if ((i > 8) && (i % 8 == 5)) clean_mosaics ();
     161      if ((i > 8) && (i % 8 == 5)) clean_images ();
    145162
    146163      // if ((i == 1) || (i == 5) || (i ==  9) || (i == 13)) clean_measures (catalog, Ncatalog, FALSE);
     
    148165      // if ((i == 4) || (i == 8) || (i == 12) || (i == 16)) clean_mosaics ();
    149166      // if ((i == 4) || (i == 8) || (i == 12) || (i == 16)) clean_images ();
    150       global_stats (catalog, Ncatalog, flatcorr);
     167      if (i % 3 == 2) global_stats (catalog, Ncatalog, flatcorr);
    151168      MARKTIME("-- finished loop %d: %f sec\n", i, dtime);
    152169    }
  • trunk/Ohana/src/relphot/src/relphot_client.c

    r33651 r33963  
    1919  // get configuration info, args, lockfile (set CATDIR, HOST_ID, HOSTDIR, etc)
    2020  initialize_client (argc, argv);
     21  client_logger_init ();
    2122
    2223  // load the current sky table (layout of all SkyRegions)
     
    3334      exit (2);
    3435  }
     36  client_logger_message ("loaded sky table and defined patch\n");
    3537 
    3638  switch (MODE) {
     
    4244          exit (2);
    4345      }
     46      client_logger_message ("loaded catalogs\n");
     47
    4448      BrightCatalog *bcatalog = BrightCatalogMerge (catalog, Ncatalog);
     49      client_logger_message ("generated subset data\n");
     50
    4551      if (!BrightCatalogSave (BCATALOG, bcatalog)) {
    4652          fprintf (stderr, "ERROR saving bright catalog from %s\n", CATDIR);
    4753          exit (2);
    4854      }
     55      client_logger_message ("generated subset table\n");
    4956      break;
    5057    }
     
    5865          exit (2);
    5966      }
     67      client_logger_message ("loaded image subset data\n");
    6068     
    6169      // save the available image information in the static array in ImageOps.c
     
    6674      snprintf (flatcorrFile, 1024, "%s/flatcorr.fits", CATDIR);
    6775      FlatCorrectionTable *flatcorr = FlatCorrectionLoad (flatcorrFile, VERBOSE);
     76      client_logger_message ("loaded flat-field correction data\n");
    6877
    6978      reload_catalogs (skylist, flatcorr, HOST_ID, HOSTDIR);
     79      client_logger_message ("updated catalogs\n");
    7080      break;
    7181    }
     
    7383    case MODE_UPDATE_OBJECTS: {
    7484      relphot_objects (HOST_ID, HOSTDIR);
     85      client_logger_message ("updated objects\n");
    7586      break;
    7687    }
     
    8091      abort();
    8192  }
     93  client_logger_message ("done with relphot_client\n");
    8294
    8395  exit (0);
    8496}
     97
  • trunk/Ohana/src/relphot/src/relphot_objects.c

    r33651 r33963  
    7878          catalog.secfilt[j*Nsecfilt + k].Map    = NAN;
    7979          catalog.secfilt[j*Nsecfilt + k].dM     = NAN;
     80          catalog.secfilt[j*Nsecfilt + k].Mstdev = NAN_S_SHORT;
    8081          catalog.secfilt[j*Nsecfilt + k].Xm     = NAN;
    8182          catalog.secfilt[j*Nsecfilt + k].M_20   = NAN_S_SHORT;
     
    8990    }
    9091
    91     setMave (&catalog, 1);
     92    populate_tiny_values(&catalog, DVO_TV_MEASURE | DVO_TV_AVERAGE);
     93
     94    initMrel (&catalog, 1);
     95    setMrelFinal (&catalog, NULL, TRUE);
    9296
    9397    if (!UPDATE) {
    9498      dvo_catalog_unlock (&catalog);
     99      free_tiny_values(&catalog);
    95100      dvo_catalog_free (&catalog);
    96101      continue;
     
    104109    dvo_catalog_save (&catalog, VERBOSE);
    105110    dvo_catalog_unlock (&catalog);
     111    free_tiny_values(&catalog);
    106112    dvo_catalog_free (&catalog);
    107113  }
     
    127133
    128134    // ensure that the paths are absolute path names
    129     char *tmppath = abspath (table->hosts[i].pathname, MAX_PATH_LENGTH);
     135    char *tmppath = abspath (table->hosts[i].pathname, DVO_MAX_PATH);
    130136    free (table->hosts[i].pathname);
    131137    table->hosts[i].pathname = tmppath;
  • trunk/Ohana/src/relphot/src/select_images.c

    r33651 r33963  
    1313} SkyRegionCoords;
    1414
     15void MakeSkyCoordIndex (SkyRegionCoords **skycoords_out, double **RmaxSky_out, off_t **index_out, SkyList *skylist);
    1516void dsortindex (double *X, off_t *Y, int N);
    1617off_t getRegionStartByRA (double R, double *Rref, off_t Nregions);
     
    2223  fprintf (stderr, MSG, __VA_ARGS__); }
    2324
    24 Image *select_images (SkyList *skylist, Image *timage, off_t Ntimage, off_t **LineNumber, off_t *Nimage) {
     25Image *select_images (SkyList *skylist, Image *timage, off_t Ntimage, char *inSubset, off_t **LineNumber, off_t *Nimage, SkyRegion *region) {
    2526 
    2627  Image *image;
     
    2829  off_t *line_number;
    2930  int InRange, ecode, found;
    30   double Ri[5], Di[5], Xi[5], Yi[5], dx, dy;
     31  double Ri[5], Di[5], Xi[5], Yi[5];
    3132  Coords tcoords;
    32   SkyRegionCoords *skycoords;
    3333  struct timeval start, stop;
    3434 
    35   double RmaxSkyRegion, RminSkyRegion, RmidSkyRegion, DminSkyRegion, DmaxSkyRegion;
    36 
    37   double *RmaxSky;
    38   off_t *index;
    39 
    4035  if (skylist[0].Nregions < 1) {
    4136    *Nimage = 0;
     
    5449  strcpy (tcoords.ctype, "RA---TAN");
    5550
    56   ALLOCATE (skycoords, SkyRegionCoords, skylist[0].Nregions);
    57 
    58   ALLOCATE (RmaxSky, double, skylist[0].Nregions);
    59   ALLOCATE (index, off_t, skylist[0].Nregions);
    60 
    61   RminSkyRegion = +360.0;
    62   RmaxSkyRegion = -360.0;
    63   DminSkyRegion = +90.0;
    64   DmaxSkyRegion = -90.0;
    65 
    66   D_NIMAGE = 6000;
    67 
    68   // FILE *ftest = fopen ("relphot.dump.dat", "w");
    69 
    70   /* compare with each region file */
     51  double RminSkyRegion = region[0].Rmin;
     52  double RmaxSkyRegion = region[0].Rmax;
     53  double DminSkyRegion = region[0].Dmin;
     54  double DmaxSkyRegion = region[0].Dmax;
     55
     56  double RmidSkyRegion = 0.5*(RminSkyRegion + RmaxSkyRegion);
     57
     58  // generate a set of Rmin/Rmax values using this RmidSkyRegion for DEC bands of width
     59  // dDecBand (0.1 deg).  DecIndex = (Dec + 90) / dDecBand
     60  double *RminBand, *RmaxBand;
     61  float dDecBand = 0.1;
     62  int NDecBands = 180 / dDecBand + 1;
     63  ALLOCATE (RminBand, double, NDecBands);
     64  ALLOCATE (RmaxBand, double, NDecBands);
     65  for (i = 0; i < NDecBands; i++) {
     66    RminBand[i] = +360.0;
     67    RmaxBand[i] = -360.0;
     68  }
     69 
     70   /* compare with each region file */
    7171  for (i = 0; i < skylist[0].Nregions; i++) {
    72 
    73     /* we make positional comparisons in the projection of catalog */
    74     skycoords[i].Rc = 0.5*(skylist[0].regions[i][0].Rmax + skylist[0].regions[i][0].Rmin);
    75     skycoords[i].Dc = 0.5*(skylist[0].regions[i][0].Dmax + skylist[0].regions[i][0].Dmin);
    76     tcoords.crval1 = skycoords[i].Rc;
    77     tcoords.crval2 = skycoords[i].Dc;
    78 
    79     /* define catalog corners */
    80     RD_to_XY (&skycoords[i].Xc[0], &skycoords[i].Yc[0], skylist[0].regions[i][0].Rmin, skylist[0].regions[i][0].Dmin, &tcoords);
    81     RD_to_XY (&skycoords[i].Xc[1], &skycoords[i].Yc[1], skylist[0].regions[i][0].Rmax, skylist[0].regions[i][0].Dmin, &tcoords);
    82     RD_to_XY (&skycoords[i].Xc[2], &skycoords[i].Yc[2], skylist[0].regions[i][0].Rmax, skylist[0].regions[i][0].Dmax, &tcoords);
    83     RD_to_XY (&skycoords[i].Xc[3], &skycoords[i].Yc[3], skylist[0].regions[i][0].Rmin, skylist[0].regions[i][0].Dmax, &tcoords);
    84     skycoords[i].Xc[4] = skycoords[i].Xc[0];   
    85     skycoords[i].Yc[4] = skycoords[i].Yc[0];   
    86 
    87     RmaxSky[i] = skylist[0].regions[i][0].Rmax;
    88     index[i] = i;
    89 
    90     dx = 0.02*(skycoords[i].Xc[2] - skycoords[i].Xc[0]);
    91     dy = 0.02*(skycoords[i].Yc[2] - skycoords[i].Yc[0]);
    92     skycoords[i].Xc[0] -= dx; skycoords[i].Yc[0] -= dy;
    93     skycoords[i].Xc[1] += dx; skycoords[i].Yc[1] -= dy;
    94     skycoords[i].Xc[2] += dx; skycoords[i].Yc[2] += dy;
    95     skycoords[i].Xc[3] -= dx; skycoords[i].Yc[3] += dy;
    96     skycoords[i].Xc[4] -= dx; skycoords[i].Yc[4] -= dy;
    97 
    98     RminSkyRegion = MIN(RminSkyRegion, skylist[0].regions[i][0].Rmin);
    99     RmaxSkyRegion = MAX(RmaxSkyRegion, skylist[0].regions[i][0].Rmax);
    100     DminSkyRegion = MIN(DminSkyRegion, skylist[0].regions[i][0].Dmin);
    101     DmaxSkyRegion = MAX(DmaxSkyRegion, skylist[0].regions[i][0].Dmax);
    102   }
    103   RmidSkyRegion = 0.5*(RminSkyRegion + RmaxSkyRegion);
    104   MARKTIME("create sky region coords: %f sec\n", dtime);
    105 
    106   dsortindex (RmaxSky, index, skylist[0].Nregions);
    107   MARKTIME("sort sky coords: %f sec\n", dtime);
     72    int iDecBandMin = (skylist[0].regions[i][0].Dmin + 90.0) / dDecBand;
     73    int iDecBandMax = (skylist[0].regions[i][0].Dmax + 90.0) / dDecBand;
     74
     75    double RminAlt = ohana_normalize_angle_to_midpoint (skylist[0].regions[i][0].Rmin, RmidSkyRegion);
     76    double RmaxAlt = ohana_normalize_angle_to_midpoint (skylist[0].regions[i][0].Rmax, RmidSkyRegion);
     77
     78    for (j = iDecBandMin; j <= iDecBandMax; j++) {
     79      RminBand[j] = MIN(RminBand[j], RminAlt);
     80      RmaxBand[j] = MAX(RmaxBand[j], RmaxAlt);
     81    }
     82  }
     83
     84# if (1)
     85  // XXX quick test of the dec bands:
     86  FILE *fout = fopen ("dec.bands.dat", "w");
     87  for (i = 0; i < NDecBands; i++) {
     88    fprintf (fout, "%d %f : %f - %f\n", (int) i, dDecBand * i - 90.0, RminBand[i], RmaxBand[i]);
     89  }
     90  fclose (fout);
     91# endif
     92
     93  SkyRegionCoords *skycoords = NULL;
     94  double *RmaxSky = NULL;
     95  off_t *index = NULL;
     96
     97  if (!USE_BASIC_CHECK) {
     98    MakeSkyCoordIndex (&skycoords, &RmaxSky, &index, skylist);
     99  }
    108100
    109101  if (VERBOSE) fprintf (stderr, "finding images\n");
    110102  BuildChipMatch (timage, Ntimage);
    111   MARKTIME("build chip match: %f sec\n", dtime);
     103  MARKTIME("build chip match for %d images: %f sec\n", (int) Ntimage, dtime);
     104
     105  D_NIMAGE = 6000;
    112106
    113107  nimage = 0;
     
    185179    if (RminImage > RmaxSkyRegion) continue;
    186180    if (RmaxImage < RminSkyRegion) continue;
     181
     182    // the above checks are only valid for the outermost region.  however, at a given
     183    // declination, the range of RA is limited by the actual catalog boundaries
     184    // check if this image is in range for the Dmax and Dmin locations
     185
     186    int iDecBandMin = (DminImage + 90.0) / dDecBand;
     187    int iDecBandMax = (DmaxImage + 90.0) / dDecBand;
     188
     189    // the sky region RA is defined to be 0 - 360.0
     190    if (RminImage < RminBand[iDecBandMin]) {
     191      if (VERBOSE2) fprintf (stderr, "skip image %s (%f,%f) on boundary\n", timage[i].name, 0.5*(RminImage + RmaxImage), 0.5*(DminImage + DmaxImage));
     192      continue;
     193    }
     194    if (RminImage < RminBand[iDecBandMax]) {
     195      if (VERBOSE2) fprintf (stderr, "skip image %s (%f,%f) on boundary\n", timage[i].name, 0.5*(RminImage + RmaxImage), 0.5*(DminImage + DmaxImage));
     196      continue;
     197    }
     198    if (RmaxImage > RmaxBand[iDecBandMin]) {
     199      if (VERBOSE2) fprintf (stderr, "skip image %s (%f,%f) on boundary\n", timage[i].name, 0.5*(RminImage + RmaxImage), 0.5*(DminImage + DmaxImage));
     200      continue;
     201    }
     202    if (RmaxImage > RmaxBand[iDecBandMax]) {
     203      if (VERBOSE2) fprintf (stderr, "skip image %s (%f,%f) on boundary\n", timage[i].name, 0.5*(RminImage + RmaxImage), 0.5*(DminImage + DmaxImage));
     204      continue;
     205    }
    187206
    188207    // image overlaps region, keep it
     
    230249  found_it:
    231250    image[nimage] = timage[i];
     251    inSubset[i] = TRUE;
    232252    /* always allow 'few' images to succeed, if possible (new images / detections may have
    233253     * been added) */
     
    255275  MARKTIME("finish image selection: %f sec\n", dtime);
    256276
    257   // fclose (ftest);
    258 
    259277  if (VERBOSE) fprintf (stderr, "found "OFF_T_FMT" images\n", nimage);
    260278
    261279  REALLOCATE (image, Image, MAX (nimage, 1));
    262280  REALLOCATE (line_number, off_t, MAX (nimage, 1));
    263   free (skycoords);
    264   free (RmaxSky);
    265   free (index);
     281
     282  if (!USE_BASIC_CHECK) {
     283    free (skycoords);
     284    free (RmaxSky);
     285    free (index);
     286  }
    266287
    267288  *Nimage  = nimage;
     
    379400  return (Nlo);
    380401}
     402
     403void MakeSkyCoordIndex (SkyRegionCoords **skycoords_out, double **RmaxSky_out, off_t **index_out, SkyList *skylist) {
     404
     405  off_t i;
     406  SkyRegionCoords *skycoords;
     407  Coords tcoords;
     408  double *RmaxSky;
     409  off_t *index;
     410  double dx, dy;
     411
     412  // the comparison is made in the catalog local projection. below we set crval1,2
     413  tcoords.crpix1 = tcoords.crpix2 = 0.0;
     414  tcoords.cdelt1 = tcoords.cdelt2 = 1.0 / 3600.0;
     415  tcoords.pc1_1  = tcoords.pc2_2 = 1.0;
     416  tcoords.pc1_2  = tcoords.pc2_1 = 0.0;
     417  strcpy (tcoords.ctype, "RA---TAN");
     418
     419  /* compare with each region file */
     420  ALLOCATE (skycoords, SkyRegionCoords, skylist[0].Nregions);
     421
     422  ALLOCATE (RmaxSky, double, skylist[0].Nregions);
     423  ALLOCATE (index, off_t, skylist[0].Nregions);
     424
     425  for (i = 0; i < skylist[0].Nregions; i++) {
     426
     427    /* we make positional comparisons in the projection of catalog */
     428    skycoords[i].Rc = 0.5*(skylist[0].regions[i][0].Rmax + skylist[0].regions[i][0].Rmin);
     429    skycoords[i].Dc = 0.5*(skylist[0].regions[i][0].Dmax + skylist[0].regions[i][0].Dmin);
     430    tcoords.crval1 = skycoords[i].Rc;
     431    tcoords.crval2 = skycoords[i].Dc;
     432
     433    /* define catalog corners */
     434    RD_to_XY (&skycoords[i].Xc[0], &skycoords[i].Yc[0], skylist[0].regions[i][0].Rmin, skylist[0].regions[i][0].Dmin, &tcoords);
     435    RD_to_XY (&skycoords[i].Xc[1], &skycoords[i].Yc[1], skylist[0].regions[i][0].Rmax, skylist[0].regions[i][0].Dmin, &tcoords);
     436    RD_to_XY (&skycoords[i].Xc[2], &skycoords[i].Yc[2], skylist[0].regions[i][0].Rmax, skylist[0].regions[i][0].Dmax, &tcoords);
     437    RD_to_XY (&skycoords[i].Xc[3], &skycoords[i].Yc[3], skylist[0].regions[i][0].Rmin, skylist[0].regions[i][0].Dmax, &tcoords);
     438    skycoords[i].Xc[4] = skycoords[i].Xc[0];   
     439    skycoords[i].Yc[4] = skycoords[i].Yc[0];   
     440
     441    RmaxSky[i] = skylist[0].regions[i][0].Rmax;
     442    index[i] = i;
     443
     444    dx = 0.02*(skycoords[i].Xc[2] - skycoords[i].Xc[0]);
     445    dy = 0.02*(skycoords[i].Yc[2] - skycoords[i].Yc[0]);
     446    skycoords[i].Xc[0] -= dx; skycoords[i].Yc[0] -= dy;
     447    skycoords[i].Xc[1] += dx; skycoords[i].Yc[1] -= dy;
     448    skycoords[i].Xc[2] += dx; skycoords[i].Yc[2] += dy;
     449    skycoords[i].Xc[3] -= dx; skycoords[i].Yc[3] += dy;
     450    skycoords[i].Xc[4] -= dx; skycoords[i].Yc[4] -= dy;
     451  }
     452
     453  dsortindex (RmaxSky, index, skylist[0].Nregions);
     454
     455  *RmaxSky_out = RmaxSky;
     456  *index_out = index;
     457  *skycoords_out = skycoords;
     458
     459  return;
     460}
  • trunk/Ohana/src/relphot/src/setMrelFinal.c

    r33651 r33963  
    55// output dbFlags values
    66
    7 void setMrelFinal (Catalog *catalog, FlatCorrectionTable *flatcorr) {
     7void setMrelFinal (Catalog *catalog, FlatCorrectionTable *flatcorr, int simpleAverage) {
    88
    99  off_t i;
     
    4343        catalog[0].secfilt[N].Map    = NAN;
    4444        catalog[0].secfilt[N].dM     = NAN;
     45        catalog[0].secfilt[N].Mstdev = NAN_S_SHORT;
    4546        catalog[0].secfilt[N].Xm     = NAN;
    4647        catalog[0].secfilt[N].M_20   = NAN_S_SHORT;
     
    6566          }
    6667       
    67           if (!KEEP_UBERCAL) {
    68             catalog[0].measure[m].Mcal = 0;
    69             catalog[0].measure[m].dbFlags &= ~ID_MEAS_PHOTOM_UBERCAL;
     68          // only reset Mcal for measures with a matching image
     69          // do not reset Mcal for ubercal images unless explicitly requested
     70
     71          if (catalog[0].measure[m].dbFlags & ID_MEAS_PHOTOM_UBERCAL) {
     72            if (!KEEP_UBERCAL) {
     73              catalog[0].measure[m].Mcal = 0.0;
     74              catalog[0].measure[m].dbFlags &= ~ID_MEAS_PHOTOM_UBERCAL;
     75            }
     76          } else {
     77            if (getImageEntry (m, 0) >= 0) {
     78              catalog[0].measure[m].Mcal = 0.0;
     79            }
    7080          }
    7181          catalog[0].measure[m].dbFlags &= ~PHOTOM_FLAGS;
     
    8494  }
    8595
    86   clean_measures (catalog, 1, TRUE, flatcorr);    /* mark outliers ID_MEAS_POOR_PHOTOM */
     96  // XXX make this optional? (do not clean for -averages?)
     97  if (!simpleAverage) clean_measures (catalog, 1, TRUE, flatcorr);    /* mark outliers ID_MEAS_POOR_PHOTOM */
    8798  for (i = 0; i < 5; i++) {
    8899    skip_measurements (catalog, i, flatcorr);       /* set ID_MEAS_SKIP for measures to be skipped */
    89100    setMrelOutput  (catalog, 1, i, flatcorr);    /* set Mrel using remaining measures */
    90101  }
    91   setMcalOutput (catalog, 1, flatcorr);
     102  if (!simpleAverage) setMcalOutput (catalog, 1, flatcorr);
    92103
    93104  /* clear ID_STAR_POOR, ID_STAR_FEW values before writing ??? */
     
    248259    }
    249260  }
    250   if (VERBOSE2) fprintf (stderr, "pass %d, Ntot: "OFF_T_FMT", Ntry: "OFF_T_FMT", Nskip: "OFF_T_FMT", Nkeep: "OFF_T_FMT"\n",
     261  if (VERBOSE) fprintf (stderr, "pass %d, Ntot: "OFF_T_FMT", Ntry: "OFF_T_FMT", Nskip: "OFF_T_FMT", Nkeep: "OFF_T_FMT"\n",
    251262                        pass, Ntot, Ntry, Nskip, Nkeep);
    252263}
  • trunk/Ohana/src/uniphot/include/setphot.h

    r33654 r33963  
    1919
    2020/* global variables set in parameter file */
    21 # define MAX_PATH_LENGTH 1024
    22 char         ImageCat[MAX_PATH_LENGTH];
     21# define DVO_MAX_PATH 1024
     22char         ImageCat[DVO_MAX_PATH];
    2323char        *CATDIR;
    2424int          HOST_ID;
  • trunk/Ohana/src/uniphot/src/initialize_setphot.c

    r33654 r33963  
    140140  // force CATDIR to be absolute (so parallel mode will work)
    141141  char *tmpcatdir = NULL;
    142   ALLOCATE (tmpcatdir, char, MAX_PATH_LENGTH);
     142  ALLOCATE (tmpcatdir, char, DVO_MAX_PATH);
    143143  GetConfig (config, "CATDIR",                 "%s",  0, tmpcatdir);
    144   CATDIR = abspath (tmpcatdir, MAX_PATH_LENGTH);
     144  CATDIR = abspath (tmpcatdir, DVO_MAX_PATH);
    145145  free (tmpcatdir);
    146146
  • trunk/Ohana/src/uniphot/src/setphot.c

    r33654 r33963  
    2121    zpts = load_zpt_ubercal (argv[1], &Nzpts, &flatcorrTable);
    2222
    23     char flatcorrfile[MAX_PATH_LENGTH];
    24     int size = snprintf (flatcorrfile, MAX_PATH_LENGTH, "%s/flatcorr.fits", CATDIR);
    25     assert (size < MAX_PATH_LENGTH);
     23    char flatcorrfile[DVO_MAX_PATH];
     24    int size = snprintf (flatcorrfile, DVO_MAX_PATH, "%s/flatcorr.fits", CATDIR);
     25    assert (size < DVO_MAX_PATH);
    2626    FlatCorrectionSave(&flatcorrTable, flatcorrfile);
    2727    // XXX should this program save any old copy of this file?
  • trunk/Ohana/src/uniphot/src/update_dvo_setphot.c

    r33654 r33963  
    105105
    106106    // ensure that the paths are absolute path names
    107     char *tmppath = abspath (table->hosts[i].pathname, MAX_PATH_LENGTH);
     107    char *tmppath = abspath (table->hosts[i].pathname, DVO_MAX_PATH);
    108108    free (table->hosts[i].pathname);
    109109    table->hosts[i].pathname = tmppath;
  • trunk/ippMonitor

  • trunk/ippScripts/scripts/destreak_restore_camera.pl

  • trunk/ippScripts/scripts/ipp_apply_burntool_single.pl

  • trunk/ippScripts/scripts/magic_destreak.pl

  • trunk/ippTools/share/camtool_find_pendingimfile.sql

  • trunk/ippTools/share/chiptool_setimfiletoupdate.sql

  • trunk/ippTools/share/pxadmin_create_tables.sql

  • trunk/ippTools/share/warptool_towarped.sql

  • trunk/ippTools/src

  • trunk/ippTools/src/magictool.c

  • trunk/ippconfig

  • trunk/ippconfig/recipes/reductionClasses.mdc

  • trunk/ppImage/src

  • trunk/psModules

  • trunk/psModules/src/objects/pmModelFuncs.h

    r29004 r33963  
    4646
    4747typedef enum {
    48     PM_MODEL_OP_NONE    = 0x00,
    49     PM_MODEL_OP_FUNC    = 0x01,
    50     PM_MODEL_OP_RES0    = 0x02,
    51     PM_MODEL_OP_RES1    = 0x04,
    52     PM_MODEL_OP_FULL    = 0x07,
    53     PM_MODEL_OP_SKY     = 0x08,
    54     PM_MODEL_OP_CENTER  = 0x10,
    55     PM_MODEL_OP_NORM    = 0x20,
    56     PM_MODEL_OP_NOISE   = 0x40,
     48    PM_MODEL_OP_NONE     = 0x00,
     49    PM_MODEL_OP_FUNC     = 0x01,
     50    PM_MODEL_OP_RES0     = 0x02,
     51    PM_MODEL_OP_RES1     = 0x04,
     52    PM_MODEL_OP_FULL     = 0x07,
     53    PM_MODEL_OP_SKY      = 0x08,
     54    PM_MODEL_OP_CENTER   = 0x10,
     55    PM_MODEL_OP_NORM     = 0x20,
     56    PM_MODEL_OP_NOISE    = 0x40,
     57    PM_MODEL_OP_MODELVAR = 0x80,
    5758} pmModelOpMode;
    5859
  • trunk/psModules/src/objects/pmSource.c

    r33879 r33963  
    5151    psFree(tmp->pixels);
    5252    psFree(tmp->variance);
     53    psFree(tmp->modelVar);
    5354    psFree(tmp->maskObj);
    5455    psFree(tmp->maskView);
     
    7778    psFree (source->pixels);
    7879    psFree (source->variance);
     80    psFree (source->modelVar);
    7981    psFree (source->maskObj);
    8082    psFree (source->maskView);
     
    8486    source->pixels = NULL;
    8587    source->variance = NULL;
     88    source->modelVar = NULL;
    8689    source->maskObj = NULL;
    8790    source->maskView = NULL;
     
    113116    source->pixels = NULL;
    114117    source->variance = NULL;
     118    source->modelVar = NULL;
    115119    source->maskObj = NULL;
    116120    source->maskView = NULL;
     
    200204    source->pixels   = in->pixels   ? psImageCopyView(NULL, in->pixels)   : NULL;
    201205    source->variance = in->variance ? psImageCopyView(NULL, in->variance) : NULL;
     206    source->modelVar = NULL;
    202207    source->maskView = in->maskView ? psImageCopyView(NULL, in->maskView) : NULL;
    203208
     
    10281033
    10291034    bool addNoise = mode & PM_MODEL_OP_NOISE;
     1035    bool addModelVar = mode & PM_MODEL_OP_MODELVAR;
     1036
     1037    if (addModelVar) psAssert (source->modelVar, "programming error");
    10301038
    10311039    // require the use of pmModelAddWithOffset if we are adding noise (because the model size and norm are rescaled)
     
    10501058        }
    10511059
    1052         psF32 **target = source->pixels->data.F32;
     1060        psF32 **target = addModelVar ? source->modelVar->data.F32 : source->pixels->data.F32;
    10531061
    10541062        for (int iy = 0; iy < source->modelFlux->numRows; iy++) {
     
    10651073            }
    10661074        }
    1067         if (add) {
    1068             source->tmpFlags &= ~PM_SOURCE_TMPF_SUBTRACTED;
    1069         } else {
    1070             source->tmpFlags |= PM_SOURCE_TMPF_SUBTRACTED;
     1075        if (!addModelVar) {
     1076            if (add) {
     1077                source->tmpFlags &= ~PM_SOURCE_TMPF_SUBTRACTED;
     1078            } else {
     1079                source->tmpFlags |= PM_SOURCE_TMPF_SUBTRACTED;
     1080            }
    10711081        }
    10721082        return true;
     
    10771087        target = source->variance;
    10781088    }
     1089    if (addModelVar) {
     1090        target = source->modelVar;
     1091    }
    10791092
    10801093    if (add) {
    10811094        status = pmModelAddWithOffset (target, source->maskObj, model, PM_MODEL_OP_FULL, maskVal, dx, dy);
    1082         source->tmpFlags &= ~PM_SOURCE_TMPF_SUBTRACTED;
     1095        if (!addNoise && !addModelVar) source->tmpFlags &= ~PM_SOURCE_TMPF_SUBTRACTED;
    10831096    } else {
    10841097        status = pmModelSubWithOffset (target, source->maskObj, model, PM_MODEL_OP_FULL, maskVal, dx, dy);
    1085         source->tmpFlags |= PM_SOURCE_TMPF_SUBTRACTED;
     1098        if (!addNoise && !addModelVar) source->tmpFlags |= PM_SOURCE_TMPF_SUBTRACTED;
    10861099    }
    10871100
  • trunk/psModules/src/objects/pmSource.h

    r33879 r33963  
    7272    psImage *pixels;                    ///< Rectangular region including object pixels.
    7373    psImage *variance;                  ///< Image variance.
     74    psImage *modelVar;                  ///< variance based on current models
    7475    psImage *maskObj;                   ///< unique mask for this object which marks included pixels associated with objects.
    7576    psImage *maskView;                  ///< view into global image mask for this object region
  • trunk/psModules/src/objects/pmSourcePhotometry.c

    r32998 r33963  
    899899}
    900900
    901 double pmSourceModelWeight(const pmSource *Mi, int term, const bool unweighted_sum, const float covarFactor, psImageMaskType maskVal)
     901double pmSourceModelWeight(const pmSource *Mi, int term, const pmSourceFitVarMode fitVarMode, const float covarFactor, psImageMaskType maskVal)
    902902{
    903903    PS_ASSERT_PTR_NON_NULL(Mi, NAN);
    904     double flux = 0, wt = 0, factor = 0;
     904    double flux = 0, wt = 1.0, factor = 0;
    905905
    906906    const psImage *Pi = Mi->modelFlux;
    907907    assert (Pi != NULL);
    908     const psImage *Wi = Mi->variance;
    909     if (!unweighted_sum) {
    910         assert (Wi != NULL);
    911     }
     908
     909    const psImage *Wi = NULL;
     910    switch (fitVarMode) {
     911      case PM_SOURCE_PHOTFIT_CONST:
     912        break;
     913      case PM_SOURCE_PHOTFIT_IMAGE_VAR:
     914        Wi = Mi->variance;
     915        psAssert (Wi, "programming error");
     916        break;
     917      case PM_SOURCE_PHOTFIT_MODEL_VAR:
     918        Wi = Mi->modelVar;
     919        psAssert (Wi, "programming error");
     920        break;
     921      case PM_SOURCE_PHOTFIT_NONE:
     922        psAbort("programming error");
     923    }   
     924
    912925    const psImage *Ti = Mi->maskObj;
    913926    assert (Ti != NULL);
     
    915928    for (int yi = 0; yi < Pi->numRows; yi++) {
    916929        for (int xi = 0; xi < Pi->numCols; xi++) {
    917             if (Ti->data.PS_TYPE_IMAGE_MASK_DATA[yi][xi] & maskVal)
    918                 continue;
    919             if (!unweighted_sum) {
     930            if (Ti->data.PS_TYPE_IMAGE_MASK_DATA[yi][xi] & maskVal) continue;
     931            if (fitVarMode != PM_SOURCE_PHOTFIT_CONST) {
    920932                wt = covarFactor * Wi->data.F32[yi][xi];
    921                 if (wt == 0)
    922                     continue;
     933                if (wt == 0) continue;
    923934            }
    924935
     
    937948            }
    938949
    939             if (unweighted_sum) {
    940                 flux += (factor * Pi->data.F32[yi][xi]);
    941             } else {
    942                 flux += (factor * Pi->data.F32[yi][xi]) / wt;
    943             }
     950            // wt is 1.0 for CONST
     951            flux += (factor * Pi->data.F32[yi][xi]) / wt;
    944952        }
    945953    }
     
    947955}
    948956
    949 double pmSourceModelDotModel (const pmSource *Mi, const pmSource *Mj, const bool unweighted_sum, const float covarFactor, psImageMaskType maskVal)
     957double pmSourceModelDotModel (const pmSource *Mi, const pmSource *Mj, const pmSourceFitVarMode fitVarMode, const float covarFactor, psImageMaskType maskVal)
    950958{
    951959    PS_ASSERT_PTR_NON_NULL(Mi, NAN);
     
    955963    int xIs, xJs, yIs, yJs;
    956964    int xIe, yIe;
    957     double flux, wt;
     965    double flux;
     966    double wt = 1.0;
    958967
    959968    const psImage *Pi = Mi->modelFlux;
     
    962971    assert (Pj != NULL);
    963972
    964     const psImage *Wi = Mi->variance;
    965     if (!unweighted_sum) {
    966         assert (Wi != NULL);
    967     }
     973    const psImage *Wi = NULL;
     974    switch (fitVarMode) {
     975      case PM_SOURCE_PHOTFIT_CONST:
     976        break;
     977      case PM_SOURCE_PHOTFIT_IMAGE_VAR:
     978        Wi = Mi->variance;
     979        psAssert (Wi, "programming error");
     980        break;
     981      case PM_SOURCE_PHOTFIT_MODEL_VAR:
     982        Wi = Mi->modelVar;
     983        psAssert (Wi, "programming error");
     984        break;
     985      case PM_SOURCE_PHOTFIT_NONE:
     986        psAbort("programming error");
     987    }   
    968988
    969989    const psImage *Ti = Mi->maskObj;
     
    9951015                continue;
    9961016
    997             // XXX skip the nonsense weight pixels?
    998             if (unweighted_sum) {
    999                 flux += (Pi->data.F32[yi][xi] * Pj->data.F32[yj][xj]);
    1000             } else {
     1017            float value = (Pi->data.F32[yi][xi] * Pj->data.F32[yj][xj]);
     1018            switch (fitVarMode) {
     1019              case PM_SOURCE_PHOTFIT_CONST:
     1020                wt = 1.0;
     1021                break;
     1022              case PM_SOURCE_PHOTFIT_IMAGE_VAR:
     1023              case PM_SOURCE_PHOTFIT_MODEL_VAR:
    10011024                wt = covarFactor * Wi->data.F32[yi][xi];
    1002                 if (wt > 0) {
    1003                     flux += (Pi->data.F32[yi][xi] * Pj->data.F32[yj][xj]) / wt;
    1004                 }
    1005             }
     1025                break;
     1026              case PM_SOURCE_PHOTFIT_NONE:
     1027                psAbort("programming error");
     1028            }
     1029            // skip pixels with nonsense weight values
     1030            if (wt <= 0) continue;
     1031
     1032            flux += value / wt;
    10061033        }
    10071034    }
     
    10091036}
    10101037
    1011 double pmSourceDataDotModel (const pmSource *Mi, const pmSource *Mj, const bool unweighted_sum, const float covarFactor, psImageMaskType maskVal)
     1038double pmSourceDataDotModel (const pmSource *Mi, const pmSource *Mj, const pmSourceFitVarMode fitVarMode, const float covarFactor, psImageMaskType maskVal)
    10121039{
    10131040    PS_ASSERT_PTR_NON_NULL(Mi, NAN);
     
    10171044    int xIs, xJs, yIs, yJs;
    10181045    int xIe, yIe;
    1019     double flux, wt;
     1046    double flux;
     1047    double wt = 1.0;
    10201048
    10211049    const psImage *Pi = Mi->pixels;
     
    10241052    assert (Pj != NULL);
    10251053
    1026     const psImage *Wi = Mi->variance;
    1027     if (!unweighted_sum) {
    1028         assert (Wi != NULL);
    1029     }
     1054    const psImage *Wi = NULL;
     1055    switch (fitVarMode) {
     1056      case PM_SOURCE_PHOTFIT_CONST:
     1057        break;
     1058      case PM_SOURCE_PHOTFIT_IMAGE_VAR:
     1059        Wi = Mi->variance;
     1060        psAssert (Wi, "programming error");
     1061        break;
     1062      case PM_SOURCE_PHOTFIT_MODEL_VAR:
     1063        Wi = Mi->modelVar;
     1064        psAssert (Wi, "programming error");
     1065        break;
     1066      case PM_SOURCE_PHOTFIT_NONE:
     1067        psAbort("programming error");
     1068    }   
    10301069
    10311070    const psImage *Ti = Mi->maskObj;
     
    10571096                continue;
    10581097
    1059             // XXX skip the nonsense weight pixels?
    1060             if (unweighted_sum) {
    1061                 flux += (Pi->data.F32[yi][xi] * Pj->data.F32[yj][xj]);
    1062             } else {
     1098            float value = (Pi->data.F32[yi][xi] * Pj->data.F32[yj][xj]);
     1099            switch (fitVarMode) {
     1100              case PM_SOURCE_PHOTFIT_CONST:
     1101                wt = 1.0;
     1102                break;
     1103              case PM_SOURCE_PHOTFIT_IMAGE_VAR:
     1104              case PM_SOURCE_PHOTFIT_MODEL_VAR:
    10631105                wt = covarFactor * Wi->data.F32[yi][xi];
    1064                 if (wt > 0) {
    1065                     flux += (Pi->data.F32[yi][xi] * Pj->data.F32[yj][xj]) / wt;
    1066                 }
    1067             }
     1106                break;
     1107              case PM_SOURCE_PHOTFIT_NONE:
     1108                psAbort("programming error");
     1109            }
     1110            // skip pixels with nonsense weight values
     1111            if (wt <= 0) continue;
     1112
     1113            flux += value / wt;
     1114
    10681115        }
    10691116    }
  • trunk/psModules/src/objects/pmSourcePhotometry.h

    r31670 r33963  
    3838} pmSourcePhotometryMode;
    3939
     40typedef enum {
     41    PM_SOURCE_PHOTFIT_NONE       = 0,
     42    PM_SOURCE_PHOTFIT_CONST      = 1,
     43    PM_SOURCE_PHOTFIT_IMAGE_VAR  = 2,
     44    PM_SOURCE_PHOTFIT_MODEL_VAR  = 3,
     45} pmSourceFitVarMode;
     46
    4047bool pmSourcePhotometryModel(
    4148    float *fitMag,                      ///< integrated fit magnitude
     
    7582bool pmSourceMeasureDiffStats (pmSource *source, psImageMaskType maskVal, psImageMaskType markVal);
    7683
    77 double pmSourceDataDotModel (const pmSource *Mi, const pmSource *Mj, const bool unweighted_sum, const float covarFactor, psImageMaskType maskVal);
    78 double pmSourceModelDotModel (const pmSource *Mi, const pmSource *Mj, const bool unweighted_sum, const float covarFactor, psImageMaskType maskVal);
    79 double pmSourceModelWeight(const pmSource *Mi, int term, const bool unweighted_sum, const float covarFactor, psImageMaskType maskVal);
     84double pmSourceDataDotModel (const pmSource *Mi, const pmSource *Mj, const pmSourceFitVarMode fitVarMode, const float covarFactor, psImageMaskType maskVal);
     85double pmSourceModelDotModel (const pmSource *Mi, const pmSource *Mj, const pmSourceFitVarMode fitVarMode, const float covarFactor, psImageMaskType maskVal);
     86double pmSourceModelWeight(const pmSource *Mi, int term, const pmSourceFitVarMode fitVarMode, const float covarFactor, psImageMaskType maskVal);
    8087
    8188bool pmSourceNeighborFlags (pmSource *source);
  • trunk/psphot

  • trunk/psphot/src

  • trunk/psphot/src/psphot.h

    r33883 r33963  
    9999
    100100bool            psphotFitSourcesLinear (pmConfig *config, const pmFPAview *view, const char *filerule, bool final);
    101 bool            psphotFitSourcesLinearReadout (psMetadata *recipe, pmReadout *readout, psArray *sources, pmPSF *psf, bool final);
     101bool            psphotFitSourcesLinearReadout (psMetadata *recipe, pmReadout *readout, psArray *sources, pmPSF *psf, bool final, pmSourceFitVarMode fitVarMode);
    102102
    103103bool            psphotSourceSize (pmConfig *config, const pmFPAview *view, const char *filerule, bool getPSFsize);
  • trunk/psphot/src/psphotDefineFiles.c

    r25983 r33963  
    8585        output->save = true;
    8686    }
     87//    // optionally save the smoothed variance model (small FITS image)
     88//    if (psMetadataLookupBool(NULL, recipe, "SAVE.BACKMDL")) {
     89//        int DX = psMetadataLookupS32 (&status, recipe, "BACKGROUND.XBIN");
     90//        int DY = psMetadataLookupS32 (&status, recipe, "BACKGROUND.YBIN");
     91//        pmFPAfile *output = pmFPAfileDefineFromFile (config, input, DX, DY, "PSPHOT.VARMDL");
     92//        if (!output) {
     93//            psError(PSPHOT_ERR_CONFIG, false, "Cannot find a rule for PSPHOT.VARMDL");
     94//            return false;
     95//        }
     96//        output->save = true;
     97//    }
     98//    // optionally save the smoothed variance model's standard deviation (small FITS image)
     99//    if (psMetadataLookupBool(NULL, recipe, "SAVE.VARMDL.STDEV")) {
     100//        int DX = psMetadataLookupS32 (&status, recipe, "BACKGROUND.XBIN");
     101//        int DY = psMetadataLookupS32 (&status, recipe, "BACKGROUND.YBIN");
     102//        pmFPAfile *output = pmFPAfileDefineFromFile (config, input, DX, DY, "PSPHOT.VARMDL.STDEV");
     103//        if (!output) {
     104//            psError(PSPHOT_ERR_CONFIG, false, "Cannot find a rule for PSPHOT.VARMDL.STDEV");
     105//            return false;
     106//        }
     107//        output->save = true;
     108//    }
    87109    // optionally save the PSF Model
    88110    if (psMetadataLookupBool(NULL, recipe, "SAVE.PSF")) {
  • trunk/psphot/src/psphotEfficiency.c

    r32695 r33963  
    420420
    421421    // psphotFitSourcesLinearReadout subtracts the model fits
    422     if (!psphotFitSourcesLinearReadout(recipe, readout, fakeSourcesAll, psf, true)) {
     422    if (!psphotFitSourcesLinearReadout(recipe, readout, fakeSourcesAll, psf, true, PM_SOURCE_PHOTFIT_CONST)) {
    423423        psError(PS_ERR_UNKNOWN, false, "Unable to perform linear fit on fake sources.");
    424424        psFree(fakeSources);
  • trunk/psphot/src/psphotFitSourcesLinear.c

    r32996 r33963  
    1212static bool SetBorderMatrixElements (psSparseBorder *border, pmReadout *readout, psArray *sources, bool constant_weights, int SKY_FIT_ORDER, psImageMaskType markVal);
    1313
     14bool psphotGenerateModelVariance (pmConfig *config, const pmFPAview *view, pmFPAfile *file, int index, psMetadata *recipe, pmReadout *readout, psArray *sources);
     15pmSourceFitVarMode psphotGetFitVarMode (psMetadata *recipe);
     16bool psphotFreeModelVariance (pmReadout *readout, psArray *sources);
     17
    1418// for now, let's store the detections on the readout->analysis for each readout
    1519bool psphotFitSourcesLinear (pmConfig *config, const pmFPAview *view, const char *filerule, bool final)
     
    2428    assert (recipe);
    2529
     30    pmSourceFitVarMode fitVarMode = psphotGetFitVarMode (recipe);
     31    if (!fitVarMode) {
     32        psError (PSPHOT_ERR_CONFIG, true, "failed to get LINEAR_FIT_VARIANCE_MODE");
     33        return false;
     34    }
     35    // MODEL_VAR requires 2 passes -- in the first, we get the rough fluxes; in the second, we
     36    // use the flux to define the model variance before fitting the objects.  Other modes only
     37    // do a single pass.
     38    pmSourceFitVarMode fitVarModePass1 = (fitVarMode == PM_SOURCE_PHOTFIT_MODEL_VAR) ? PM_SOURCE_PHOTFIT_CONST : fitVarMode;
     39
    2640    int num = psphotFileruleCount(config, filerule);
    2741
     
    5064        psAssert (psf, "missing psf?");
    5165
    52         if (!psphotFitSourcesLinearReadout (recipe, readout, sources, psf, final)) {
     66        if (!psphotFitSourcesLinearReadout (recipe, readout, sources, psf, final, fitVarModePass1)) {
    5367            psError (PSPHOT_ERR_CONFIG, false, "failed to fit sources (linear) for %s entry %d", filerule, i);
    5468            return false;
    5569        }
     70
     71        // the MODEL_VAR weighting scheme requires knowledge of the model fluxes to generate the variance
     72        // after we have determined the initial set of fits, then we can generate the variance image and
     73        // re-run the fit against that variance.
     74        if (fitVarMode == PM_SOURCE_PHOTFIT_MODEL_VAR) {
     75            // generate the model variance image & source pointers
     76            if (!psphotGenerateModelVariance (config, view, file, i, recipe, readout, sources)) {
     77                psError (PSPHOT_ERR_CONFIG, false, "failed to fit sources (linear) for %s entry %d", filerule, i);
     78                return false;
     79            }
     80
     81            // replace all sources (use TMPF_SUBTRACTED as test)
     82            psphotReplaceAllSourcesReadout (config, view, filerule, i, recipe, false);
     83
     84            // rerun fit with correct fitVarMode
     85            if (!psphotFitSourcesLinearReadout (recipe, readout, sources, psf, final, fitVarMode)) {
     86                psError (PSPHOT_ERR_CONFIG, false, "failed to fit sources (linear) for %s entry %d", filerule, i);
     87                return false;
     88            }
     89
     90            // free the model variance image & source pointers
     91            if (!psphotFreeModelVariance (readout, sources)) {
     92                psError (PSPHOT_ERR_CONFIG, false, "failed to fit sources (linear) for %s entry %d", filerule, i);
     93                return false;
     94            }
     95        }
    5696
    5797        psphotVisualShowResidualImage (readout, (num > 0));
     
    62102}
    63103
    64 bool psphotFitSourcesLinearReadout (psMetadata *recipe, pmReadout *readout, psArray *sources, pmPSF *psf, bool final) {
     104// look up the fit variance mode from the recipe; older recipes do not have the value
     105// 'LINEAR_FIT_VARIANCE_MODE'; in those cases, look for 'CONSTANT_PHOTOMETRIC_WEIGHTS' as a boolean and
     106// set the value to either CONST or IMAGE_VAR
     107pmSourceFitVarMode psphotGetFitVarMode (psMetadata *recipe) {
     108
     109    bool status = false;
     110
     111    char *fitVarModeString = psMetadataLookupStr(&status, recipe, "LINEAR_FIT_VARIANCE_MODE");
     112    if (!status) {
     113        bool CONSTANT_PHOTOMETRIC_WEIGHTS = psMetadataLookupBool(&status, recipe, "CONSTANT_PHOTOMETRIC_WEIGHTS");
     114        if (!status) {
     115            psAbort("You must provide a value for LINEAR_FIT_VARIANCE_MODE or CONSTANT_PHOTOMETRIC_WEIGHTS");
     116        }
     117        pmSourceFitVarMode fitVarMode = CONSTANT_PHOTOMETRIC_WEIGHTS ? PM_SOURCE_PHOTFIT_CONST : PM_SOURCE_PHOTFIT_IMAGE_VAR;
     118        return fitVarMode;
     119    }
     120    if (!strcasecmp(fitVarModeString, "CONSTANT") || !strcasecmp(fitVarModeString, "CONST")) {
     121        return PM_SOURCE_PHOTFIT_CONST;
     122    }
     123    if (!strcasecmp(fitVarModeString, "IMAGE") || !strcasecmp(fitVarModeString, "IMAGE_VAR")) {
     124        return PM_SOURCE_PHOTFIT_IMAGE_VAR;
     125    }
     126    if (!strcasecmp(fitVarModeString, "MODEL") || !strcasecmp(fitVarModeString, "MODEL_VAR")) {
     127        return PM_SOURCE_PHOTFIT_MODEL_VAR;
     128    }
     129    psError (PSPHOT_ERR_CONFIG, false, "Invalid value for LINEAR_FIT_VARIANCE_MODE (%s)", fitVarModeString);
     130    return PM_SOURCE_PHOTFIT_NONE;
     131}
     132
     133bool psphotFitSourcesLinearReadout (psMetadata *recipe, pmReadout *readout, psArray *sources, pmPSF *psf, bool final, pmSourceFitVarMode fitVarMode) {
    65134
    66135    bool status;
     
    99168    if (psRegionIsNaN (AnalysisRegion)) psAbort("analysis region mis-defined");
    100169
    101     bool CONSTANT_PHOTOMETRIC_WEIGHTS =
    102         psMetadataLookupBool(&status, recipe, "CONSTANT_PHOTOMETRIC_WEIGHTS");
    103     if (!status) {
    104         psAbort("You must provide a value for the BOOL recipe CONSTANT_PHOTOMETRIC_WEIGHTS");
    105     }
    106170    int SKY_FIT_ORDER = psMetadataLookupS32(&status, recipe, "SKY_FIT_ORDER");
    107171    if (!status) {
     
    231295    psSparseBorder *border = psSparseBorderAlloc (sparse, nBorder);
    232296
     297    // if fitVarMode is MODEL_VAR, then we need to generate the model image variance
     298    // XXX we have two possibilities here:
     299
     300    // 1) do 2 passes, where in the first case we use the CONST weighting, and in the second
     301    // use the fitted model values to define the model
     302
     303    // 2) do a single pass, and use the model guess to define the model variance (but do I trust the Model Guess?)
     304
    233305    // fill out the sparse matrix elements and border elements (B)
    234306    // SRCi is the current source of interest
     
    238310
    239311        // diagonal elements of the sparse matrix (auto-cross-product)
    240         f = pmSourceModelDotModel (SRCi, SRCi, CONSTANT_PHOTOMETRIC_WEIGHTS, covarFactor, maskVal);
     312        f = pmSourceModelDotModel (SRCi, SRCi, fitVarMode, covarFactor, maskVal);
    241313        psSparseMatrixElement (sparse, i, i, f);
    242314
    243         // the formal error depends on the weighting scheme
    244         if (CONSTANT_PHOTOMETRIC_WEIGHTS) {
    245             float var = pmSourceModelDotModel (SRCi, SRCi, false, covarFactor, maskVal);
     315        // if we have used CONSTANT errors, then we need to calculate the value of the parameter error
     316        if (fitVarMode != PM_SOURCE_PHOTFIT_IMAGE_VAR) {
     317            float var = pmSourceModelDotModel (SRCi, SRCi, PM_SOURCE_PHOTFIT_IMAGE_VAR, covarFactor, maskVal);
    246318            errors->data.F32[i] = 1.0 / sqrt(var);
    247319        } else {
     
    251323
    252324        // find the image x model value
    253         f = pmSourceDataDotModel (SRCi, SRCi, CONSTANT_PHOTOMETRIC_WEIGHTS, covarFactor, maskVal);
     325        f = pmSourceDataDotModel (SRCi, SRCi, fitVarMode, covarFactor, maskVal);
    254326        psSparseVectorElement (sparse, i, f);
    255327
     
    257329        switch (SKY_FIT_ORDER) {
    258330          case 1:
    259             f = pmSourceModelWeight (SRCi, 1, CONSTANT_PHOTOMETRIC_WEIGHTS, covarFactor, maskVal);
     331            f = pmSourceModelWeight (SRCi, 1, fitVarMode, covarFactor, maskVal);
    260332            psSparseBorderElementB (border, i, 1, f);
    261             f = pmSourceModelWeight (SRCi, 2, CONSTANT_PHOTOMETRIC_WEIGHTS, covarFactor, maskVal);
     333            f = pmSourceModelWeight (SRCi, 2, fitVarMode, covarFactor, maskVal);
    262334            psSparseBorderElementB (border, i, 2, f);
    263335
    264336          case 0:
    265             f = pmSourceModelWeight (SRCi, 0, CONSTANT_PHOTOMETRIC_WEIGHTS, covarFactor, maskVal);
     337            f = pmSourceModelWeight (SRCi, 0, fitVarMode, covarFactor, maskVal);
    266338            psSparseBorderElementB (border, i, 0, f);
    267339            break;
     
    283355
    284356            // got an overlap; calculate cross-product and add to output array
    285             f = pmSourceModelDotModel (SRCi, SRCj, CONSTANT_PHOTOMETRIC_WEIGHTS, covarFactor, maskVal);
     357            f = pmSourceModelDotModel (SRCi, SRCj, fitVarMode, covarFactor, maskVal);
    286358            psSparseMatrixElement (sparse, j, i, f);
    287359        }
     
    321393
    322394    // set the sky, sky_x, sky_y components of border matrix
    323     SetBorderMatrixElements (border, readout, fitSources, CONSTANT_PHOTOMETRIC_WEIGHTS, SKY_FIT_ORDER, markVal);
     395    SetBorderMatrixElements (border, readout, fitSources, (fitVarMode == PM_SOURCE_PHOTFIT_CONST), SKY_FIT_ORDER, markVal);
    324396
    325397    psSparseConstraint constraint;
     
    479551    return true;
    480552}
     553
     554bool psphotModelBackgroundReadout(psImage *model,  // Model image
     555                                  psImage *modelStdev, // Model stdev image
     556                                  psMetadata *analysis, // Analysis metadata for outputs
     557                                  pmReadout *readout, // Readout for which to generate a background model
     558                                  psImageBinning *binning, // Binning parameters
     559                                  const pmConfig *config,// Configuration
     560                                  bool useVarianceImage
     561    );
     562
     563bool psphotGenerateModelVariance (pmConfig *config, const pmFPAview *view, pmFPAfile *file, int index, psMetadata *recipe, pmReadout *readout, psArray *sources) {
     564
     565    bool status = false;
     566    psRegion fullRegion = psRegionSet (0, 0, 0, 0);
     567
     568    // bit-masks to test for good/bad pixels
     569    psImageMaskType maskVal = psMetadataLookupImageMask(&status, recipe, "MASK.PSPHOT");
     570    assert (maskVal);
     571
     572    // bit-mask to mark pixels not used in analysis
     573    psImageMaskType markVal = psMetadataLookupImageMask(&status, recipe, "MARK.PSPHOT");
     574    assert (markVal);
     575
     576    // maskVal is used to test for rejected pixels, and must include markVal
     577    maskVal |= markVal;
     578
     579    // create a model variance image
     580    psImage *modelVar = psImageCopy (NULL, readout->variance, PS_TYPE_F32);
     581
     582    // find the binning information
     583    psImageBinning *backBinning = psphotBackgroundBinning (modelVar, config);
     584    assert (backBinning);
     585   
     586    psImage *varModel = psImageAlloc(backBinning->nXruff, backBinning->nYruff, PS_TYPE_F32); // Background model
     587    psImage *varModelStdev = psImageAlloc(backBinning->nXruff, backBinning->nYruff, PS_TYPE_F32); // Background model
     588
     589    if (!psphotModelBackgroundReadout(varModel, varModelStdev, NULL, readout, backBinning, config, true)) {
     590        psError(PS_ERR_UNKNOWN, false, "Unable to generate background model");
     591        psFree (varModel);
     592        psFree (varModelStdev);
     593        return false;
     594    }
     595
     596    // linear interpolation to full-scale
     597    if (!psImageUnbin (modelVar, varModel, backBinning)) {
     598        psError (PSPHOT_ERR_PROG, true, "inconsistent sizes for unbinning");
     599        psFree (varModel);
     600        psFree (varModelStdev);
     601        return false;
     602    }
     603
     604    psFree (varModel);
     605    psFree (varModelStdev);
     606
     607    // XXX for a test:
     608    psphotSaveImage (NULL, modelVar, "model.bck.fits");
     609
     610    // insert all of the source models
     611    for (int i = 0; i < sources->n; i++) {
     612
     613        // source of interest
     614        pmSource *source = sources->data[i];
     615
     616        // skip sources which were not fitted already
     617        if (!(source->mode & PM_SOURCE_MODE_LINEAR_FIT)) continue;
     618
     619        // pixel region appropriate for the source
     620        psRegion region = psRegionForImage (source->pixels, fullRegion);
     621
     622        // define the source->modelVar pixels (view on modelVar image)
     623        psAssert (!source->modelVar, "programming error : modelVar should be NULL here");
     624        psAssert (source->modelFlux, "programming error : modelFlux should not be NULL here");
     625        psAssert (source->modelFlux->data.F32, "programming error : modelFlux should not be NULL here");
     626        source->modelVar = psImageSubset(modelVar, region);
     627
     628        // add the source model to the model variance image
     629        pmSourceAdd (source, PM_MODEL_OP_MODELVAR, maskVal);
     630    }
     631
     632    // XXX for a test:
     633    psphotSaveImage (NULL, modelVar, "model.var.fits");
     634    psphotSaveImage (NULL, readout->variance, "image.var.fits");
     635
     636    // we save the model variance for future reference
     637    psMetadataAddImage(readout->analysis, PS_LIST_TAIL, "PSPHOT.MODEL.VAR", PS_META_REPLACE, "model variance", modelVar);
     638    psFree (modelVar);
     639
     640    return true;
     641}
     642
     643bool psphotFreeModelVariance (pmReadout *readout, psArray *sources) {
     644
     645    bool status = false;
     646
     647    // find the binning information
     648    psImage *modelVar = psMetadataLookupPtr(&status, readout->analysis, "PSPHOT.MODEL.VAR");
     649    assert (modelVar);
     650
     651    psMetadataRemoveKey (readout->analysis, "PSPHOT.MODEL.VAR");
     652
     653    // clear modelVar pointers for all of the source models
     654    for (int i = 0; i < sources->n; i++) {
     655
     656        // source of interest
     657        pmSource *source = sources->data[i];
     658        psFree (source->modelVar);
     659    }
     660
     661    return true;
     662}
  • trunk/psphot/src/psphotModelBackground.c

    r32348 r33963  
    3737// corresponding to the model.  Other information about the background model is saved on the
    3838// readout->analysis
    39 static bool psphotModelBackgroundReadout(psImage *model,  // Model image
    40                                   psImage *modelStdev, // Model stdev image
    41                                   psMetadata *analysis, // Analysis metadata for outputs
    42                                   pmReadout *readout, // Readout for which to generate a background model
    43                                   psImageBinning *binning, // Binning parameters
    44                                   const pmConfig *config // Configuration
     39bool psphotModelBackgroundReadout(psImage *model,  // Model image
     40                                  psImage *modelStdev, // Model stdev image
     41                                  psMetadata *analysis, // Analysis metadata for outputs
     42                                  pmReadout *readout, // Readout for which to generate a background model
     43                                  psImageBinning *binning, // Binning parameters
     44                                  const pmConfig *config,// Configuration
     45                                  bool useVarianceImage
    4546    )
    4647{
     
    4950    bool status = true;
    5051
    51     psImage *image = readout->image, *mask = readout->mask; // Image and mask for readout
     52    psImage *image = useVarianceImage ? readout->variance : readout->image;
     53    psImage *mask = readout->mask; // Image and mask for readout
    5254
    5355    // select the appropriate recipe information
     
    143145
    144146    // we save the binning structure for use in psphotMagnitudes
    145     psMetadataAddPtr(analysis, PS_LIST_TAIL, "PSPHOT.BACKGROUND.BINNING", PS_DATA_UNKNOWN | PS_META_REPLACE, "Background binning", binning);
     147    if (!useVarianceImage) {
     148        psMetadataAddPtr(analysis, PS_LIST_TAIL, "PSPHOT.BACKGROUND.BINNING", PS_DATA_UNKNOWN | PS_META_REPLACE, "Background binning", binning);
     149    }
    146150
    147151    psVector *dQ = psVectorAllocEmpty (100, PS_TYPE_F32);
     
    159163
    160164    // measure clipped median for subimages
    161     psRegion ruffRegion = {0,0,0,0};
    162     psRegion fineRegion = {0,0,0,0};
     165    psRegion ruffRegion = psRegionSet (0,0,0,0);
     166    psRegion fineRegion = psRegionSet (0,0,0,0);
    163167    for (int iy = 0; iy < model->numRows; iy++) {
    164168        for (int ix = 0; ix < model->numCols; ix++) {
     
    330334    psVectorStats (statsDQ, dQ, NULL, NULL, 0);
    331335
    332     psMetadataAddF32(readout->analysis, PS_LIST_TAIL, "SKY_MEAN",  PS_META_REPLACE, "sky mean", Value);
    333     psMetadataAddF32(readout->analysis, PS_LIST_TAIL, "SKY_STDEV", PS_META_REPLACE, "sky stdev", ValueStdev);
    334     psMetadataAddF32(readout->analysis, PS_LIST_TAIL, "SKY_DQ",    PS_META_REPLACE, "sky quartile slope", statsDQ->sampleMedian);
    335     psLogMsg ("psphot", PS_LOG_INFO, "image sky : mean %f, stdev %f, dQ %f", Value, ValueStdev, statsDQ->sampleMedian);
    336 
    337     // measure image and background stats and save for later output
    338     psStats *statsBck = psStatsAlloc (PS_STAT_SAMPLE_MEAN |
    339                                       PS_STAT_SAMPLE_STDEV |
    340                                       PS_STAT_MIN |
    341                                       PS_STAT_MAX);
    342     psImageStats (statsBck, model, NULL, 0);
    343     psMetadataAddF32 (readout->analysis, PS_LIST_TAIL, "MSKY_MN",  PS_META_REPLACE, "sky model mean",          statsBck->sampleMean);
    344     psMetadataAddF32 (readout->analysis, PS_LIST_TAIL, "MSKY_SIG", PS_META_REPLACE, "sky model stdev",         statsBck->sampleStdev);
    345     psMetadataAddF32 (readout->analysis, PS_LIST_TAIL, "MSKY_DEV", PS_META_REPLACE, "sky stdev",               ValueStdev);
    346     psMetadataAddF32 (readout->analysis, PS_LIST_TAIL, "MSKY_DQ",  PS_META_REPLACE, "sky quartile slope",      statsDQ->sampleMedian);
    347     psMetadataAddF32 (readout->analysis, PS_LIST_TAIL, "MSKY_MAX", PS_META_REPLACE, "sky model maximum value", statsBck->max);
    348     psMetadataAddF32 (readout->analysis, PS_LIST_TAIL, "MSKY_MIN", PS_META_REPLACE, "sky model minimum value", statsBck->min);
    349     psMetadataAddS32 (readout->analysis, PS_LIST_TAIL, "MSKY_NX", PS_META_REPLACE, "sky model size (x)",      model->numCols);
    350     psMetadataAddS32 (readout->analysis, PS_LIST_TAIL, "MSKY_NY", PS_META_REPLACE, "sky model size (y)",      model->numRows);
    351     psLogMsg ("psphot", PS_LOG_INFO, "background sky : min %f mean %f max %f stdev %f",
    352               statsBck->min, statsBck->sampleMean, statsBck->max, statsBck->sampleStdev);
     336    if (!useVarianceImage) {
     337        psMetadataAddF32(readout->analysis, PS_LIST_TAIL, "SKY_MEAN",  PS_META_REPLACE, "sky mean", Value);
     338        psMetadataAddF32(readout->analysis, PS_LIST_TAIL, "SKY_STDEV", PS_META_REPLACE, "sky stdev", ValueStdev);
     339        psMetadataAddF32(readout->analysis, PS_LIST_TAIL, "SKY_DQ",    PS_META_REPLACE, "sky quartile slope", statsDQ->sampleMedian);
     340        psLogMsg ("psphot", PS_LOG_INFO, "image sky : mean %f, stdev %f, dQ %f", Value, ValueStdev, statsDQ->sampleMedian);
     341
     342        // measure image and background stats and save for later output
     343        psStats *statsBck = psStatsAlloc (PS_STAT_SAMPLE_MEAN |
     344                                          PS_STAT_SAMPLE_STDEV |
     345                                          PS_STAT_MIN |
     346                                          PS_STAT_MAX);
     347        psImageStats (statsBck, model, NULL, 0);
     348        psMetadataAddF32 (readout->analysis, PS_LIST_TAIL, "MSKY_MN",  PS_META_REPLACE, "sky model mean",          statsBck->sampleMean);
     349        psMetadataAddF32 (readout->analysis, PS_LIST_TAIL, "MSKY_SIG", PS_META_REPLACE, "sky model stdev",         statsBck->sampleStdev);
     350        psMetadataAddF32 (readout->analysis, PS_LIST_TAIL, "MSKY_DEV", PS_META_REPLACE, "sky stdev",               ValueStdev);
     351        psMetadataAddF32 (readout->analysis, PS_LIST_TAIL, "MSKY_DQ",  PS_META_REPLACE, "sky quartile slope",      statsDQ->sampleMedian);
     352        psMetadataAddF32 (readout->analysis, PS_LIST_TAIL, "MSKY_MAX", PS_META_REPLACE, "sky model maximum value", statsBck->max);
     353        psMetadataAddF32 (readout->analysis, PS_LIST_TAIL, "MSKY_MIN", PS_META_REPLACE, "sky model minimum value", statsBck->min);
     354        psMetadataAddS32 (readout->analysis, PS_LIST_TAIL, "MSKY_NX", PS_META_REPLACE, "sky model size (x)",      model->numCols);
     355        psMetadataAddS32 (readout->analysis, PS_LIST_TAIL, "MSKY_NY", PS_META_REPLACE, "sky model size (y)",      model->numRows);
     356        psLogMsg ("psphot", PS_LOG_INFO, "background sky : min %f mean %f max %f stdev %f",
     357                  statsBck->min, statsBck->sampleMean, statsBck->max, statsBck->sampleStdev);
     358        psFree(statsBck);
     359    } else {
     360        psLogMsg ("psphot", PS_LOG_INFO, "variance data : mean %f, stdev %f, dQ %f", Value, ValueStdev, statsDQ->sampleMedian);
     361    }
    353362
    354363    psFree(statsDQ);
     
    356365
    357366    psFree(stats);
    358     psFree(statsBck);
    359367    psFree(statsDefaults);
    360368    psFree(binning);
     
    375383    psImage *modelStdev = psImageAlloc(binning->nXruff, binning->nYruff, PS_TYPE_F32); // Standard deviation
    376384
    377     if (!psphotModelBackgroundReadout(model, modelStdev, readout->analysis, readout, binning, config)) {
     385    if (!psphotModelBackgroundReadout(model, modelStdev, readout->analysis, readout, binning, config, false)) {
    378386        psFree(model);
    379387        psFree(modelStdev);
     
    400408    pmReadout *modelStdev = pmFPAGenerateReadout(config, view, "PSPHOT.BACKMDL.STDEV", inFPA, binning, index);
    401409
    402     if (!psphotModelBackgroundReadout(model->image, modelStdev->image, model->analysis, readout, binning, config)) {
     410    if (!psphotModelBackgroundReadout(model->image, modelStdev->image, model->analysis, readout, binning, config, false)) {
    403411        psError(PS_ERR_UNKNOWN, false, "Unable to generate background model");
    404412        return false;
  • trunk/psphot/src/psphotStackImageLoop.c

  • trunk/psphot/src/psphotTest.c

    r33089 r33963  
    103103# if (0)
    104104
    105     psRegion region = {0,0,0,0};        // a region representing the entire array
     105psRegion region = psRegionSet (0,0,0,0);        // a region representing the entire array
    106106    psphotTestArguments (&argc, argv);
    107107
  • trunk/psphot/src/psphotTestSourceOutput.c

    r21183 r33963  
    136136
    137137            // generate working image for this source
    138             psRegion region = {ix - dx, ix + dx, iy - dy, iy + dy};
     138            psRegion region = psRegionSet(ix - dx, ix + dx, iy - dy, iy + dy);
    139139
    140140            psImage *vM = psImageSubset (imMo, region);
  • trunk/pstamp/scripts

  • trunk/psvideophot

Note: See TracChangeset for help on using the changeset viewer.