コード例 #1
0
ファイル: get2dflags.c プロジェクト: brechmos-stsci/hstcal
int Get2dFlags (WF3Info *wf32d, Hdr *phdr) {

	extern int status;

	int missing = 0;	/* true if any calibration file is missing */
	int nsteps = 0;		/* number of calibration steps to perform */
		
	/* Check each reference file that we need. */

	if (checkDQI (phdr, wf32d, &missing, &nsteps))
	    return (status);

	if (checkCCD (phdr, wf32d, &missing))
	    return (status);

	if (checkDark (phdr, wf32d, &missing, &nsteps))
	    return (status);

	if (checkFlat (phdr, wf32d, &missing, &nsteps))
	    return (status);

	if (checkShad (phdr, wf32d, &missing, &nsteps))
	    return (status);

	if (checkPhot (phdr, wf32d, &missing, &nsteps))
	    return (status);

	if (missing) {
	    return (status = CAL_FILE_MISSING);
	} else if (nsteps < 1) {
	    trlwarn ("No calibration switch was set to PERFORM,");
	    trlwarn ("  or all reference files had PEDIGREE = DUMMY.");
	    return (status = NOTHING_TO_DO);
	} else {
	    return (status);
	}
}
コード例 #2
0
ファイル: acsrej_init.c プロジェクト: jhunkeler/hstcal
/* acsrej_init -- get the initial average pixel values

  Description:
  ------------
  Get the initial average according to the specified scheme

  Date          Author          Description
  ----          ------          -----------
  22-Sep-1998   W.J. Hack       initial version, uses multiamp noise,gain
  20-Mar-2000   W.J. Hack       corrected problem with rog2, needed to be array
  15-Apr-2002   W.J. Hack       correctly zero'd out npts array, added
                                DQ checking for BOTH median and minimum images,
                                also added ERR array for median image.
  26-Aug-2002   J. Blakeslee    Modified threshhold for minimum to use SCALENSE
                                only with sky-subtracted pixels.
  01-Dec-2015   P.L. Lim        Calculations now entirely in electrons.
  13-Jan-2016   P.L. Lim        Removed variance init and cleaned up function.
*/
int acsrej_init (IODescPtr ipsci[], IODescPtr ipdq[], clpar *par, int nimgs,
                 int dim_x, int dim_y, float efac[], float skyval[],
                 SingleGroup *sg, float *work) {
    /*
      Parameters:

      ipsci   i: Array of pointers to SCI extension of the given EXTVER,
                 each pointer is an input image. Unit now in electrons.
      ipdq    i: Array of pointers to DQ extension of the given EXTVER,
                 each pointer is an input image.
      par     i: User specified parameters.
      nimgs   i: Number of input images.
      dim_x, dim_y  i: Image dimension taken from the first input image.
                       All images must have the same dimension.
      efac    i: Array of EXPTIME for each image. If all inputs have
                 EXPTIME=0 (all biases), then the values are all set to 1.
      skyval  i: Array of sky values for each input image.
                 Unit now in electrons.
      sg      o: Its "sci" component is the average image used for
                 comparison during CR rejection. Unit is e/s.
                 This is really the median or minimum depending on
                 "initgues" provided by the user.
      work    o: Intermediate result used to calculate sg but not used
                 outside this function.
    */
    extern int status;

    float     val, raw, dumf;
    int       i, j, n, p, dum;
    float     *buf;
    short     *bufdq;
    int       *npts, *ipts;
    short     dqpat;
    Hdr       dqhdr;

    void      ipiksrt (float [], int, int[]);

    /* -------------------------------- begin ------------------------------- */

    dqpat = par->badinpdq;

    ipts = calloc (nimgs, sizeof(int));
    npts = calloc (dim_x, sizeof(int));
    buf = calloc (dim_x, sizeof(float));
    bufdq = calloc (dim_x, sizeof(short));

    /* Use the stack median to construct the initial average. */
    if (strncmp(par->initgues, "median", 3) == 0) {
        for (j = 0; j < dim_y; j++) {
            memset (npts, 0, dim_x*sizeof(int));

            for (n = 0; n < nimgs; n++) {
                initHdr(&dqhdr);
                getHeader(ipdq[n], &dqhdr);
                getFloatLine (ipsci[n], j, buf);  /* electrons */
                getShortLine (ipdq[n], j, bufdq);
                freeHdr(&dqhdr);

                /* Only use GOOD pixels to build initial image.
                   work array is already initialized to zeroes in acsrej_do.c */
                if (efac[n] > 0.) {
                    for (i = 0; i < dim_x; i++) {
                        if ((bufdq[i] & dqpat) == OK) {
                            PIX(work, npts[i], i, nimgs) =
                                (buf[i] - skyval[n]) / efac[n];  /* e/s */
                            npts[i] += 1;
                        }
                    }
                }
            }  /* End of nimgs loop */

            /* ALL AMPS */
            for (i = 0; i < dim_x; i++) {
                dum = npts[i];  /* Number of good data points */
                if (dum == 0)
                    Pix(sg->sci.data, i, j) = 0.0F;
                else {
                    /* Setup index array for sorting... */
                    for (p=0; p < nimgs; p++) ipts[p] = p;
                    /* Sort pixel stack and corresponding index array. */
                    ipiksrt (&PIX(work, 0, i, nimgs), dum, ipts);
                     /* Even number of input images for this pixel */
                    if ((dum / 2) * 2 == dum) {
                        Pix(sg->sci.data, i, j) =
                            (PIX(work, dum / 2 - 1, i, nimgs) +
                             PIX(work, dum / 2, i, nimgs)) / 2.;
                    } else {
                        Pix(sg->sci.data, i, j) = PIX(work, dum / 2, i, nimgs);
                    }
                }
            } /* End loop over ALL AMPS used on pixels in the line */
        } /* End loop over lines */

    /* use the minimum to construct the initial average */
    } else {
        if (strncmp(par->initgues, "minimum", 3) != 0) {
            sprintf (MsgText,
                     "Invalid INITGUES value %s, reset it to 'minimum'",
                     par->initgues);
            trlwarn (MsgText);
            strcpy (par->initgues, "minimum");
        }

        for (n = 0; n < nimgs; n++) {
            initHdr(&dqhdr);
            getHeader(ipdq[n], &dqhdr);

            for (j = 0; j < dim_y; j++) {
                getFloatLine (ipsci[n], j, buf);  /* electrons */
                getShortLine (ipdq[n], j, bufdq);

                /* ALL AMPS */
                for (i = 0; i < dim_x; i++) {
                    raw = buf[i];  /* e */
                    dumf = raw - skyval[n];  /* e */

                    if (efac[n] > 0.) {
                        /* Can be negative */
                        val = dumf / efac[n];  /* e/s */
                    } else {
                        val = 0.;
                    }

                    if ( (n == 0) || (val < Pix(sg->sci.data, i, j)) ) {
                        /* If this pixel is bad in the first image,
                           then the min is automatically set to 0. As a
                           result, only negative val is going to be stored and
                           valid positive min is ignored.
                           SLIGHTLY BUGGY HERE??? */
                        if ((bufdq[i] & dqpat) == OK && (efac[n] > 0.)) {
                            Pix(sg->sci.data, i, j) = val;  /* e/s */
                        } else {
                            Pix(sg->sci.data, i, j) = 0.;
                        }
                    }
                } /* End of loop over ALL AMPS for this line in each image */
            } /* End of loop over lines in image (y) */

            freeHdr(&dqhdr);
        } /* End of loop over images in set */
    }

    /* free the memory */
    free (ipts);
    free (npts);
    free (buf);
    free (bufdq);

    return (status);
}
コード例 #3
0
ファイル: wf3table.c プロジェクト: brechmos-stsci/hstcal
int GetAsnTable (AsnInfo *asn) {

    /* Arguments:
     **	asn		o: Association info structure
     */
    extern int status;

    /* Local variables */
    int i;				/* loop index */
    int nrows;			/* number of rows in ASNTAB */
    int col, row;			/* loop indexes */
    IRAFPointer tp;			/* ASNTAB table pointer */
    IRAFPointer colptr[NCOLS];	/* ASNTAB column pointers */
    int numsp;			/* number of sub-products in asn */
    int	posid;			/* id of sub-product */
    RowInfo *exp;		/* Internal structure for table information */
    int *spmems, *expmem;	/* number of EXP for each sub-product */
    int poslen;		/* Length of memtype string minus POSID */
    int prodid;		/* id of product 	*/
    int expid;
    int defid;		/* default position id for exposures */
    int procprod;
    int maxspmems;		/* max number of sub-product members */
    char *word;
    Bool proddth;
    char spname_ext[SZ_CBUF+1];	/* Extension for sub-product */
    char spname_ext_cte[SZ_CBUF+1];	/* Extension for sub-product */
    char memtype[SZ_COLNAME+1];
    char memsubtype[SZ_COLNAME+1];

    /* ASNTAB column names */
    char colname[NCOLS][SZ_COLNAME+1] = {
        "MEMNAME",
        "MEMTYPE",
        "MEMPRSNT"
    };

    /* Function definitions */
    void freeAsnInfo (AsnInfo *);
    int  allocAsnInfo (AsnInfo *, int, int *);
    void trlopenerr (char *);
    void trlwarn (char *);
    char *lowcase (char *, char *);
    int  MkName (char *, char *, char *, char *, char *, int);
    void initRowInfo (RowInfo *);
    int  streq_ic (char *, char *);  /* strings equal? (case insensitive) */

    if (asn->debug) {
        sprintf (MsgText, "GetAsnTable: ASN_TABLE is %s",asn->asn_table);
        trlmessage (MsgText); 
    }

    /* Open the ASN table */
    tp = c_tbtopn (asn->asn_table, IRAF_READ_ONLY, 0);
    if (c_iraferr()) {
        trlopenerr (asn->asn_table);
        return (status = TABLE_ERROR);
    }

    /* Get pointers to columns in ASNTAB */
    for (col=0; col < NCOLS; col++) {
        c_tbcfnd1 (tp, colname[col], &(colptr[col]));
        if (c_iraferr() || colptr[col] == 0) {
            sprintf (MsgText, "Can't find column %s in %s", colname[col],
                    asn->asn_table);
            trlerror (MsgText);
            c_tbtclo (tp);
            return (status = COLUMN_NOT_FOUND);
        }
    }

    /* Find out how many rows are in ASNTAB */
    nrows = 0;
    nrows = c_tbpsta (tp, TBL_NROWS);
    if (nrows <= 0) {
        sprintf (MsgText, "Invalid number of rows in %s", asn->asn_table);
        trlerror (MsgText);
        c_tbtclo (tp);
        return (status = TABLE_ERROR);
    }

    /* Initialize total number of members based on number of
     ** rows in table */
    asn->numasn = nrows;
    poslen = 0;

    /* Allocate space for internal variables */
    exp = NULL;
    exp = (RowInfo *)calloc(nrows, sizeof(RowInfo));
    for (row = 0; row < nrows; row++)
        initRowInfo (&(exp[row]));

    /* Read each row of ASNTAB into a local structure */
    for (row = 0; row < nrows; row++) {

        /* Get the MEMBER NAME in this row */
        c_tbegtt (tp, colptr[0], row+1, exp[row].memname, SZ_CBUF);
        if (c_iraferr()) {
            sprintf (MsgText, "Can't read %s in row %d in %s", colname[0],
                    row+1, asn->asn_table);
            trlerror (MsgText);
            c_tbtclo (tp);
            free (exp);
            return (status = ELEMENT_NOT_FOUND);
        }

        /* Convert to lowercase for use as a file name */
        for (i = 0; i < strlen(exp[row].memname); i++)
            exp[row].memname[i] = tolower(exp[row].memname[i]);

        /* Get the TYPE in this row */
        c_tbegtt (tp, colptr[1], row+1, exp[row].mtype, SZ_CBUF);
        if (c_iraferr()) {
            sprintf (MsgText, "Can't read %s in row %d in %s", colname[1],
                    row+1, asn->asn_table);
            trlerror (MsgText);
            c_tbtclo (tp);
            free (exp);
            return (status = ELEMENT_NOT_FOUND);
        }

        /* Convert to lowercase for use later in routine.
         ** Also, if a value of MEMTYPE contains a UNDERLINE, then 
         ** record conversion to DASH in trailer file and warn
         ** user to correct the value. */
        lowcase (exp[row].type, exp[row].mtype);
        for (i = 0; i < strlen(exp[row].type); i++) {
            if (exp[row].type[i] == UNDERLINE_CHAR) {       
                exp[row].type[i] = DASH_CHAR;
                sprintf(MsgText, "MEMTYPE %s in row %d was INVALID and needs to be corrected.",
                        exp[row].mtype, row+1);
                trlwarn(MsgText);
            }
        }

        /* Get the STATUS in this row */
        c_tbegtb (tp, colptr[2], row+1, &(exp[row].prsnt));
        if (c_iraferr()) {
            sprintf (MsgText, "Can't read %s in row %d in %s", colname[2],
                    row+1, asn->asn_table);
            trlerror (MsgText);
            c_tbtclo (tp);
            free (exp);
            return (status = ELEMENT_NOT_FOUND);
        }
        if (asn->debug) {
            sprintf (MsgText, "GetAsnTable: Read in row %d from ASN table",
                    row);
            trlmessage (MsgText);
        }
    }

    /*  
     ** Determine whether CRCORR or RPTOBS processing will be required
     ** by searching for MEMTYPE of EXP_CR* or EXP_RPT*, respectively.
     ** Once it is determined, go on to next step...
     */
    for (row = 0; row < nrows; row++) {

        /* Check to see if we need to do CR-SPLIT combination ... */
        if (strstr (exp[row].type, "-cr") != NULL) {
            asn->crcorr = PERFORM;
            asn->rptcorr = OMIT;
            poslen = CRLEN;
            break;

            /* ... or REPEAT-OBS combination ... 	*/
        } else if (strstr (exp[row].type, "-rp") != NULL) { 
            asn->rptcorr = PERFORM;
            asn->crcorr = OMIT;
            poslen = RPTLEN;
            break;

            /* ... or neither at all	*/
        } else {
            asn->rptcorr = OMIT;
            asn->crcorr = OMIT;
            poslen = DTHLEN;
        }	
    }

    /* Default to always perform DRIZCORR step */
    asn->dthcorr = PERFORM;

    if (asn->debug) {
        sprintf (MsgText, "GetAsnTable: CRCORR = %d, RPTCORR = %d",
                asn->crcorr,asn->rptcorr);
        trlmessage (MsgText);
    }

    /* Sort through the list figuring out which are input vs. output
     ** files, and see if any input files are missing. */
    /* Initialize local variables */
    numsp   = 0;
    posid   = 0;
    prodid  = 0;
    proddth = False;
    defid   = 1;

    /* Find out how many products/sub-products are in the association
     ** and determine the posid for each member. */	
    for (row = 0; row < nrows; row++) {
        memtype[0] = '\0';
        memsubtype[0] = '\0';

        /* As long as this is not the final product,
         ** count number of members in each product/sub-product...*/
        if (strstr(exp[row].type,"prod-dth") != NULL) {
            exp[row].posid = 0;	
            posid = 0;	

            /* If we have a dither product listed, we want to eventually
             ** perform dither combining step... */	
            prodid++;
            proddth = True;

            /* We always want to produce a product, but if
             ** not set to PERFORM, then create an empty product... */
            if (asn->dthcorr == OMIT) 
                asn->dthcorr = DUMMY;

        } else {

            strcpy(memtype,exp[row].type);	
            /* Let's start by breaking up the MEMTYPE string */
            word = strtok(memtype,"-");
            strcpy(memsubtype,word);
            /* The end of this second part of MEMTYPE has the POSID */
            word = strtok(NULL,"\n");

            /* If the last character of the memtype is a number or letter, 
             ** convert to an integer value...  */
            if (streq_ic(word,"crj") || streq_ic(word,"rpt") || streq_ic(word,"crc") ) {
                posid = 1;
            } else {
                if (exp[row].prsnt || streq_ic(memsubtype,"prod")) {

                    if (isalnum(word[poslen])) {
                        /* Interpret the POSID from the second part
                         ** of MEMTYPE */
                        posid=(int)strtol(&word[poslen],(char **)NULL,10);
                    } else {
                        /* Otherwise, assume it is a different pointing
                         ** and assign an incremented position ID. After
                         ** all, it is NOT a CR-SPLIT or RPT-OBS exposure.*/
                        posid = defid;
                        defid++;
                    }
                }
            }

            /* Keep track of how many sub-products there are based on
             ** POSID from MEMTYPE values */

            if (posid > numsp) {
                if ((exp[row].prsnt && (strstr(memtype,"exp") != NULL)) ||
                        strstr(memtype,"prod") != NULL) {
                    numsp++;
                }
            }

            exp[row].posid = posid;		
        }

        if (asn->debug) {
            sprintf (MsgText, "GetAsnTable: Posid = %d for row %d",posid,
                    row);
            trlmessage (MsgText);
        }	

        /* If the member is missing, give a warning */
        /* This implies that MEMPRSNT must be set to YES for EXP_*
         ** This is not fatal for WF3.  Simply decrement tmembers. */
        if (!exp[row].prsnt && strncmp(exp[row].type, "prod-",5) != 0) {
            sprintf (MsgText, "Member \"%s\" is not present",
                    exp[row].memname);
            trlwarn (MsgText);		 
            asn->numasn--;
            /* Now flag row as being absent so it doesn't get passed
             ** along for further processing... */
            exp[row].posid = MEMABSENT;
        }
    }

    if (asn->debug) {
        sprintf (MsgText, "GetAsnTable: NUMSP = %d, PRODID = %d",numsp,
                prodid);
        trlmessage (MsgText);
    }

    /* Check for existence of enough data to process */
    if (asn->numasn < 1) {
        trlerror ("No data available for given assoc. table");
        freeAsnInfo (asn);
        return (status = ERROR_RETURN);
    }

    /* Record the number of products found in association */
    if (proddth) {
        asn->numprod = prodid;
    } else {
        /* If there are no PROD-DTH entries in ASN table, set
         ** numprod to 1 */
        asn->numprod = prodid + 1;
    }

    /* Determine what elements should be processed based on
     ** initial input, either FULL or PARTIAL processing.  */
    procprod = 0;
    if (asn->process != FULL) {
        for (row=0; row < nrows; row++){
            /* Look for entry with same name as input */
            if (streq_ic(exp[row].memname, asn->rootname)) {
                /* We only want to process this product	*/
                procprod = exp[row].posid;
                numsp = 1;
            }	
        }
    }

    /* Allocate space to count number of exposures per sub-product
     ** with spmems[0] being reserved for final output product
     ** since POSID starts indexing at 1. */
    spmems = (int *)calloc(numsp+1,sizeof(int));
    expmem = (int *)calloc(numsp+1,sizeof(int));

    /* Initialize arrays */
    for (i=0; i <= numsp; i++) {
        spmems[i] = 0;
        expmem[i] = 0;
    }

    /* For each sub-product,
     ** identify each EXP that belongs to that posid and 
     ** is present to be processed. */
    for (row=0; row < nrows; row++) {
        if (strstr(exp[row].type, "exp-") && exp[row].posid > MEMABSENT) {

            if ((asn->process != FULL && exp[row].posid == procprod) ||
                    asn->process == FULL) {

                spmems[exp[row].posid]++;
                /* Exposure IDs will start at 1 to be consistent 
                 ** with POSID numbering. Initialize here, count later. */
                expmem[exp[row].posid] = 1;
            }
        }
    }

    /* Allocate slots for all members in ASN info structure */
    if (allocAsnInfo (asn, numsp, spmems)) {
        return (status = TABLE_ERROR);
    }

    asn->product[prodid].prodid = prodid;

    /* Reset prodid for filling ASN table */
    prodid = 0;

    /* Copy summary information about ASN relationships to ASN structure. */
    maxspmems = 0;
    asn->numsp = numsp;
    for (i=0; i <= numsp; i++) {
        asn->spmems[i] = spmems[i];
        if (spmems[i] > maxspmems)
            maxspmems = spmems[i];
    }

    /* If there aren't any sub-products with more than 1 member, then
     ** omit crcorr/rptcorr processing */
    if ((maxspmems < 2) && asn->crcorr == PERFORM) {
        sprintf (MsgText,
                "No sub-product with more than 1 member; CRCORR will be skipped");
        trlwarn (MsgText);
        asn->crcorr = DUMMY;
    } else if ((maxspmems < 2) && asn->rptcorr == PERFORM) {
        sprintf (MsgText,
                "No sub-product with more than 1 member; RPTCORR will be skipped");
        trlwarn (MsgText);
        asn->rptcorr = DUMMY;
    }

    /* Copy information read-in into ASN structure now... */
    for (row = 0; row < nrows; row++) {
        if (exp[row].posid != MEMABSENT) {
            if ((asn->process != FULL && exp[row].posid == procprod) ||
                    asn->process == FULL) {	  
                posid = exp[row].posid;

                /* Is this row the final product entry? */
                if (strstr(exp[row].type, "prod-dth") != NULL) {
                    strcpy (asn->product[prodid].name, exp[row].memname);
                    strcpy (asn->product[prodid].mtype, exp[row].type);
                    asn->product[prodid].prsnt = exp[row].prsnt;
                    asn->product[prodid].numsp = numsp;
                    asn->product[prodid].asnrow = row+1;

                    /* Create full file name for this image */
                    if (MkName (exp[row].memname, "_raw", "_drz", "",
                                asn->product[prodid].prodname, SZ_LINE)){
                        strcpy(asn->product[prodid].prodname,
                                exp[row].memname);
                        strcat (asn->product[prodid].prodname,
                                "_drz.fits");
                    }
                    
                    /* Create full file name for this CTE image */
                    if (MkName (exp[row].memname, "_rac_tmp", "_drc", "",
                                asn->product[prodid].prodname_cte, SZ_LINE)){
                        strcpy(asn->product[prodid].prodname_cte,
                                exp[row].memname);
                        strcat (asn->product[prodid].prodname_cte,
                                "_drc.fits");
                    }
                    

                    /* Or, is this row an input exposure? */
                } else if (strstr(exp[row].type, "exp-") != NULL) {

                    if (exp[row].posid > MEMABSENT) {

                        /* Internal counter for which exposure we want for
                         ** a position */
                        expid = expmem[posid];
                        strcpy(asn->product[prodid].subprod[posid].exp[expid].name,
                                exp[row].memname);		
                        strcpy(asn->product[prodid].subprod[posid].exp[expid].mtype,
                                exp[row].type);
                        asn->product[prodid].subprod[posid].exp[expid].prsnt =
                            exp[row].prsnt;
                        asn->product[prodid].subprod[posid].exp[expid].asnrow=
                            row+1;

                        /* Create full file name for this image */
                        if (MkName (exp[row].memname, "_raw", "_raw", "",
                                    asn->product[prodid].subprod[posid].exp[expid].expname,
                                    SZ_LINE)) {

                            strcpy(asn->product[prodid].subprod[posid].exp[expid].expname,
                                    exp[row].memname);
                            strcat(asn->product[prodid].subprod[posid].exp[expid].expname,
                                    "_raw.fits");
                        }

                        /* Fill-in sub-product information for EXP-DTH
                         ** exposures which don't create sub-products */
                        if (strstr(exp[row].type, "exp-dth") != NULL) {
                            if (!MkName (exp[row].memname, "_raw", "_flt", "",
                                        asn->product[prodid].subprod[posid].spname,
                                        SZ_LINE) ) {

                                strcpy(asn->product[prodid].subprod[posid].name,
                                        exp[row].memname);
                                strcpy(asn->product[prodid].subprod[posid].mtype,
                                        exp[row].type);
                                asn->product[prodid].subprod[posid].posid =
                                    exp[row].posid;
                            }
                        }

                        /* Increment that counter for next exposure's id
                         ** for this posid */
                        expmem[posid]++;
                    }

                    /* If neither, it must be a sub-product */
                } else {

                    if (spmems[posid] > 0) {

                        strcpy(asn->product[prodid].subprod[posid].name,
                                exp[row].memname);
                        strcpy(asn->product[prodid].subprod[posid].mtype,
                                exp[row].type);
                        asn->product[prodid].subprod[posid].prsnt =
                            exp[row].prsnt;
                        asn->product[prodid].subprod[posid].asnrow = row+1;


                        /* Create full file name for this image for 
                         ** DTHCORR input */
                        spname_ext[0] = '\0';
                        spname_ext_cte[0] = '\0';
                        if (asn->crcorr || asn->rptcorr) {
                            strcpy (spname_ext, "_crj");
                            strcpy (spname_ext_cte,"_crc");
                        } else {
                            strcpy (spname_ext, "_sfl");
                            strcpy (spname_ext_cte, "_sfl");
                        }

                        if (MkName (exp[row].memname, "_raw", spname_ext, "",
                                    asn->product[prodid].subprod[posid].spname,
                                    SZ_LINE)) {

                            strcpy(asn->product[prodid].subprod[posid].spname,
                                    exp[row].memname);
                            strcat(asn->product[prodid].subprod[posid].spname,
                                    spname_ext);		
                            strcat(asn->product[prodid].subprod[posid].spname,
                                    ".fits");		
                                    
                        }
                        if (MkName (exp[row].memname, "_raw", spname_ext_cte, "",
                                    asn->product[prodid].subprod[posid].spname_cte,
                                    SZ_LINE)) {

                            strcpy(asn->product[prodid].subprod[posid].spname_cte,
                                    exp[row].memname);
                            strcat(asn->product[prodid].subprod[posid].spname_cte,
                                    spname_ext_cte);		
                            strcat(asn->product[prodid].subprod[posid].spname_cte,
                                    ".fits");		
                                    
                        }

                        asn->product[prodid].subprod[posid].numexp =
                            spmems[posid];
                        asn->product[prodid].subprod[posid].posid = posid;

                    }
                }
            }
        } /* Process only those exposures where MEMPRSNT == YES */
    }

    /* Close the ASN table.  We are done reading it in. */
    c_tbtclo (tp);



    /* Clean up memory usage as well. */
    free (spmems);
    free (expmem);
    free (exp);

    if (asn->debug) {
        trlmessage ("GetAsnTable: Info from ASN read into memory.");
    }

    /* Successful return */
    return (status);
}
コード例 #4
0
ファイル: cr_scaling.c プロジェクト: jhunkeler/hstcal
/*
Description:
------------
If using the exposure time, the scaling factors are normalized to ratios 
relative to the max exposure. 

    Date            Author      Description
    ----            ------      -----------
    24-Sep-1998     W.J. Hack   Initial Version
    18-Mar-1999     W.J. Hack   Revised to read EXPTIMEs from Primary headers
                                using image-template list directly
    20-Oct-1999     W.J. Hack   Revised to compute number of good input images
                                and insure they are less than MAX_FILES.
    14-Apr-2000     W.J. Hack   Revised to also return final EXPEND appropriate
                                for output CR-combined product
    14-Mar-2002     W.J. Hack   Added computation of cumulative DARKTIME
    4-Apr-2002      W.J. Hack   added initialization of 'totd'
   24-Apr-2002      W.J. Hack   removed darktime altogether, find initial EXPSTART
*/
int cr_scaling (char *expname, IRAFPointer tpin, float efac[], int *nimgs, double *expend, double *expstart)
{
    extern int status;

    Hdr         prihdr;
    int         nzero, k;
    char        fdata[CHAR_FNAME_LENGTH + 1];
    IODescPtr   ip;
    int         numimgs;        /* How many good input images are there? */

    double     end, keyend, keystart, start;

    int         GetKeyFlt (Hdr *, char *, int, float, float *);
    int         GetKeyDbl (Hdr *, char *, int, double, double *);
    /* -------------------------------- begin ---------------------------------- */

    /* Rewind the image template pointer */
    c_imtrew(tpin);

    *nimgs = c_imtlen(tpin);
    end = 0.0;
    keyend = 0.0;
    start = 1e+10;
    keystart = 0.0;

    
    /* Check to make sure there are not too many images to work with... */
    if (*nimgs > MAX_FILES) {
        trlerror("There are too many input images to combine. "); 
        return(status = NOTHING_TO_DO);
    }

    /* if the parameter scaling is null, all images have equal weight. 
        If no keyword name is given for the exposure time, assume equal
        weights of 1 for all images.
    */
    if (expname[0] == '\0') {
        return (status);
    }

    /* Use exposure time as scaling factor */
    nzero = 0;	
     
    /* loop all input files counting how many usable inputs there are */
    numimgs = 0;
    for (k = 0; k < *nimgs; ++k) {

        /* read the next input image name in the template list */
        c_imtgetim (tpin, fdata, CHAR_FNAME_LENGTH);

        /* open the primary header */
        ip = openInputImage (fdata, "", 0);
        if (hstio_err()) {
            sprintf (MsgText, "Cannot open data file '%s'", fdata);
            trlerror (MsgText);
            return (status = OPEN_FAILED);
        }

        initHdr (&prihdr);

        /* read in primary header from image */
        getHeader (ip, &prihdr);

        if (GetKeyFlt (&prihdr, expname, USE_DEFAULT, 0., &efac[k]) != 0) {
            sprintf (MsgText, "cannot read '%s' from the primary header of '%s'", expname, fdata);
            trlerror (MsgText);
            freeHdr (&prihdr);
            return(status = KEYWORD_MISSING);
        }
        
        if (efac[k] < 0.) {
            sprintf (MsgText, "exposure time of file '%s' is negative", fdata);
            trlerror (MsgText);
            freeHdr (&prihdr);
            return(status = INVALID_VALUE);
        }
        if (efac[k] == 0.) {
            nzero++;
        }
        
        numimgs++;
        if (GetKeyDbl (&prihdr, "EXPEND", USE_DEFAULT, 0., &keyend) != 0) {
            sprintf (MsgText, "cannot read 'EXPEND' from the primary header of '%s'", fdata);
            trlerror (MsgText);
            freeHdr (&prihdr);
            return(status = KEYWORD_MISSING);
        }
        if (GetKeyDbl (&prihdr, "EXPSTART", USE_DEFAULT, 0., &keystart) != 0) {
            sprintf (MsgText, "cannot read 'EXPSTART' from the primary header of '%s'", fdata);
            trlerror (MsgText);
            freeHdr (&prihdr);
            return(status = KEYWORD_MISSING);
        }
        
        end = (keyend > end) ? keyend: end;
        start = (keystart < start) ? keystart : start;
        closeImage (ip);
        freeHdr (&prihdr);
    }
    
    if (nzero > 0 && nzero < *nimgs) {
        trlwarn ("Some (but not all) input imsets have zero exposure time.");
        trlwarn ("Final product will be compromised!");
        
        /* This type of error will need to be handled differently in order
            to allow pipeline processing of this type of dataset. 
        return (status = INVALID_VALUE);
        */
    }
    
    /* Only return the number of valid input images,
        initial EXPSTART and final EXPEND value
    */
    *nimgs = numimgs;
    *expend = end;
    *expstart = start;
    
    return (status);
}
コード例 #5
0
ファイル: acsrej_do.c プロジェクト: pllim/hstcal
/*  acsrej_do -- Perform the cosmic ray rejection for ACS images

  Description:
  ------------
  This is mostly a file bookkeeping routine for the cosmic ray rejection task.
  It takes care of input/output files open/close, check for dimensions, read/
  write data from/to files, allocate memory spaces etc.

    Date          Author          Description
    ----          ------          -----------
    06-May-1996   J.-C. Hsu       Adapt from the SPP code crrej_do.x
    05-Aug-1998   W. Hack         Modified to handle ACS data
    11-Feb-1999   W. Hack         EXPTIME now in Pri. Hdr.
    18-Mar-1999   W.J. Hack       Revised to read EXPTIMEs from Primary headers
                                  for cr_scaling using tpin directly
    14-Sep-1999   W.J. Hack       Cleaned up SHADCORR usage. Added check for max
                                  number of files here.
*/
int acsrej_do (IRAFPointer tpin, char *outfile, char *mtype, clpar *par, int newpar[])
{
    extern int  status;

    IODescPtr   ipsci[MAX_FILES];   /* science image descriptor */
    IODescPtr   ipdq[MAX_FILES];    /* data quality image descriptor */
    float       skyval[MAX_FILES];  /* background DN values */
    float       efac[MAX_FILES];    /* exposure factors */
    multiamp    noise;              /* readout noise */
    multiamp    gain;               /* A-to-D gain factors */
    float       exptot;
    float       texpt;
    int         nimgs;
    SingleGroup sg;
    int         niter = 0;
    float       sigma[MAX_ITER];

    Hdr         phdr;               /* primary header */
    int         extver;             /* Current extension being processed*/
    int         numext;             /* Number of extensions in each image */
    int         nextend;            /* Number of output extensions */
    char        imgname[MAX_FILES][CHAR_FNAME_LENGTH];
    char        fimage[CHAR_FNAME_LENGTH];  /* Name of first image in list */
    char        root[CHAR_FNAME_LENGTH];    /* ROOTNAME for output CRJ file */
    char        uroot[CHAR_FNAME_LENGTH];   /* Upper case version of rootname */
    char        *shadrefname;

    int         ext[MAX_FILES];
    int         dim_x, dim_y;       /* image dimensions */
    int         i, j, n;            /* loop indices */
    float       *efacsum, *work;
    int         nrej;               /* total number of rejected pixels */
    float       skysum;             /* total sky level */
    int         logit;
    RefImage    shadref;
    int         shadswitch;
    double      expend, expstart;
    int         non_zero;           /* number of input images with EXPTIME>0.*/
    int         found;
    char        imgdefault[CHAR_FNAME_LENGTH];  /* name of first input image with EXPTIME > 0. */

    int     GetSwitch (Hdr *, char *, int *);
    int     UpdateSwitch (char *, int, Hdr *, int *);

    void    InitRefImg (RefImage *);
    int     ImgHistory (const RefImage *, Hdr *);
    int     ImgPedigree (RefImage *);

    int     acsrej_check (IRAFPointer, int, int, clpar *, int [],  char [][CHAR_FNAME_LENGTH],
                int [], IODescPtr [], IODescPtr [],
                multiamp *, multiamp *, int *,
                int *, int);
    int     cr_scaling (char *, IRAFPointer, float [], int *, double *, double *);
    int     rejpar_in(clpar *, int [], int, float,   int *, float []);
    void    acsrej_sky (char *, IODescPtr [], IODescPtr [], int, short, float []);
    void    cr_history (SingleGroup *, clpar *, int);
    int     acsrej_init (IODescPtr [], IODescPtr [], clpar *, int, int, int,
                multiamp, multiamp, float [], float [],
                SingleGroup *,   float *);
    int     acsrej_loop (IODescPtr [], IODescPtr [], char [][CHAR_FNAME_LENGTH],
                int [], int, clpar *, int, int, int, float [],
                multiamp, multiamp, float [], float [],
                FloatTwoDArray *, FloatTwoDArray *, float *,
                ShortTwoDArray *, int *, char *);
    int     PutKeyFlt (Hdr *, char *, float, char *);
    int     PutKeyDbl (Hdr *, char *, double, char *);
    int     PutKeyStr (Hdr *, char *, char *, char *);
    int     GetKeyStr (Hdr *, char *, int, char *, char *, int);
    int     PutKeyInt (Hdr *, char *, int, char *);
    int     GetKeyInt (Hdr *, char *, int, int, int *);
    void    UFilename (char *, Hdr *);
    void    UMemType (char *, Hdr *);
    void    UExpname (char *, Hdr *);
    int     LoadHdr (char *, Hdr *);
    void    UpperAll (char *, char *, int);
    void    TimeStamp (char *, char *);
    void    WhichError (int);
    void    PrSwitch (char *, int);
    void    FindAsnRoot (char *, char *);
    void    initmulti (multiamp *);
    /* -------------------------------- begin ---------------------------------- */
    /* Initialize necessary structures */
    InitRefImg (&shadref);
    root[0] = '\0';
    uroot[0] = '\0';
    initmulti (&noise);
    initmulti (&gain);

    numext = 0;
    nextend = 0;


    /* Since CR-SPLIT images are in separate files, we need to
        combine the same chip's exposure from each file.  Therefore
        we will loop over each extension in the first image, determine
        what chip that corresponds to, and get the same chip from the
        rest of the images (which could be in any arbitrary
        extension in each of the images).
    */

    /* First, let's determine how many extensions/chips in each file */
    c_imtgetim (tpin, fimage, CHAR_FNAME_LENGTH);

    if (LoadHdr (fimage, &phdr) )
        return (status = ERROR_RETURN);

    if (GetKeyInt (&phdr, "NEXTEND", NO_DEFAULT, 0, &nextend) == 0)
        numext = nextend / EXT_PER_GROUP;
    else
        numext = 1;

    shadswitch = 0;
    /* Check to see if SHADCORR was set to PERFORM in image header */
    if (GetSwitch (&phdr, "SHADCORR", &shadswitch) )
        return(status);

    /* If shadcorr was set either by the user on the command line
        or in the image header, initialize shadcorr processing.
    */
    if (par->shadcorr == PERFORM || shadswitch == PERFORM) {

        /* Use par->shadcorr as switch for performing shading correction */
        par->shadcorr = PERFORM;
        shadrefname = calloc(CHAR_FNAME_LENGTH, sizeof(char));

        if (GetKeyStr (&phdr, "SHADFILE", NO_DEFAULT, "", shadrefname, CHAR_FNAME_LENGTH) )
            return(status);
        strcpy (shadref.name, shadrefname);
        /* Read in PEDIGREE and DESCRIPTION for SHADFILE */
        if (ImgPedigree (&shadref) )
            return (status);
        /* If a DUMMY shadfile was specified, turn off shadcorr */
        if (shadref.goodPedigree == DUMMY)
            par->shadcorr = OMIT;
        free (shadrefname);
    }

    freeHdr (&phdr);

    /* Initialize efac */
    for (n = 0; n < MAX_FILES; n++) efac[n] = 1.0;

    /* calculate the scaling factors due to different exposure time */
    strcpy (par->expname, "EXPTIME");
    if (cr_scaling (par->expname, tpin, efac, &nimgs, &expend, &expstart) ){
        WhichError (status);
        return (status);
    }

    /* make sure there is more than one image to process */
    if (nimgs < 2) {
        trlmessage ("Needs more than one input image.");
        return (status = NOTHING_TO_DO);
    }

    /* calculate the total exposure time */
    exptot = 0.;
    non_zero = 0;
    for (n = 0; n < nimgs; ++n) {
        exptot += efac[n];
        /* Count how many inputs have non-zero(valid) EXPTIME */
        if (efac[n] > 0.) non_zero++;
    }
    /* for the case of all images have zero exposure time, use equal
        exposure time of 1. */
    if (exptot == 0.) {
        for (n = 0; n < nimgs; ++n) {
            efac[n] = 1.;
        }
        texpt = (float) nimgs;
        non_zero = nimgs;
    } else {
        texpt = exptot;
    }

    /* Now, start the loop. */
    for (extver = 1; extver <= numext; extver++) {

        if (par->printtime) {
            TimeStamp ("Start cosmic ray rejection","");
        }

        /* open input files and temporary files, check the parameters */
        if (acsrej_check (tpin, extver, numext, par, newpar, imgname, ext,
            ipsci, ipdq, &noise, &gain, &dim_x, &dim_y, nimgs)) {
            WhichError (status);
            return(status);
        }

        /* Now that we have read in SHADCORR, report if it will be performed */
        PrSwitch ("shadcorr", par->shadcorr);

        /* read in the parameters */
        if (rejpar_in (par, newpar, nimgs, exptot,   &niter, sigma) )
            return(status);

        /* allocate array space */
        efacsum = calloc (dim_x*dim_y, sizeof(float));
        work    = calloc (nimgs*dim_x, sizeof(float));

        /* calculate the sky levels */
        acsrej_sky (par->sky, ipsci, ipdq, nimgs, par->badinpdq, skyval);
        if (status != ACS_OK) {
            WhichError (status);
            return (status);
        }
        if (par->verbose) {
            for (n = 0; n < nimgs; n++) {
                sprintf (MsgText, "sky of '%s[sci,%d]' is %0.3f DN", imgname[n], ext[n], skyval[n]);
                trlmessage (MsgText);
            }
        }

        /* use the first input image to set up the data structure */
        initSingleGroup (&sg);

        /* Find the first image in the input list which has an
            EXPTIME > 0. to use for initializing the output SingleGroup.
        */
        found = 0;
        n = 0;
        /* By default, simply use the first one, so initialize accordingly.*/
        strcpy (imgdefault, imgname[0]);
        do {
            if (efac[n] > 0.) {
                strcpy(imgdefault,imgname[n]);
                found = 1;
            }
            n++;
        } while (found == 0);

        getSingleGroup (imgdefault, extver, &sg);

        if (non_zero > 1){
            /* compute the initial pixel values to be used to compare against all
               images. */
            if (non_zero < nimgs){
                trlwarn ("Some input exposures had EXPTIME = 0.");
            }

            if (acsrej_init (ipsci, ipdq, par, nimgs, dim_x, dim_y,
                    noise, gain, efac, skyval, &sg, work) ) {
                WhichError(status);
                closeSciDq(nimgs, ipsci, ipdq, par);
                return (status);
            }

            if (par->printtime)
                TimeStamp ("Calculated initial guess for extension", "");

            /* do the iterative cosmic ray rejection calculations */
            if (acsrej_loop (ipsci, ipdq, imgname, ext, nimgs, par, niter, dim_x, dim_y,
                    sigma, noise, gain, efac, skyval,
                    &sg.sci.data, &sg.err.data, efacsum, &sg.dq.data,
                    &nrej, shadref.name) ) {
                WhichError(status);
                closeSciDq(nimgs, ipsci, ipdq, par);
                return (status);
            }
        } else {
            trlwarn ("Cosmic-ray rejection NOT performed!");
            if (non_zero > 0) {
                trlwarn ("Some input exposures had EXPTIME = 0.");
                trlwarn ("Output product will not be cosmic-ray cleaned!");
            } /*else {
                trlwarn ("ALL input exposures had EXPTIME = 0.");
                trlwarn ("Output product will be BLANK!");
            } */
        } /* End if(non_zero) block */


        /* must close all images, now that we are done reading them */
        closeSciDq(nimgs, ipsci, ipdq, par);

        /* calculate the total sky ... */
        skysum = 0.;
        for (n = 0; n < nimgs; ++n) {
            skysum += skyval[n];
        }
        /* ... and force it to be non-negative */
        if (skysum < 0.) skysum = 0.;

        if (par->printtime){
            if (non_zero > 1){
                TimeStamp ("Finished detecting cosmic rays on extension", "");
            } else {
                TimeStamp ("Done checking this extension","");
            }
        }

        /* write to the output image */
        if (non_zero > 0){
            for (j = 0; j < dim_y; ++j) {
                for (i = 0; i < dim_x; ++i) {
                    PPix(&sg.sci.data,i,j) = PPix(&sg.sci.data,i,j)*texpt + skysum;
                    PPix(&sg.err.data,i,j) *= texpt;
                }
            }
        } else {
            for (j = 0; j < dim_y; ++j) {
                for (i = 0; i < dim_x; ++i) {
                    PPix(&sg.sci.data,i,j) = par->fillval;
                    PPix(&sg.err.data,i,j) = 0.;
                    /* Set DQ value to one which will always be considered BAD */
                    PPix(&sg.dq.data,i,j) = 1;
                }
            }
                    /* Set at least one pixel to a different value to insure
                      that an image array actually gets produced. */
                    PPix(&sg.err.data,0,0) = -1.;
                    PPix(&sg.dq.data,0,0) = 8;
        }

        /* update the exposure time of the output images */
        PutKeyFlt (sg.globalhdr, "TEXPTIME", exptot, "");
        PutKeyFlt (sg.globalhdr, "SKYSUM", skysum, "Total sky level (DN)");
        PutKeyDbl (sg.globalhdr, "EXPSTART", expstart, "computed exposure start time (Modified Julian Date)");
        PutKeyDbl (sg.globalhdr, "EXPEND", expend, "exposure end time (Modified Julian Date)");
        /*
            Updated REJ_RATE to use 'texpt' as a safe value when
            EXPTIME=0 for all members. WJH, 24 Feb 2003
        */
        PutKeyFlt (sg.globalhdr, "REJ_RATE", (float)nrej/texpt,
                "Cosmic ray impact rate (pixels/sec)");
        PutKeyFlt (sg.globalhdr, "EXPTIME", exptot, "");
        if (par->shadcorr) {
            logit = 0;
            if (UpdateSwitch ("SHADCORR", par->shadcorr, sg.globalhdr, &logit) )
                return (status);

                PrSwitch ("shadcorr", COMPLETE);

            if (logit) {
                /*Records SHADFILE information in header comments... */
                if (ImgHistory (&shadref, sg.globalhdr))
                    return (status);

            }
        }

        /* record parameters to the output file */
        cr_history (&sg, par, nextend);
        PutKeyInt (&sg.sci.hdr, "NCOMBINE", nimgs, "");
        UFilename (outfile, sg.globalhdr);
        UMemType (mtype, sg.globalhdr);
        FindAsnRoot (outfile, root);
        UpperAll (root, uroot, strlen(root)+1 );
        /*  EXPNAME values modified for all extensions in a SingleGroup.
                   WJH 7 July 1999
        */
        UExpname (root, &sg.sci.hdr);
        UExpname (root, &sg.err.hdr);
        UExpname (root, &sg.dq.hdr);

        PutKeyStr (sg.globalhdr, "ROOTNAME", uroot,"Rootname of the observation set");

        /* Output CHIP to the same EXTVER as the CHIP ID */
        putSingleGroup (outfile, extver, &sg, 0);
        freeSingleGroup (&sg);

        if (par->printtime)
            TimeStamp ("Finished writing out extension", "");

        /* deallocate memories */
        free (efacsum);
        free (work);

    }
    /* Set status to a value which will be understood by
        CALACS to turn off subsequent processing. */
    if (non_zero == 0) status = NO_GOOD_DATA;

    return (status);
}
コード例 #6
0
ファイル: getccdtab.c プロジェクト: jhunkeler/hstcal
int GetCCDTab (ACSInfo *acs, int dimx, int dimy) {

/* arguments:
ACSInfo *acs     io: calibration switches, etc
int     dimx      i: number of columns in exposure
int     dimy      i: number of lines in exposure
*/

	extern int status;

	TblInfo tabinfo;	/* pointer to table descriptor, etc */
	TblRow tabrow;		/* values read from a table row */

	int row;		/* loop index */
	int i;
	char amp[5] = "ABCD";
    int samegain;
	
	int foundit;		/* has the correct row been found? */
	int RowPedigree (RefTab *, int, IRAFPointer, IRAFPointer, IRAFPointer);
	int SameInt (int, int);
	int SameFlt (float, float);
	int SameString (char *, char *);

	/* Open the CCD parameters table and find columns. */
	if (OpenCCDTab (acs->ccdpar.name, &tabinfo))
	    return (status);

	/* Check each row for a match with ccdamp, ccdgain, ccdoffst,
	   binaxis1, and binaxis2, and get info from the matching row.
	*/

	foundit = 0;
	for (row = 1;  row <= tabinfo.nrows;  row++) {

	    /* Read the current row into tabrow. */
	    if (ReadCCDTab (&tabinfo, row, &tabrow))
		return (status);

        /* Commanded gain values were int valued pre-SM4 and 
           float valued post-SM4, so we need to check what type
           of ref table we have as input.
        */
        if (tabinfo.intgain == 1) {
            /* Pre-SM4 int valued table */
            samegain = SameInt (tabrow.ccdgaini, (int)acs->ccdgain);
        } else {
            /* Post-SM4 float valued table */
            samegain = SameFlt (tabrow.ccdgainf, acs->ccdgain);
        }

	    if (SameString (tabrow.ccdamp, acs->ccdamp) &&
		samegain &&
		SameInt (tabrow.ccdchip, acs->chip) &&
		SameInt (tabrow.ccdoffset[0], acs->ccdoffset[0]) &&
		SameInt (tabrow.ccdoffset[1], acs->ccdoffset[1]) &&
		SameInt (tabrow.ccdoffset[2], acs->ccdoffset[2]) &&
		SameInt (tabrow.ccdoffset[3], acs->ccdoffset[3])) {

		foundit = 1;
		if (RowPedigree (&acs->ccdpar, row,
			tabinfo.tp, tabinfo.cp_pedigree, tabinfo.cp_descrip))
		    return (status);
		if (acs->ccdpar.goodPedigree == DUMMY_PEDIGREE) {
		    sprintf (MsgText, "Row %d of CCDTAB is DUMMY.", row);
			trlwarn (MsgText);
		}

		for (i = 0; i < NAMPS; i++){
			/* If the amp is used, keep the value, otherwise set to zero*/
			if (strchr(acs->ccdamp, amp[i]) != NULL) {
				acs->atodgain[i] = tabrow.atodgain[i];
				acs->readnoise[i] = tabrow.readnoise[i];
				acs->ccdbias[i] = tabrow.bias[i];
			} else {
				acs->atodgain[i] = 0.;
				acs->readnoise[i] = 0.;			
				acs->ccdbias[i] = 0.;			
			}
		}

        /* 
            Correct ampx/ampy to match the actual size of the exposure
            This will allow more seamless processing of subarrays.
        */
		acs->ampx = (tabrow.ampx > dimx) ? dimx : tabrow.ampx;
		acs->ampy = tabrow.ampy;		
		acs->saturate = tabrow.saturate;
		break;
	    }
	}

	if (!foundit) {
	    sprintf (MsgText, "Matching row not found in CCDTAB `%s'.", acs->ccdpar.name);
	    trlerror (MsgText);
		sprintf (MsgText, "CCDAMP %s, CCDGAIN %4.1f, CCDOFFST %d,%d,%d,%d.",
		acs->ccdamp, acs->ccdgain, acs->ccdoffset[0], acs->ccdoffset[1],
		acs->ccdoffset[2], acs->ccdoffset[3]);
		trlerror (MsgText);
		
	    CloseCCDTab (&tabinfo);
	    return (status = TABLE_ERROR);
	}

	if (CloseCCDTab (&tabinfo))		/* close the table */
	    return (status);

	return (status);
}
コード例 #7
0
ファイル: calacs.c プロジェクト: jhunkeler/hstcal
int ProcessMAMA (AsnInfo *asn, ACSInfo *acshdr, int printtime) {

    extern int status;

    RefFileInfo sciref;       /* ref file keywords and names */
    CalSwitch sci_sw;         /* all cal switches for science file */
    CalSwitch acsccd_sci_sw;  /* ACSCCD switches for science file */
    CalSwitch acscte_sci_sw;  /* ACSCTE switches for science file */
    CalSwitch acs2d_sci_sw;   /* ACS2D  switches for science file */

    int prod;             /* which CR-split/Rptobs product?    */
    int posid;            /* counter for input products    */
    int expid;            /* counter for input exposures */
    int newpreface = NO;  /* switch for keeping previous comments for
                             all remaining trailer files */

    char *acssum_input;  /* Input list for ACSSUM */
    char acssum_output[CHAR_FNAME_LENGTH+1];
    char acssum_mtype[SZ_STRKWVAL+1];  /* Role of exposure in association */
    char *acssum_msgtext;

    void ACSDefaults (ACSInfo *);
    void InitRefFile (RefFileInfo *);
    void FreeRefFile (RefFileInfo *);
    int ACSRefInit (ACSInfo *, CalSwitch *, RefFileInfo *);
    int ACS2d (char *, char *, CalSwitch *, RefFileInfo *, int, int);
    int AcsSum (char *, char *, char *, int, int);
    char *BuildSumInput (AsnInfo *, int, int);
    int GetAsnMember (AsnInfo *, int, int, int, ACSInfo *);
    int GetSingle (AsnInfo *, ACSInfo *);
    int InsertACSSuffix (ACSInfo *);
    void updateAsnTable (AsnInfo *, int, int);

    if (asn->debug) {
        trlmessage ("CALACS: processing MAMA observations");
    }

    /* Loop over the products/positions for each
       Repeat-Obs or Repeat-Obs/DITHER set.
       PRODID/prod starts at 0, while numprod starts at 1...
    */
    for (prod = 0; prod < asn->numprod; prod++) {

        /* loop over members of a position/product;
           individual CR-SPLIT/Repeat-obs exposures */
        /* Process SINGLE/PARTIAL/FULL product */
        for (posid = 1; posid <= asn->numsp; posid++) {
            if (asn->verbose){
                sprintf (MsgText,"CALACS: processing MAMA posid = %d", posid);
                trlmessage (MsgText);
            }

            for (expid = 1; expid <= asn->spmems[posid]; expid++) {

                /* Read in Member keyword info from --FIRST-- EXP image header */
                if(prod == 0 && posid == 1 && expid == 1) {
                    /* (Re-)Initialize the lists of reference file keywords
                       and names. */
                    InitRefFile (&sciref);

                    /* Assign default values in acs. */
                    ACSDefaults (acshdr);

                   if (asn->process == SINGLE ) {
                       if (GetSingle (asn, acshdr) )
                           return (status);
                   } else {
                       if( GetAsnMember(asn, prod, posid, expid, acshdr))
                           return (status);
                   }

                   /* Initialize variables, and get info (cal switches and
                      reference file names) from primary headers.
                   */
                   if (ACSRefInit (acshdr, &sci_sw, &sciref))
                       return (status);

                   if (asn->verbose) {
                       trlmessage ("CALACS: Got reference file information");
                   }
                   /* Store the trailer file comments into preface */
                   newpreface = YES;

                } else {

                    /* Read in Member keyword info from image header */
                    if (asn->process == SINGLE ) {
                        if (GetSingle (asn, acshdr) )
                            return (status);
                    } else {
                        if( GetAsnMember(asn, prod, posid, expid, acshdr))
                            return (status);
                    }

                    /* Construct output and temporary file names. */
                    if (InsertACSSuffix (acshdr))
                        return (status);
                }

                /* From this point on, we are working with ONE image at a time */

                /* Copy switch values for ACSCCD, ACSCTE, and ACS2D
                   argument lists. */
                SetACSSw (&sci_sw, &acsccd_sci_sw, &acscte_sci_sw, &acs2d_sci_sw);

                /* Ready to process input image now */
                if (acshdr->sci_basic_2d == PERFORM) {

                    /* Copy all messages up to here into preface buffer
                       to be prepended to all input file trailer files */
                    if (newpreface == YES) {
                        InitTrlPreface();
                    }

                    /* Flat field the input MAMA image. */
                    if (ACS2d (acshdr->rawfile, acshdr->fltfile,
                               &acs2d_sci_sw, &sciref, printtime, asn->verbose))
                        return (status);

                } else {

                    /* Copy the input file to fltfile.  We need to do this
                       because ACSSUM needs it for input. */
                    trlwarn ("No processing performed on image.");
                    if (acshdr->sci_rptcorr != PERFORM)
                        status = NOTHING_TO_DO;

                    sprintf (MsgText, "Copying input to %s ",acshdr->fltfile);
                    trlwarn(MsgText);

                    if (CopyFFile (acshdr->rawfile, acshdr->fltfile))
                        return (status);
                }
            }  /* Finished processing EXP images */
        }  /* Finished processing this position's sub-product */
    }  /* Finished looping over all the products */

    /* Reset the trailer file preface to NULL since
       it has already been copied into trailer files */
    ResetTrlPreface();

    /* Done with lists of reference file keywords and names. */
    FreeRefFile (&sciref);

    /* Perform RPTCORR here, as needed. */
    if (acshdr->sci_rptcorr == PERFORM) {
        /* We need to pass a list of input fltfile images for each subproduct
           to be produced, with the subproducts as inputs to DTHCORR. */
        acssum_input = NULL;
        acssum_mtype[0] = '\0';

        trlmessage("Starting RPTCORR now...");

        /* For each DTH product... */
        for (prod = 0; prod < asn->numprod; prod++) {
            /* Loop through all the input subproducts... */
            for (posid = 1; posid <= asn->numsp; posid++) {
                if (asn->spmems[posid] == 0) {
                    continue;
                }
                acssum_input = BuildSumInput (asn, prod, posid);

                strcpy(acssum_output, asn->product[prod].subprod[posid].spname);
                if (asn->verbose) {
                    /* Need to allocate memory for a separate string to be long
                       enough to hold all the input names when printing it
                       out.  Caused pipeline problems otherwise. WJH 19-Mar-04
                    */
                    acssum_msgtext = calloc(strlen(acssum_input)+25, sizeof(char));
                    sprintf (acssum_msgtext, "Input to ASCSUM is: %s",acssum_input);
                    trlmessage(acssum_msgtext);
                    free(acssum_msgtext);

                    sprintf (MsgText, "Output for ASCSUM is: %s",acssum_output);
                    trlmessage(MsgText);
                }

                strcpy(acssum_mtype, asn->product[prod].subprod[posid].mtype);
                if (acssum_mtype[0] == '\0'){
                    strcpy(acssum_mtype, asn->product[prod].mtype);
                }
                trlmessage("ACSSUM starting now...");

                if (AcsSum (acssum_input, acssum_output, acssum_mtype, printtime, asn->verbose)) {
                    return (status);
                }

                /* Pass posid of 0 to indicate a PRODUCT is to be updated */
                updateAsnTable(asn, prod, posid);
            }
        }
        free (acssum_input);
    } /* End RPTCORR Processing */

    return (status);
}
コード例 #8
0
ファイル: getflags.c プロジェクト: brechmos-stsci/hstcal
int GetFlags (CalSwitch *sw, Hdr *phdr) {

/* arguments:
CalSwitch *sw   o: values (0 or 1) of calibration switches
Hdr *phdr       i: primary header
*/

	extern int status;
	FitsKw key;		/* keyword location in header */
    char flashkey[ACS_CBUF];

	int GetKeyInt (Hdr *, char *, int, int, int *);

	if (GetSw (phdr, "ATODCORR", &sw->atodcorr))
	    return (status);
	if (GetSw (phdr, "BIASCORR", &sw->biascorr))
	    return (status);
	if (GetSw (phdr, "BLEVCORR", &sw->blevcorr))
	    return (status);
	if (GetSw (phdr, "CRCORR",   &sw->crcorr))
	    return (status);
	if (GetSw (phdr, "DARKCORR", &sw->darkcorr))
	    return (status);
	if (GetSw (phdr, "DQICORR",  &sw->dqicorr))
	    return (status);
	if (GetSw (phdr, "FLATCORR", &sw->flatcorr))
	    return (status);
//if (GetSw (phdr, "PCTECORR", &sw->pctecorr))
//    return (status);
  if (GetSw (phdr, "PCTECORR", &sw->pctecorr) == HEADER_PROBLEM)
      sw->pctecorr = OMIT;


    sprintf(flashkey,"FLSHCORR");
	key = findKw (phdr, flashkey);
	if (key == NotFound) {
        sprintf(MsgText,"FLSHCORR keyword not found...");
        trlwarn(MsgText);

	    key = findKw (phdr, "POSTFLSH");
        if (key != NotFound) {
            sprintf(flashkey,"POSTFLSH");

            /* Now warn the user to change keyword name to FLSHCORR. */
            sprintf(MsgText,"Using old keyword POSTFLSH!");
            trlwarn(MsgText);
            sprintf(MsgText,"Please rename keyword to FLSHCORR in header.");
            trlwarn(MsgText);
        }
	}

	if (GetSw (phdr, flashkey, &sw->flashcorr))
        return(status);

	if (GetSw (phdr, "GLINCORR", &sw->glincorr))
	    return (status);
	if (GetSw (phdr, "LFLGCORR", &sw->lflgcorr))
	    return (status);
	if (GetSw (phdr, "PHOTCORR", &sw->photcorr))
	    return (status);
	if (GetSw (phdr, "RPTCORR",  &sw->rptcorr))
	    return (status);
	if (GetSw (phdr, "SHADCORR", &sw->shadcorr))
	    return (status);
	if (GetSw (phdr, "EXPSCORR", &sw->expscorr))
	    return (status);

    /* Check to insure that only one of these switches are
        set, since they are exclusive options.
    */
    if (sw->rptcorr == PERFORM && sw->crcorr == PERFORM) {
            trlerror("RPTCORR and CRCORR both set to PERFORM!");
            trlerror("    One switch needs to be set to OMIT!");
            status = HEADER_PROBLEM;
            return (status);
    }
	return (status);
}
コード例 #9
0
ファイル: calacs.c プロジェクト: jhunkeler/hstcal
int ProcessACSCCD (AsnInfo *asn, ACSInfo *acshdr, int *save_tmp, int printtime, const unsigned nThreads, const unsigned cteAlgorithmGen, const char * pcteTabNameFromCmd) {

    extern int status;

    RefFileInfo sciref;       /* ref file keywords and names */
    CalSwitch sci_sw;         /* all cal switches for science file */
    CalSwitch acsccd_sci_sw;  /* ACSCCD switches for science file */
    CalSwitch acscte_sci_sw;  /* ACSCTE switches for science file */
    CalSwitch acs2d_sci_sw;   /* ACS2D switches for science file */
    int save_crj;             /* don't delete crj_tmp file? */

    int prod;             /* which CR-split/Rptobs product? */
    int posid;            /* counter for input products */
    int expid;            /* counter for input exposures */
    int newpreface = NO;  /* switch for keeping previous comments for
                             all remaining trailer files */

    char *acsrej_input;     /* list of input names for ACSREJ */
    char *acsrejc_input;    /* list of CTE corrected input names for ACSREJ */
    char *acsrej_msgtext;   /* str for list of input filenames */
    char *acsrejc_msgtext;  /* str for list of CTE corrected input filenames */
    int nchars;             /* Number of chars for input string to ACSREJ */

    void ACSDefaults (ACSInfo *);
    void InitRefFile (RefFileInfo *);
    void FreeRefFile (RefFileInfo *);
    int ACSRefInit (ACSInfo *, CalSwitch *, RefFileInfo *);
    int ACSccd (char *, char *, CalSwitch *, RefFileInfo *, int, int);
    int ACScte (char *, char *, CalSwitch *, RefFileInfo *, int, int, int, const unsigned cteAlgorithmGen, const char * pcteTabNameFromCmd, const bool forwardModelOnly);
    int ACS2d (char *, char *,CalSwitch *, RefFileInfo *, int, int);
    int GetAsnMember (AsnInfo *, int, int, int, ACSInfo *);
    int GetSingle (AsnInfo *, ACSInfo *);
    int CheckCorr (AsnInfo *, ACSInfo *);
    int InsertACSSuffix (ACSInfo *);

    save_crj = *save_tmp;  /* initial value; */

    /* Loop over the products/positions for each CR-split/Repeat-Obs set. */
    for (prod = 0; prod < asn->numprod; prod++) {
        if (asn->verbose){
            sprintf (MsgText, "CALACS: processing CCD product %d", prod);
            trlmessage (MsgText);
        }

        /* Process this PARTIAL/SINGLE/FULL product... */
        for (posid = 1; posid <= asn->numsp; posid++) {

            if (asn->verbose) {
                sprintf (MsgText,"CALACS: processing posid = %d", posid);
                trlmessage (MsgText);
            }
            /*  Allocate space for ACSREJ input image list */
            if ( (asn->crcorr == PERFORM) || (asn->rptcorr == PERFORM) ) {
                nchars = asn->spmems[posid] * CHAR_FNAME_LENGTH;
                acsrej_input = (char *) calloc( nchars + 1, sizeof(char));
                /* Initialize this string to NULL */
                acsrej_input[0] = '\0';

                acsrejc_input = (char *) calloc( nchars + 1, sizeof(char));
                /* Initialize this string to NULL */
                acsrejc_input[0] = '\0';
            }

            /* Run ACSCCD on individual EXPosures. */
            for (expid = 1; expid <= asn->spmems[posid]; expid++) {
                /* From this point on, we are working with ONE image at a time */

                /* Read in Member keyword info from --FIRST-- EXP image header */
                /*if(prod == 0 && posid == 1 && expid == 1) { */
                if(expid == 1) {
                    /* (Re-)Initialize the lists of reference file keywords
                       and names. */
                    InitRefFile (&sciref);

                    /* Assign default values in acs. */
                    ACSDefaults (acshdr);

                    if (asn->process == SINGLE ) {
                        if (GetSingle (asn, acshdr) )
                            return (status);
                    } else {
                        if( GetAsnMember(asn, prod, posid, expid, acshdr))
                            return (status);
                    }
                    /* Initialize variables, and get info (cal switches and
                       reference file names) from primary headers.
                    */
                    if (ACSRefInit (acshdr, &sci_sw, &sciref))
                        return (status);

                    /* Make sure 'save_tmp' and 'save_crj' are no
                       longer set to 'DUMMY'.

                       If save_tmp was set from the command-line, then
                       ignore what is set in the header keyword
                       EXPSCORR.
                    */
                    if (*save_tmp == DUMMY) {
                        *save_tmp = NO;
                        save_crj = *save_tmp;
                    }

                    if (asn->verbose) {
                        trlmessage ("CALACS: Got reference file information");
                    }
                    /* Store the trailer file comments into preface */
                    newpreface = YES;

                } else {

                    if (asn->process == SINGLE ) {
                        if (GetSingle (asn, acshdr))
                            return (status);
                    } else {
                        if( GetAsnMember(asn, prod, posid, expid, acshdr))
                            return (status);
                    }

                    /* Construct output and temporary file names. */
                    if (InsertACSSuffix (acshdr))
                        return (status);
                }

                /* Check ASN table settings for CRCORR/RPTCORR
                   against image header values.  If they are not
                   consistent, print out a ERROR message and quit.
                   Only need to perform this check on the first image
                   in the association. WJH 21 May 1999
                */
                if (prod == 0 && posid == 1 && expid == 1) {
                    if (CheckCorr(asn, acshdr))
                        return (status);
                }

                /* Copy switch values for ACSCCD, ACSCTE, and ACS2D
                   argument lists. */
                SetACSSw(&sci_sw, &acsccd_sci_sw, &acscte_sci_sw, &acs2d_sci_sw);

                if (asn->verbose) {
                    trlmessage ("CALACS: Processing switches set... ");
                }

                /* Ready to process input image now... */
                /* Do we have anything to do with this image? */
                if (acshdr->sci_basic_2d != PERFORM &&
                        acshdr->sci_basic_ccd != PERFORM &&
                        acshdr->sci_basic_cte != PERFORM &&
                        acshdr->sci_crcorr != PERFORM &&
                        acshdr->sci_rptcorr != PERFORM ){
                    trlwarn ("No calibration switch was set to PERFORM.");
                    FreeRefFile (&sciref);
                    return (status = NOTHING_TO_DO);
                }

                /* First, initialize the Input CCD image with ACSCCD.
                   Then, perform PCTECORR if needed.
                   Then, either do cosmic ray rejection followed by ACS2D,
                   or just run ACS2D. */

                /* First do atodcorr, dqicorr, and blevcorr
                   (or copy the name). */
                if (acshdr->sci_basic_ccd == PERFORM) {
                    /* This is acsccd; note that we use acsccd_sci_sw. */

                    /* Copy all messages up to here into preface buffer
                       to be prepended to all input file trailer files */
                    if (newpreface == YES) {
                        InitTrlPreface();
                    }

                    SetTrlPrefaceMode (YES);

                    if (ACSccd (acshdr->rawfile, acshdr->blv_tmp,
                                &acsccd_sci_sw, &sciref, printtime,
                                asn->verbose))
                        return (status);

                    /* Reset switches */
                    ResetACSSw (&acsccd_sci_sw, &acs2d_sci_sw);

                } else {
                    /* Copy the input file to blv_tmp. We need to do this
                       because acsrej may (depending on the crmask column
                       in the crrejtab) modify the DQ flags in its input file.
                    */
                    if (CopyFFile (acshdr->rawfile, acshdr->blv_tmp))
                        return (status);
                }

                /* Do PCTECORR now. */
                if (acshdr->sci_basic_cte == PERFORM) {
                    // ``forwardModelOnly = false`` because it is not part of the pipeline processing.
                    if (ACScte(acshdr->blv_tmp, acshdr->blc_tmp,
                               &acscte_sci_sw, &sciref, printtime,
                               asn->verbose, nThreads, cteAlgorithmGen, pcteTabNameFromCmd, false)) {
                        return (status);
                    }
                }

                /* We now are working with blv_tmp here... */
                /* Copy (cat) blv_tmp name to acsrej_input string */
                if ( (acshdr->sci_crcorr == PERFORM) ||
                     (acshdr->sci_rptcorr == PERFORM) ) {
                    strcat(acsrej_input, acshdr->blv_tmp);
                    if (expid < asn->spmems[posid]) {
                        /* Don't add a comma to the end of the last filename*/
                        strcat(acsrej_input, ",");
                    }
                    /* Also, add blv_tmp to list of files to be deleted */
                    strcpy(asn->product[prod].subprod[posid].exp[expid].blv_tmp,
                           acshdr->blv_tmp);

                    /* do this again for CTE corrected exposures */
                    if (acscte_sci_sw.pctecorr == PERFORM) {
                        strcat(acsrejc_input, acshdr->blc_tmp);
                        if (expid < asn->spmems[posid]) {
                            /* Don't add a comma to the end of the last filename*/
                            strcat(acsrejc_input, ",");
                        }
                        /* Also, add blc_tmp to list of files to be deleted */
                        strcpy(asn->product[prod].subprod[posid].exp[expid].blc_tmp, acshdr->blc_tmp);
                    }
                }
            }  /* end loop of individual EXPosures for running ACSCCD */

            /* Cosmic ray rejection, followed by basic 2-D processing
               of _crj_tmp. */
            if ( (acshdr->sci_crcorr == PERFORM) ||
                 (acshdr->sci_rptcorr == PERFORM) ) {
                if (asn->verbose) {
                    sprintf (MsgText,"CALACS: Now process position %d from product %d", posid, prod);
                    trlmessage (MsgText);
                }

                /* Commented out, not sure why these need to be reset.
                   Everything should have correct settings after ACSCCD.
                   MRD 17-May-2011 */
                /* Copy switch values for ACSCCD, ACSCTE, and ACS2D
                   argument lists. */
                /*SetACSSw (&sci_sw, &acsccd_sci_sw, &acscte_sci_sw, &acs2d_sci_sw); */
                /* Reset DQICORR, since it will already have been done...
                   WJH  23-Apr-2002 */
                /*acs2d_sci_sw.dqicorr = COMPLETE; */

                if (asn->debug){
                    sprintf(MsgText,"Non-CTE corrected Input to ACSREJ is:");
                    trlmessage(MsgText);

                    /* Need to allocate memory for a separate string to be
                       long enough to hold all the input names when printing
                       it out. Caused pipeline problems otherwise.
                       WJH 19-Mar-04 */
                    acsrej_msgtext = calloc(strlen(acsrej_input)+25,
                                            sizeof(char));
                    sprintf (acsrej_msgtext, "%s", acsrej_input);
                    trlmessage(acsrej_msgtext);
                    free(acsrej_msgtext);

                    sprintf(MsgText,"Non-CTE corrected Output to ACSREJ is: %s", acshdr->crj_tmp);
                    trlmessage(MsgText);

                    if (acscte_sci_sw.pctecorr == PERFORM) {
                        sprintf(MsgText,"CTE corrected Input to ACSREJ is:");
                        trlmessage(MsgText);

                        /* Need to allocate memory for a separate string to be
                           long enough to hold all the input names when printing
                           it out. Caused pipeline problems otherwise.
                           WJH 19-Mar-04 */
                        acsrejc_msgtext = calloc(strlen(acsrejc_input)+25, sizeof(char));
                        sprintf (acsrejc_msgtext, "%s",acsrejc_input);
                        trlmessage(acsrejc_msgtext);
                        free(acsrejc_msgtext);

                        sprintf(MsgText,"CTE corrected Output to ACSREJ is: %s", acshdr->crc_tmp);
                        trlmessage(MsgText);
                    }
                }

                /* Set up the correct value of ASN_MTYP for ACSREJ
                   output image. */
                if ( strncmp(acshdr->asn_table, acshdr->crj_tmp, 9) ) {
                    /* crj_tmp is a sub-product */
                    strcpy (acshdr->mtype, asn->product[prod].subprod[posid].mtype);
                } else {
                    /* crj_tmp leads to a product with same rootname as asn_table */
                    strcpy (acshdr->mtype, asn->product[prod].mtype);
                }

                // Reject cosmic rays.
                int pctecorrSwitchState = acscte_sci_sw.pctecorr;
                if (!OmitStep(pctecorrSwitchState))
                {
                    // Temporarily set this to OMIT so that ACS2d, called within
                    // the ACSRej_oWrapper call stack, uses the non-CTE darks.
                    // This is not thread safe.
                    acs2d_sci_sw.pctecorr = OMIT;
                }
                if ((status = ACSRej_0Wrapper(acsrej_input,
                        acshdr->crj_tmp,
                        acshdr->crjfile,
                        asn->product[prod].subprod[posid].crj_tmp,
                        acshdr,
                        asn,
                        prod,
                        posid,
                        &acs2d_sci_sw,
                        &sciref,
                        printtime,
                        save_crj,
                        True)))
                {
                    //freeStuff
                    delete((void**)&acsrej_input);
                    return status;
                }
                if (!OmitStep(pctecorrSwitchState))
                    acs2d_sci_sw.pctecorr = pctecorrSwitchState;
                delete((void**)&acsrej_input);



                /* now repeat the same thing with CTE corrected products */
                if (!OmitStep(acscte_sci_sw.pctecorr))
                {
                    if ((status = ACSRej_0Wrapper(acsrejc_input,
                            acshdr->crc_tmp,
                            acshdr->crcfile,
                            asn->product[prod].subprod[posid].crc_tmp,
                            acshdr,
                            asn,
                            prod,
                            posid,
                            &acs2d_sci_sw,
                            &sciref,
                            printtime,
                            save_crj,
                            False)))
                    {
                        //freeStuff
                        delete((void**)&acsrejc_input);
                        return status;
                    }
                }
                delete((void**)&acsrejc_input);
            }  /* End of CRCORR processing */

            if (asn->debug){
                trlmessage("Run ACS2D for CCD next...");
            }

            /* Run ACS2D on individual EXPosures. */
            for (expid = 1; expid <= asn->spmems[posid]; expid++) {
                /* From this point on, we are working with ONE image
                   at a time... */

                /* load acs file info */
                if (asn->process == SINGLE ) {
                    if (GetSingle (asn, acshdr) )
                        return (status);
                } else {
                    if( GetAsnMember(asn, prod, posid, expid, acshdr))
                        return (status);
                }

                /* Construct output and temporary file names. */
                if (InsertACSSuffix (acshdr))
                    return (status);

                /* If we are not performing CRCORR or RPTCORR or
                   EXPSCORR is set to PERFORM, then finish
                   processing individual EXP files with ACS2D...
                */
                if ( (acshdr->sci_crcorr != PERFORM) ||
                     (acshdr->sci_rptcorr != PERFORM) ||
                     (sci_sw.expscorr == PERFORM) ) {
                    if (asn->debug) {
                        trlmessage("CRCORR not set to Perform or EXPSCORR turned on...");
                    }

                    if (acshdr->sci_basic_2d == PERFORM) {
                        SetTrlPrefaceMode (NO);
                        if (asn->copy_input == PERFORM) {
                            if (CopyFFile (acshdr->fltfile, acshdr->blv_tmp))
                                return (status);
                            remove (acshdr->fltfile);
                        }

                        /* Basic 2-D processing (flat field, etc). */
                        /* temporarily set acs2d_sci_sw.pctecorr to omit so the
                           correct acs2d processing is done */
                        if (acs2d_sci_sw.pctecorr == PERFORM) {
                            acs2d_sci_sw.pctecorr = OMIT;

                            if (ACS2d (acshdr->blv_tmp, acshdr->fltfile,
                                       &acs2d_sci_sw, &sciref, printtime,
                                       asn->verbose))
                                return (status);

                            acs2d_sci_sw.pctecorr = PERFORM;
                        } else {
                            if (ACS2d (acshdr->blv_tmp, acshdr->fltfile,
                                       &acs2d_sci_sw, &sciref, printtime,
                                       asn->verbose))
                                return (status);
                        }

                    } else {
                        /* If we are not performing CRCORR, then copy
                           blv_tmp file into a final _flt file. */
                        if (acshdr->sci_crcorr != PERFORM ||
                            acshdr->sci_rptcorr != PERFORM) {
                            if (CopyFFile (acshdr->blv_tmp, acshdr->fltfile))
                                return (status);
                        }
                    }

                    /* now repeat ACS2D processing for CTE products */
                    if (acshdr->sci_basic_2d == PERFORM &&
                            acscte_sci_sw.pctecorr == PERFORM) {
                        if (asn->copy_input == PERFORM) {
                            if (CopyFFile (acshdr->flcfile, acshdr->blc_tmp))
                                return (status);
                            remove (acshdr->flcfile);
                        }

                        /* Basic 2-D processing (flat field, etc). */
                        if (ACS2d (acshdr->blc_tmp, acshdr->flcfile,
                                   &acs2d_sci_sw, &sciref, printtime,
                                   asn->verbose))
                            return (status);
                    } else if (acscte_sci_sw.pctecorr == PERFORM) {
                        /* If we are not performing CRCORR, then copy
                           blc_tmp file into a final _flc file. */
                        if (acshdr->sci_crcorr != PERFORM ||
                            acshdr->sci_rptcorr != PERFORM) {
                            if (CopyFFile (acshdr->blc_tmp, acshdr->flcfile))
                                return (status);
                        }
                    }

                }  /* Finished processing blv_tmp file through ACS2D */

                /* Now, delete _blv_tmp and _blc_tmp files */
                if (*save_tmp != YES) {
                    remove (acshdr->blv_tmp);
                    if (acscte_sci_sw.pctecorr == PERFORM) {
                        remove (acshdr->blc_tmp);
                    }
                }
            }  /* End loop over ind EXP for making _flt and _flc files. */

            /* Reset the trailer file preface to NULL since
               it has already been copied into trailer files */
            ResetTrlPreface();

        }  /* End of processing for SINGLE/PARTIAL product */
    }  /* End loop over CCD products here... */

    /* Done with lists of reference file keywords and names. */
    FreeRefFile (&sciref);

    return (status);
}
コード例 #10
0
ファイル: findover.c プロジェクト: brechmos-stsci/hstcal
int FindOverscan (ACSInfo *acs, int nx, int ny, int *overscan) {

/* arguments:
ACSInfo *acs		  i: structure with all values from OSCNTAB 
int nx, ny            i: lengths of first and second image axes
int offsetx, offsety  i: Trim values from LTV1,2
*/

	extern int status;
	int row;
	TblInfo tabinfo;
	TblRow tabrow;
	int foundit;
    
    int cx0, cx1, tx1,tx2;
    int full_nx;

	int SameInt (int, int);
	int SameString (char *, char *);

	/* Open the CCD parameters table and find columns. */
	if (OpenOverTab (acs->oscn.name, &tabinfo))
	    return (status);

	/* Check each row for a match with ccdamp, chip, nx, ny,
	   binx, and biny, and get info from the matching row.
	*/

	foundit = NO;
    *overscan = NO;
	
	for (row = 1;  row <= tabinfo.nrows;  row++) {

	    /* Read the current row into tabrow. */
	    if (ReadOverTab (&tabinfo, row, &tabrow))
		return (status);

	    if (SameString (tabrow.ccdamp, acs->ccdamp) &&
		SameInt (tabrow.chip, acs->chip) &&
        /* The overscan regions only depend on the full chip size...
		SameInt (tabrow.nx, nx) &&
		SameInt (tabrow.ny, ny) &&
		*/
        SameInt (tabrow.bin[0], acs->bin[0]) &&
		SameInt (tabrow.bin[1], acs->bin[1])) {

			foundit = YES;
            *overscan = YES;
                        
            if (acs->subarray == YES) {
                /* We are working with a subarray... */
                /* There is never any virtual overscan. */
                acs->trimy[0] = 0;
                acs->trimy[1] = 0;
			    acs->vx[0] = 0;
			    acs->vx[1] = 0;
			    acs->vy[0] = 0;
			    acs->vy[1] = 0;
                /* Determine whether the subarray extends into the
                    physical overscan regions on either side of the chip */
                tx1 = (int)(nx - acs->offsetx);
                cx1 = tabrow.nx - tabrow.trimx[1] - tabrow.trimx[0];
                cx0 = (int)(tabrow.trimx[0] - acs->offsetx);
                
                if (acs->offsetx > 0) {
                    /* Subarray starts in the first overscan region... */
                    acs->trimx[0] = (acs->offsetx < tabrow.trimx[0])? acs->offsetx : tabrow.trimx[0];
                    /* Check to see if it extends into second overscan region...
                        Fixed 24 July 2001 WJH.
                    */
                    full_nx = tabrow.nx - (tabrow.trimx[0] + tabrow.trimx[1]);
                    tx2 = (int)(nx - acs->trimx[0]) - full_nx;
                    acs->trimx[1] = (tx2 < 0) ? 0 : tx2;
                    acs->biassecta[0] = (tabrow.biassecta[0] - 1 - cx0 > 0) ? (tabrow.biassecta[0] - 1 - cx0) : 0;
                    acs->biassecta[1] = tabrow.biassecta[1] - 1 - cx0;
                    acs->biassectb[0] = 0;
                    acs->biassectb[1] = 0;
                } else if ( tx1 > cx1 && tx1 <= tabrow.nx) {
                    /* ... then the subarray overlaps biassectb... */
                    acs->trimx[0] = 0;
                    acs->trimx[1] = tx1 - cx1;
                    acs->biassecta[0] = 0;
                    acs->biassecta[1] = 0;
                    acs->biassectb[0] = nx - (tx1 - cx1);
                    acs->biassectb[1] = nx - 1;
                     
                } else {
                    /* Subarray doesn't overlap either physical overscan region */
                    acs->trimx[0] = 0;
                    acs->trimx[1] = 0;
                    acs->biassecta[0] = 0;
                    acs->biassecta[1] = 0;
                    acs->biassectb[0] = 0;
                    acs->biassectb[1] = 0;                               
                    *overscan = NO;             
                }
            } else {
                /* We are working with a full chip image... */		
			    acs->trimx[0] = tabrow.trimx[0];
			    acs->trimx[1] = tabrow.trimx[1];
			    acs->trimy[0] = tabrow.trimy[0];
			    acs->trimy[1] = tabrow.trimy[1];
                /* Subtract one from table values to
				    conform to C array indexing... */
			    acs->vx[0] = tabrow.vx[0]-1;
			    acs->vx[1] = tabrow.vx[1]-1;
			    acs->vy[0] = tabrow.vy[0]-1;
			    acs->vy[1] = tabrow.vy[1]-1;
			    acs->biassecta[0] = tabrow.biassecta[0] - 1;
			    acs->biassecta[1] = tabrow.biassecta[1] - 1;
			    acs->biassectb[0] = tabrow.biassectb[0] - 1;
			    acs->biassectb[1] = tabrow.biassectb[1] - 1;
			}

			break;
	    }
	}
	if (foundit == NO) {
		status = ROW_NOT_FOUND;
		sprintf(MsgText, "Could not find appropriate row from OSCNTAB. ");
		trlwarn(MsgText);
	}	
	if(CloseOverTab (&tabinfo))
		return(status);
	
    if (acs->verbose == YES){
        sprintf(MsgText,"Found trim values of: x(%d,%d) y(%d,%d)",acs->trimx[0],acs->trimx[1],acs->trimy[0],acs->trimy[1]);
        trlmessage(MsgText);
    }
    
	return (status);
}
コード例 #11
0
ファイル: dostat.c プロジェクト: jhunkeler/hstcal
int doStat (SingleGroup *out, short sdqflags) {

/* arguments:
SingleGroup *out  io: image to be calibrated; the headers are modified
short sdqflags     i: "serious" data quality flags
*/

	extern int status;

	double value;			/* current data value */
	double valsum, valmin, valmax;
	double stddev;			/* current error estimate */
	double errsum, errmin, errmax;
	double snr;			/* current signal-to-noise ratio */
	double snrsum, snrmin, snrmax;
	int numgood;			/* number of good pixels */
	int num_bad_stddev;		/* number of pixels with err = 0 */
	int area;			/* total number of pixels */
	int i, j;
	int dimx, dimy;
    
	short flagval;			/* data quality flag value */
	int PutKeyFlt (Hdr *, char *, float, char *);
	int PutKeyInt (Hdr *, char *, int, char *);

	/* Statistics for the science data. */
	numgood = 0;
    valmin=0.0f;
    valmax=0.0f;
    errmin=0.0f;
    errmax=0.0f;
    snrmin=0.0f;
    snrmax=0.0f;
    
	num_bad_stddev = 0;
	valsum = 0.;
	errsum = 0.;
	snrsum = 0.;
	dimx = out->sci.data.nx;
	dimy = out->sci.data.ny;

	for (j = 0;  j < dimy;  j++) {
	     for (i = 0;  i < dimx;  i++) {
		  flagval = DQPix (out->dq.data, i, j);

		  if (!(sdqflags & flagval)) {

		      /* no serious flag bit set */
		      value = Pix (out->sci.data, i, j);
		      stddev = Pix (out->err.data, i, j);
		      if (stddev <= 0.) {
			  num_bad_stddev++;
			  continue;		/* bad error value */
		      } else {
			  snr = value / stddev;
		      }
		      if (numgood < 1) {
			  valsum = value;
			  valmin = value;
			  valmax = value;
			  errsum = stddev;
			  errmin = stddev;
			  errmax = stddev;
			  snrsum = snr;
			  snrmin = snr;
			  snrmax = snr;
			  numgood = 1;
		      } else {
			  valsum += value;
			  errsum += stddev;
			  snrsum += snr;
			  if (value < valmin)
			      valmin = value;
			  if (value > valmax)
			      valmax = value;
			  if (stddev < errmin)
			      errmin = stddev;
			  if (stddev > errmax)
			      errmax = stddev;
			  if (snr < snrmin)
			      snrmin = snr;
			  if (snr > snrmax)
			      snrmax = snr;
			  numgood++;
		      }
		  }
	     }
	}

	if (numgood > 0) {
	    valsum /= (double) numgood;
	    errsum /= (double) numgood;
	    snrsum /= (double) numgood;
	} else {
	    area = dimy * dimx;
	    if (area == 0) {
		trlwarn ("Output image size is zero.");
	    } else if (num_bad_stddev > 0) {
		if (num_bad_stddev == area) {
		    trlwarn ("No ERR values > 0.");
		} else {
		    trlwarn 
		       ("All output pixels either flagged as bad or ERR <= 0.");
		}
	    } else {
		trlwarn ("All output pixels flagged as bad.");
	    }
	    PutKeyInt (&out->sci.hdr, "NGOODPIX", numgood, "");
	    PutKeyInt (&out->err.hdr, "NGOODPIX", numgood, "");
	    return (status);
	}

	/* Update header values for the science array. */

	if (PutKeyInt (&out->sci.hdr, "NGOODPIX", numgood,
			"number of good pixels"))
	    return (status);

	if (PutKeyFlt (&out->sci.hdr, "GOODMIN", (float) valmin,
			"minimum good data value"))
	    return (status);

	if (PutKeyFlt (&out->sci.hdr, "GOODMAX", (float) valmax,
			"maximum good data value"))
	    return (status);

	if (PutKeyFlt (&out->sci.hdr, "GOODMEAN", (float) valsum,
			"average of good data values"))
	    return (status);

	if (PutKeyFlt (&out->sci.hdr, "SNRMIN", (float) snrmin,
			"minimum S/N of good data values"))
	    return (status);

	if (PutKeyFlt (&out->sci.hdr, "SNRMAX", (float) snrmax,
			"maximum S/N of good data values"))
	    return (status);

	if (PutKeyFlt (&out->sci.hdr, "SNRMEAN", (float) snrsum,
			"mean S/N of good data values"))
	    return (status);

	/* Update header values for the error array. */

	if (PutKeyInt (&out->err.hdr, "NGOODPIX", numgood,
			"number of good pixels"))
	    return (status);

	if (PutKeyFlt (&out->err.hdr, "GOODMIN", (float) errmin,
			"minimum sigma for good data"))
	    return (status);

	if (PutKeyFlt (&out->err.hdr, "GOODMAX", (float) errmax,
			"maximum sigma for good data"))
	    return (status);

	if (PutKeyFlt (&out->err.hdr, "GOODMEAN", (float) errsum,
			"average of sigma for good data"))
	    return (status);

	return (status);
}
コード例 #12
0
ファイル: blevdrift.c プロジェクト: jhunkeler/hstcal
int BlevDrift (SingleGroup *in, int *vx, int *vy, int trimx1, int *biassect,
	       int *driftcorr, short sdqflags, float rn) {

/* arguments:
SingleGroup *in      i: image to be calibrated
int vx[2], vy[2]     i: range of pixel numbers for virtual overscan region
int trimx1           i: width to trim off beginning of line
int biassect[4]      i: section to use for finding bias level
int *driftcorr       i: true if correction can be applied
float rn             i: readnoise (units of DN)
*/

	extern int status;
	double *scratch;
	double value;		/* median of values in column */
	double zerocol;		/* zero point for fit */
	int midcol;		/* middle column of overscan region */
	int i;			/* X pixel in input image */
	double *biasvals;	/* intermediate array for bias level values */
	int    *biasmask;	/* mask array for biasvals:0 means don't use */
	char nodriftcorr[] =
		{"No correction for slope will be applied."};

	*driftcorr = 0;		/* initial value */

	if (vx[1] <= vx[0] || vy[1] <= vy[0]) {
	    trlmessage ("(blevcorr) No virtual overscan region;");
	    trlmessage (nodriftcorr);
	    DriftSet (0.);
	    return (status);
	}

	/* Allocate space for temporary arrays */
	if ((scratch = malloc ((vy[1]-vy[0]+1) * sizeof (double))) == NULL) {
	    trlwarn ("Out of memory in BlevDrift.");
	    return (status = OUT_OF_MEMORY);
	}
	biasvals = (double *) calloc (vx[1]+1, sizeof(double));
	biasmask = (int *) calloc (vx[1]+1, sizeof(int));

	/* Initialize for fitting.  The first argument is the middle of
	   the section used for determining the bias level, in units of
	   pixel number in the input, untrimmed, image.
	*/
	
	/* HAB 1-Mar-2002: Modified zerocol computation so that it is
	** pixel units of the input, untrimmed image, rather than the
	** STIS approach of pixel units in the output, trimmed image. */
	/*zerocol = (double) (biassect[0] + biassect[1]) / 2. - trimx1;*/
	zerocol = (double) (biassect[0] + biassect[1]) / 2.;
	midcol = (vx[0] + vx[1]) / 2;
	DriftInit (zerocol, midcol);

	/* For each column, determine the value of the virtual overscan,
	** and accumulate sums. */
	for (i = vx[0];  i <= vx[1];  i++) {

	    /* Compute median of column */
	    if (VMedianY (in, i, vy, sdqflags, &value, scratch))
		continue;
	    biasvals[i] = value;
	    biasmask[i] = 1;
	}

	/* Analyze biasvals for outliers and mask them by setting the
	** corresponding value in the biasmask array to zero. */
	cleanDriftFit (biasvals, biasmask, vx, rn);

	/* Now that we have read in all bias level values from the overscan
	** regions and thrown out any outliers (cosmic-ray hits), we can
	** accumulate the fitting statistics now. */
	for (i = vx[0];  i <= vx[1];  i++) {
	     if (biasmask[i] == 1)
		 DriftAccum (i, biasvals[i]);
	}

	/* Fit a curve to the values found. */
	if (DriftFit()) {
	    trlwarn ("(blevcorr) Singular fit to virtual overscan; ");
	    trlwarn (nodriftcorr);
	    DriftSet (0.);
	} else {
	    *driftcorr = 1;
	}

	/* Free up local memory */
	free (scratch);
	free (biasvals);
	free (biasmask);

	return (status);
}
コード例 #13
0
ファイル: donoise.c プロジェクト: jhunkeler/hstcal
int doNoise (WF3Info *wf3, SingleGroup *x, int *done) {

/* arguments:
WF3Info *wf3	 i: calibration switches and info
SingleGroup *x	io: image to be calibrated; written to in-place
int *done        o: true if we actually did assign error array values
*/

	extern int status;

	float bias;		/* bias level to subtract (dn) */
	float rn2[NAMPS];       /* square of noise values for observation */
	float gain[NAMPS];	/* gain values for observation */
	float value;		/* dn - bias * gain (i.e. signal in el) */
	int i, j;
	int ampx;		/* border column for 2amp readout regions */
	int ampy;		/* Boundary values corrected for trim regions */
	int dimx, dimy;
	int offsetx, offsety;
	float ccdbias[NAMPS];	/* default ccdbias values for chip */

	void get_nsegn (int, int, int, int, float *, float*, float *, float *);

	*done = 0;				/* initial value */
	
	/* First check for a dummy error array.  If it's not dummy,
	** we just return without doing anything.  */
	dimx = x->err.data.nx;
	dimy = x->err.data.ny;
	for (j = 0;  j < dimy;  j++) {
	    for (i = 0;  i < dimx;  i++) {
		    if (Pix (x->err.data, i, j) != 0.) {
		        return (status);	/* not a dummy error array */
		    }
	    }
	}

    if (wf3->detector != IR_DETECTOR) { 

        /* CCD initialization */
        offsetx = (int)(wf3->offsetx > 0) ? wf3->offsetx : 0;
        offsety = (int)(wf3->offsety > 0) ? wf3->offsety : 0;

	/* Correct the AMP readout boundaries for this offset */
	ampx = ((wf3->ampx == 0) ? 0 : (int)(wf3->ampx + offsetx) );
	ampy = ((wf3->ampy == 0) ? 0 : (int)(wf3->ampy + offsety) );
	ampx += wf3->trimx[2];

	/* Bounds checking to make sure we don't try to apply gain
	** and noise outside the bounds of the image.
	** This would apply if using only 1 AMP on each WFC chip when
	** ampx is given in CCDTAB as something greater than the
	** image size.
	** WJH 8 Sept 2000 (HAB 8 May 2001)
	**
	** We need to make sure that if the ampx value extends into the
	** overscan at the end of the line, ampx gets automatically 
	** moved to cover the whole line. This allows all AMPX and AMPY
	** values to be specified in CCDTAB in trimmed coordinates.
	** WJH 27 Oct 2000 (HAB 8 May 2001)
	*/

	/*if (ampx >= (dimx - wf3->offsetx) || ampx > dimx ) ampx = dimx;*/
	if (ampx >= (dimx - wf3->trimx[1]) || ampx > dimx ) ampx = dimx;
	if (ampy >= (dimy - wf3->offsety) || ampy > dimy ) ampy = dimy;

        /* Set up gain and readnoise arrays for use with chip's data */
        for (i=0; i < NAMPS; i++) {
            gain[i] = 0.;
            rn2[i] = 0.;
        }
        get_nsegn (wf3->detector, wf3->chip, wf3->ampx, wf3->ampy,
		   wf3->atodgain, wf3->readnoise, gain, rn2);

	/* For WFC3 UVIS data, AMPY will always be zero, yet we still need
	** to select the correct ccdbias value to apply. Determine
	** that here. */
	if (wf3->detector == CCD_DETECTOR && wf3->chip == 2) {
	    ccdbias[0] = wf3->ccdbias[2];
	    ccdbias[1] = wf3->ccdbias[3];
	    ccdbias[2] = wf3->ccdbias[2];
	    ccdbias[3] = wf3->ccdbias[3];
	} else {
	    for (i=0; i < NAMPS; i++) ccdbias[i] = wf3->ccdbias[i];
	}

        /* Now square the readnoise */
        for (i = 0; i < NAMPS; i++)
	     rn2[i] = rn2[i] * rn2[i];
        
	if (wf3->ncombine > 1) {
	    trlwarn("NCOMBINE > 1 before the error array was initialized.");
	}

        /* Now apply the initilalization for each AMP used */
        for (j = 0; j < ampy; j++) {
        
            /* This region corresponds to AMP_C, 
                if it is even used for this observation. */
	    /* Let's make sure we actually found a value for the gain
	    **	and readnoise... */

	    if (ampx > 0 && (gain[AMP_C] == 0. || rn2[AMP_C] == 0.)) { 
                trlerror 
		  ("No valid GAIN or READNOISE values to initialize ERR data."); 
		return (status = ERROR_RETURN);
            }
	    bias = ccdbias[2];
	    for (i = 0;  i < ampx;  i++) {
	        /* subtract bias and convert to electrons */
	        value = (Pix (x->sci.data, i, j) - bias) * gain[AMP_C];
	        if (value < 0.)
		    value = 0.;			/* sigma = 0 if signal = 0 */
		/* include readout noise and convert back to dn */
		Pix (x->err.data,i,j) = sqrt(value + rn2[AMP_C]) / gain[AMP_C];

            }

            /* This region corresponds to AMP_D, 
            **  if it is even used for this observation.  */

	    /* Let's make sure we actually found a value for the gain
	    **	and readnoise...  */
	    if (ampx == 0 && (gain[AMP_D] == 0. || rn2[AMP_D] == 0.) ) {
                trlerror 
		  ("No valid GAIN or READNOISE values to initialize ERR data.");
		return (status = ERROR_RETURN);
            }
	    bias = ccdbias[3];
	    for (i = ampx;  i < dimx;  i++) {
		 /* subtract bias and convert to electrons */
		 value = (Pix (x->sci.data, i, j) - bias) * gain[AMP_D];
		 if (value < 0.)
		     value = 0.;		/* sigma = 0 if signal = 0 */
		 /* include readout noise and convert back to dn */
		 Pix (x->err.data,i,j) = sqrt(value + rn2[AMP_D]) / gain[AMP_D];
	    }
        }
        
        
        for (j = ampy; j < dimy; j++) {

            /* This region corresponds to AMP_A, 
            **  if it is even used for this observation.  */

	    /* Let's make sure we actually found a value for the gain
	    **	and readnoise...  */
	    if (ampx > 0 && (gain[AMP_A] == 0. || rn2[AMP_A] == 0.)) {
                trlerror 
		  ("No valid GAIN or READNOISE values to initialize ERR data.");
		return (status = ERROR_RETURN);
            }
	    bias = ccdbias[0];
            /* Only execute this loop for AMP > 0 (multi-amp for line) */
	    for (i = 0;  i < ampx;  i++) {
		 /* subtract bias and convert to electrons */
		 value = (Pix (x->sci.data, i, j) - bias) * gain[AMP_A];
		 if (value < 0.)
		     value = 0.;		/* sigma = 0 if signal = 0 */
		 /* include readout noise and convert back to dn */
		 Pix (x->err.data,i,j) = sqrt(value + rn2[AMP_A]) / gain[AMP_A];
            }

            /* This region corresponds to AMP_B, 
            ** if it is even used for this observation.
            **  
            **  Default 1-AMP loop. AMPX and AMPY are zero.  */

            /* Let's make sure we actually found a value for the gain
            **	and readnoise...  */
            if (ampx == 0 && (gain[AMP_B] == 0. || rn2[AMP_B] == 0.)) {
                trlerror 
		  ("No valid GAIN or READNOISE values to initialize ERR data.");
	        return (status = ERROR_RETURN);
            }
	    bias = ccdbias[1];
	    for (i = ampx;  i < dimx;  i++) {
 
		 /* subtract bias and convert to electrons */
		 value = (Pix (x->sci.data, i, j) - bias) * gain[AMP_B];
		 if (value < 0.)
		     value = 0.;		/* sigma = 0 if signal = 0 */
		 /* include readout noise and convert back to dn */
		 Pix (x->err.data,i,j) = sqrt(value + rn2[AMP_B]) / gain[AMP_B];
	    }
        }

       /* End of CCD initialization */

    } else {

        /* ACS MAMA initialization */
        /* Set error to max of 1 or sqrt(counts) */
        for (j = 0; j < dimy; j++) {
            for (i = 0; i < dimx; i++) {
                value = sqrt(Pix(x->sci.data, i, j));
                Pix (x->err.data, i, j) = (value > 1) ? value : 1;
            }
        }
    }

    *done = 1;
    return (status);

}
コード例 #14
0
ファイル: rej_init.c プロジェクト: jhunkeler/hstcal
int rej_init (IODescPtr ipsci[], IODescPtr ipdq[], clpar *par, int nimgs,
	      int dim_x, int dim_y, multiamp noise, multiamp gain, float efac[],
	      float skyval[], DataUnits bunit[], SingleGroup *sg, float *work) {

    extern int status;

    float  scale, val, raw, raw0, signal0;
    float  *buf;
    short  *bufdq;
    float  *exp2;
    int    i, j, n;
    int    dum;
    int    *npts, *ipts;
    float  noise2[NAMPS], rog2[NAMPS];
    float  gain2[NAMPS];
    float  nse[2], gn[2];
    int    ampx, ampy, detector, chip;
    int    k, p;
    short  dqpat;
    float  exp2n, expn;
    int    non_zero;
    Hdr    dqhdr;

    void ipiksrt (float [], int, int[]);
    void get_nsegn (int, int, int, int, float *, float*, float *, float *);

    /* -------------------------------- begin ------------------------------ */
    expn=0.0f;
    scale = par->scalense / 100.;
    ampx = gain.colx;
    ampy = gain.coly;
    detector = gain.detector;
    chip = gain.chip;
    dqpat = par->badinpdq;

    ipts = calloc (nimgs, sizeof(int));
    npts = calloc (dim_x, sizeof(int));
    buf = calloc (dim_x, sizeof(float));
    exp2 = (float *) calloc (nimgs, sizeof(float));
    bufdq = calloc (dim_x, sizeof(short));

    for (k = 0; k < NAMPS; k++) {
        gain2[k] = 0.;
        noise2[k] = 0.;
        /* Assumption: ALL images have the same noise/gain values */
        rog2[k] = SQ(noise.val[k]);
    }

    non_zero = 0;
    for (n = 0; n < nimgs; n++) {
        exp2[n] = SQ(efac[n]);
	if (efac[n] > 0.) non_zero++;
    }
    get_nsegn (detector, chip, ampx, ampy, gain.val, rog2, gain2, noise2); 

    /* Use the stack median to construct the initial average */
    if (strncmp(par->initgues, "median", 3) == 0) {
        for (j = 0; j < dim_y; j++) {
            memset (npts, 0, dim_x*sizeof(int));

            /* Set up the gain and noise values used for this line
	    ** in ALL images */
            if (j < ampy ) {
                gn[0] = gain2[AMP_C];
                gn[1] = gain2[AMP_D];
                nse[0] = noise2[AMP_C];
                nse[1] = noise2[AMP_D];
            } else {
                gn[0] = gain2[AMP_A];
                gn[1] = gain2[AMP_B];
                nse[0] = noise2[AMP_A];
                nse[1] = noise2[AMP_B];            
            }

            for (n = 0; n < nimgs; n++) {
                initHdr(&dqhdr);
                getHeader(ipdq[n],&dqhdr);
                getFloatLine (ipsci[n], j, buf);
                getShortLine (ipdq[n], j, bufdq);
                freeHdr(&dqhdr);

		/* Rescale SCI data, if necessary */
		if (bunit[n] == COUNTRATE) {
		    for (i = 0; i < dim_x; i++) {
			 buf[i] *= efac[n];
		    }
		}

                for (i = 0; i < dim_x; i++) {
		     if (efac[n] > 0.) {
                         /* Only use GOOD pixels to build initial image */
                         if ((bufdq[i] & dqpat) == OK) {
                             PIX(work,npts[i],i,nimgs) =
						(buf[i] - skyval[n]) / efac[n];
                             npts[i] += 1;
                         }
		     } else {
			 PIX(work,npts[i],i,nimgs) = 0.;
		     }
                }
            }
 
            for (i = 0; i < ampx; i++) {
                dum = npts[i];

                if (dum == 0)
                    Pix(sg->sci.data,i,j) = 0.0F;

                else {

		    /* Setup index array for sorting... */
		    for (p=0; p < nimgs; p++) ipts[p] = p;
		    /* Sort pixel stack and corresponding index array. */
                    ipiksrt (&PIX(work,0,i,nimgs), dum, ipts);

		    /* Use sorted index array to match proper exptimes to
		       selected pixels for use in ERR array calculation. */
                    if ((dum/2)*2 == dum) {
                        /* Even number of input images for this pixel */
                        Pix(sg->sci.data,i,j) = (PIX(work,dum/2-1,i,nimgs) +
						 PIX(work,dum/2,i,nimgs)) / 2.;
			expn = (exp2[ipts[dum/2-1]] + exp2[ipts[dum/2]]) / 2.;
                    } else {
			/* Odd number of input images for this pixel */
                        Pix(sg->sci.data,i,j) = PIX(work,dum/2,i,nimgs);
			expn = exp2[ipts[dum/2]];
		    }
                }
                
                raw0 = Pix(sg->sci.data,i,j);
		exp2n = (expn > 0.) ? expn : 1.;
                Pix(sg->err.data,i,j) = (nse[0]+ raw0/gn[0] + SQ(scale*raw0)) /
					exp2n;
            } /* End loop over FIRST AMP used on pixels in the line */
             
            for (i = ampx; i < dim_x; i++) {
                dum = npts[i];
                if (dum == 0)
                    Pix(sg->sci.data,i,j) = 0.0F;
                else {
		    for (p=0; p < nimgs; p++) ipts[p] = p;
                    ipiksrt (&PIX(work,0,i,nimgs), dum, ipts);
                    if ((dum/2)*2 == dum) {
                        /* Even number of input images for this pixel */
                        Pix(sg->sci.data,i,j) = (PIX(work,dum/2-1,i,nimgs) +
						 PIX(work,dum/2,i,nimgs)) / 2.;
			expn = (exp2[ipts[dum/2-1]] + exp2[ipts[dum/2]]) / 2.;
                    } else {
                        Pix(sg->sci.data,i,j) = PIX(work,dum/2,i,nimgs);
			expn = exp2[ipts[dum/2]];
		    }
                }
                
                raw0 = Pix(sg->sci.data,i,j);
		exp2n = (expn > 0.) ? expn : 1.;
                Pix(sg->err.data,i,j) = (nse[1]+ raw0/gn[1] + SQ(scale*raw0)) /
					exp2n;
            } /* End loop over SECOND AMP used on pixels in the line */
        } /* End loop over lines */

    } else {

        /* use the minimum to construct the initial average */
        if (strncmp(par->initgues, "minimum", 3) != 0) {
            sprintf (MsgText,"Invalid INITGUES value %s, reset it to 'minimum'",
		     par->initgues);
            trlwarn (MsgText);
            strcpy (par->initgues, "minimum");
        }

        for (n = 0; n < nimgs; n++) {
            initHdr(&dqhdr);
            getHeader(ipdq[n],&dqhdr);
            for (j = 0; j < dim_y; j++) { 
                /* Set up the gain and noise values used for this line
		** in ALL images */
                if (j < ampy ) {
                    gn[0] = gain2[AMP_C];
                    gn[1] = gain2[AMP_D];
                    nse[0] = noise2[AMP_C];
                    nse[1] = noise2[AMP_D];
                } else {
                    gn[0] = gain2[AMP_A];
                    gn[1] = gain2[AMP_B];
                    nse[0] = noise2[AMP_A];
                    nse[1] = noise2[AMP_B];            
                }

                getFloatLine (ipsci[n], j, buf);
		getShortLine (ipdq[n],  j, bufdq);

		/* Rescale SCI data, if necessary */
		if (bunit[n] == COUNTRATE) {
		    for (i = 0; i < dim_x; i++) {
			 buf[i] *= efac[n];
		    }
		}

                /* AMPS C and D */
                for (i = 0; i < ampx; i++) {
                    raw = buf[i];
                    raw0 = (raw > 0.)? raw : 0.;
		    signal0 = ((raw - skyval[n]) > 0.) ? (raw - skyval[n]) : 0.;

		    if (efac[n] > 0.) {
                        val = (raw - skyval[n]) / efac[n];
		    } else {
			val = 0.;
		    }
                    if ((n == 0) || (val < Pix(sg->sci.data,i,j)) ) {
			if ((bufdq[i] & dqpat) == OK && (efac[n] > 0.)) {
                             Pix(sg->sci.data,i,j) = val;
                             /*Pix(sg->err.data,i,j) =
			      (nse[0]+ raw0/gn[0] + SQ(scale*raw0)) / exp2[n];*/
			     Pix(sg->err.data,i,j) =
			    (nse[0] + raw0/gn[0] + SQ(scale*signal0)) / exp2[n];
			} else {
			     Pix(sg->sci.data,i,j) = 0.;
			     Pix(sg->err.data,i,j) = 0.;
			}
                    } 
                } /* End of loop over FIRST AMP for this line in each image */

                for (i = ampx; i < dim_x; i++) {
                    raw = buf[i];
                    raw0 = (raw > 0.)? raw : 0.;
		    signal0 = ((raw - skyval[n]) > 0.) ? (raw - skyval[n]) : 0.;

		    if (efac[n] > 0.) {
                        val = (raw - skyval[n]) / efac[n];
		    } else {
			val = 0.;
		    }
                    if ((n == 0) ||
		       (val<Pix(sg->sci.data,i,j) && ((bufdq[i]&dqpat)==OK))) {
                        Pix(sg->sci.data,i,j) = val;
			if (efac[n] > 0.) {
                            Pix(sg->err.data,i,j) = 
			     (nse[1]+ raw0/gn[1] + SQ(scale*signal0)) / exp2[n];
			} else {
			    Pix(sg->err.data,i,j) = 0.;
			}
                    } 
                } /* End of loop over SECOND AMP for this line in each image */

            } /* End of loop over lines in image (y) */
            freeHdr(&dqhdr);
        } /* End of loop over images in set */
    }

    /* free the memory */
    free (ipts);
    free (npts);
    free (buf);
    free (exp2);
    free (bufdq);

    return (status);
}
コード例 #15
0
ファイル: calacs.c プロジェクト: jhunkeler/hstcal
int CalAcsRun (char *input, int printtime, int save_tmp, int verbose, int debug, const unsigned nThreads, const unsigned cteAlgorithmGen, const char * pcteTabNameFromCmd) {

    /* arguments:
       char *input     i: name of the FITS file/table to be processed
       int printtime   i: true --> print time stamps at intermediate steps
       int *save_tmp   i: true --> save temporary files
       int verbose     i: true --> print info during processing
       int debug       i: true --> print debugging info during processing
       int onecpu      i: true --> turn off use of OpenMP during processing
    */

    extern int status;

    ACSInfo acshdr;        /* calibration switches, etc */
    AsnInfo    asn;        /* association table data    */

    char *acsdth_input;    /* Input list for ACSDTH */

    int prod;

    void PrBegin (char *);
    void PrEnd (char *);
    void PrFileName (char *, char *);
    void TimeStamp (char *, char *);
    /* Association table routines */
    void initAsnInfo (AsnInfo *);
    void freeAsnInfo (AsnInfo *);
    int LoadAsn (AsnInfo *);
    int ProcessACSCCD (AsnInfo *, ACSInfo *, int *, int, const unsigned nThreads, const unsigned cteAlgorithmGen, const char * pcteTabNameFromCmd);
    int ProcessMAMA (AsnInfo *, ACSInfo *, int);
    int AcsDth (char *, char *, int, int, int);
    char *BuildDthInput (AsnInfo *, int);
    void InitDthTrl (char *, char *);

    /* Post error handler */
    push_hstioerr (errchk);

    PrBegin ("CALACS");    /* *** CALACS -- Version ... *** */

    if (printtime)
    TimeStamp ("CALACS started", "");

    /* Determine if input is a single file or an association
       table, then populate ASN structure with appropriate
       information to control processing.
    */
    initAsnInfo(&asn);

    if (debug) {
        trlmessage ("Initialized Association data ... ");
    }

    /* Copy Input filename to ASN structure    */
    strcpy (asn.input, input);

    /* Print image name. */
    trlmessage ("\n");

    PrFileName ("input", asn.input);

    /* Set verbose flag... */
    asn.verbose = verbose;
    asn.debug = debug;

    /* LoadAsn will determine whether input is a single file or an
       Association table.  If a single image, it will look in that images
       association table to see what products are associated with it, and
       process them accordingly.  If it is just a single image as its
       own output, it will proceed as a 1 element table.
       Based on routines from n_getAsnTable() and n_setup() in CALNICB
    */
    if(LoadAsn(&asn)) {
        freeAsnInfo (&asn);
        return (status);
    }

    /* Check to see that detector is known, as it could come through with a
       value of 0 or UNKNOWN_DETECTOR.
       WJH  2Mar99
    */
    if (asn.detector == UNKNOWN_DETECTOR || asn.detector == 0) {
        trlwarn ("Unknown detector type for observations.");
        freeAsnInfo(&asn);
        return (status = NOTHING_TO_DO);
    }

    if (asn.verbose) {
        sprintf (MsgText,"CALACS: Detector %s, type %d ",asn.instr, asn.detector);
        trlmessage (MsgText);
    }

    /* Determine what detector we are working with... */
    if (asn.detector != MAMA_DETECTOR ) {  /* Process CCD data ... */
        if (asn.verbose) {
            trlmessage ("CALACS: processing a CCD product");
        }
        if (ProcessACSCCD(&asn, &acshdr, &save_tmp, printtime, nThreads, cteAlgorithmGen, pcteTabNameFromCmd)) {
            if (status == NOTHING_TO_DO) {
                trlwarn ("No processing desired for CCD data.");
            } else {
                trlerror ("Couldn't process CCD data");
            }

            freeAsnInfo(&asn);
            return (status);
        }
        trlmessage("Finished CCD processing...");
    } else {  /* Process MAMA observations here */

        trlmessage("Starting to process MAMA data now...");

        if (ProcessMAMA(&asn, &acshdr, printtime)) {
            if (status == NOTHING_TO_DO){
                trlwarn ("No processing desired for MAMA data.");
            } else{
                trlerror ("Couldn't process MAMA data");
            }
            freeAsnInfo(&asn);
            return (status);
        }
        trlmessage("Finished MAMA processing...");
    }


    /* Add DTH processing here... */
    /* For each DTH product... */
    if (asn.process == FULL){
        if (asn.verbose) {
            trlmessage ("CALACS: Building DTH products");
        }
        acsdth_input = NULL;
        for (prod = 0; prod < asn.numprod; prod++) {
            /* Create empty DTH product, header only */
            /* This uses only one sub-product for the header template,
               but later versions should use a function similar to
               BuildSumInput to create list of subproducts as inputs...
            */
            acsdth_input = BuildDthInput (&asn, prod);

            /* We always want to create a final concatenated trailer file for
               the entire association whether there is a product or not. So, we
               set up the trailer file based on the association file name itself.
            */

            /* If desired, we could optionally use the full _drz.tra filename
               as the trailer filename, based on the output dither product name.
            if (strcmp(asn.product[prod].prodname,"") != 0) {
                InitDthTrl (acsdth_input, asn.product[prod].prodname);
            } else { */

            InitDthTrl(acsdth_input, asn.rootname);

            /* End brace for optional dither product name assignment...
            } */

            /* Check if we have a PROD-DTH specified...*/
            if (strcmp(asn.product[prod].prodname, "") != 0) {

                if ((asn.dthcorr == PERFORM || asn.dthcorr == DUMMY)) {
                    if (AcsDth (acsdth_input, asn.product[prod].prodname, asn.dthcorr, printtime, asn.verbose) )
                        return (status);

                    /* Pass posid of 0 to indicate a PRODUCT is to be updated */
                    updateAsnTable(&asn, prod, NOPOSID);
                }
            } else {
                trlwarn ("No DTH product name specified. No product created.");
                /*status = ACS_OK; */
            }
        }
        free (acsdth_input);
    }
    if (asn.verbose) {
        trlmessage ("CALACS: Finished processing product ");
    }

    freeAsnInfo(&asn);

    trlmessage ("\n");
    PrEnd ("CALACS");        /* *** CALACS complete *** */

    if (printtime)
    TimeStamp ("CALACS completed", acshdr.rootname);

    /* Return the final value of status, which should be ACS_OK if
       all went well or some error condition otherwise. */
    return (status);
}
コード例 #16
0
ファイル: acssum.c プロジェクト: jhunkeler/hstcal
static int GetSumKeyInfo (AcsSumInfo *acs, Hdr *phdr) {

/* arguments:
AcsSumInfo *acs  io: calibration switches and info
Hdr *phdr       i: primary header
*/

    extern int status;
    int sdqflags;            /* "serious" data quality flags */
    int nextend;            /* number of FITS extensions */
    int nrptexp;            /* number of exposures */
    int no_def = 0;            /* missing keyword is fatal error */

    int GetKeyInt (Hdr *, char *, int, int, int *);
    int GetKeyStr (Hdr *, char *, int, char *, char *, int);
    int GetKeyDbl (Hdr *, char *, int, double, double *);

    /* Have the data been converted from counts to absolute flux? */

    if (GetKeyStr (phdr, "APERTURE", no_def, "", acs->aperture, ACS_CBUF))
        return (status);

    if (GetKeyStr (phdr, "DETECTOR", no_def, "", acs->det, ACS_CBUF))
        return (status);
    if (strcmp (acs->det, "SBC") == 0) {
        acs->detector = MAMA_DETECTOR;
    } else if (strcmp (acs->det, "HRC") == 0) {
        acs->detector = HRC_CCD_DETECTOR;
    } else if (strcmp (acs->det, "WFC") == 0) {
        acs->detector = WFC_CCD_DETECTOR;
    } else {
        sprintf (MsgText, "DETECTOR = %s is invalid", acs->det);
        trlerror (MsgText);
        return (status = HEADER_PROBLEM);
    }

    /* Filter names. */
    if (GetKeyStr (phdr, "FILTER1", USE_DEFAULT, "", acs->filter1, ACS_CBUF))
        return (status);
    if (GetKeyStr (phdr, "FILTER2", USE_DEFAULT, "", acs->filter2, ACS_CBUF))
        return (status);

    if (GetKeyDbl (phdr, "EXPTIME", NO_DEFAULT, 0., &acs->exptime))
        return (status);

    if (GetKeyInt (phdr, "SDQFLAGS", USE_DEFAULT, MAX_DQ, &sdqflags))
        return (status);
    acs->sdqflags = sdqflags;

    /* Find out how many extensions there are in this file. */
    if (GetKeyInt (phdr, "NEXTEND", USE_DEFAULT, EXT_PER_GROUP, &nextend))
        return (status);

    /* Convert number of extensions to number of SingleGroups. */
    acs->nimsets = nextend / EXT_PER_GROUP;

    /* Get NRPTEXP and compare with nimages. */
    if (GetKeyInt (phdr, "NRPTEXP", no_def, 0, &nrptexp))
        return (status);

    if (nrptexp != acs->nimages) {
        sprintf (MsgText, "%d exposures will be summed, however, NRPTEXP was %d.",
            acs->nimages, nrptexp);
        trlwarn (MsgText);
    }

    if (acs->nimages <= 1) {
        trlwarn ("ACSSUM: Can not continue. There is only one input image!");
        return (status = NOTHING_TO_DO);
    }

    return (status);
}
コード例 #17
0
ファイル: dophot.c プロジェクト: jhunkeler/hstcal
int doPhot (ACSInfo *acs2d, SingleGroup *x) {

  /* arguments:
   ACSInfo *acs2d     i: calibration switches, etc
   SingleGroup *x    io: image to be calibrated; primary header is modified
   */

  extern int status;

  PhotPar obs;

  char photmode[CHAR_LINE_LENGTH],obsmode[CHAR_LINE_LENGTH];

  /* function prototypes from lib */
  int GetKeyStr (Hdr *, char *, int, char *, char *, int);
  int PutKeyFlt (Hdr *, char *, float, char *);

  if (acs2d->photcorr == DUMMY)
    return (status);

  /* Extract photmode from sci extension header*/
  if (GetKeyStr(&x->sci.hdr,"PHOTMODE",USE_DEFAULT,"",photmode, CHAR_LINE_LENGTH))
    return (status);

  /* Add commas to PHOTMODE string and change all strings to
   lower case for use in synphot. */
  Phot2Obs(photmode,obsmode);
  if (acs2d->verbose){
    sprintf(MsgText,"Created SYNPHOT obsmode of: %s",obsmode);
    trlmessage(MsgText);
  }

  /* Initialize PhotPar struct */
  InitPhotPar(&obs, acs2d->phot.name, acs2d->phot.pedigree);

  /* get phot values */
  if (GetPhotTab(&obs,obsmode)) {
    trlerror("Error return from GetPhotTab.");
    return status;
  }

  if (acs2d->verbose){
    sprintf(MsgText,"Computed PHOTFLAM value of %g",obs.photflam);
    trlmessage(MsgText);
  }

  /* Update the photometry keyword values in the SCI header.
   Revised 10 March 1999 WJH
   */

  if (PutKeyFlt (&x->sci.hdr, "PHOTFLAM", obs.photflam, "inverse sensitivity"))
    return (status);

  if (PutKeyFlt (&x->sci.hdr, "PHOTZPT", obs.photzpt, "zero point"))
    return (status);

  if (PutKeyFlt (&x->sci.hdr, "PHOTPLAM", obs.photplam, "pivot wavelength"))
    return (status);

  if (PutKeyFlt (&x->sci.hdr, "PHOTBW", obs.photbw, "RMS bandwidth"))
    return (status);

  FreePhotPar(&obs);

  /* check whether GetPhotTab returned -9999, which means it was asked
   to do extrapolation */
  if (obs.photflam == -9999) {
    trlwarn("IMPHTTAB extrapolation not supported, PHOTCORR skipped.");
    return (status = CAL_STEP_NOT_DONE);
  }

  return (status);
}