Construct the HDU containing the pixel-level light curve.
552737
def PixelsHDU(model):
    '''
    

    '''

    # Get mission cards
    cards = model._mission.HDUCards(model.meta, hdu=2)

    # Add EVEREST info
    cards = []
    cards.append(('COMMENT', '************************'))
    cards.append(('COMMENT', '*     EVEREST INFO     *'))
    cards.append(('COMMENT', '************************'))
    cards.append(('MISSION', model.mission, 'Mission name'))
    cards.append(('VERSION', EVEREST_MAJOR_MINOR, 'EVEREST pipeline version'))
    cards.append(('SUBVER', EVEREST_VERSION, 'EVEREST pipeline subversion'))
    cards.append(('DATE', strftime('%Y-%m-%d'),
                  'EVEREST file creation date (YYYY-MM-DD)'))

    # Create the HDU
    header = pyfits.Header(cards=cards)

    # The pixel timeseries
    arrays = [pyfits.Column(name='FPIX', format='%dD' %
                            model.fpix.shape[1], array=model.fpix)]

    # The first order PLD vectors for all the neighbors (npixels, ncadences)
    X1N = model.X1N
    if X1N is not None:
        arrays.append(pyfits.Column(name='X1N', format='%dD' %
                                    X1N.shape[1], array=X1N))

    cols = pyfits.ColDefs(arrays)
    hdu = pyfits.BinTableHDU.from_columns(cols, header=header, name='PIXELS')

    return hdu
523590
def gather_info_hdu(self, hdulist):
        """"""
        values = {}
        values['n_ext'] = len(hdulist)
        extnames = [hdu.header.get('extname', '') for hdu in hdulist[1:]]
        values['name_ext'] = ['PRIMARY'] + extnames

        fits_extractor = self.extractor_map['fits']
        for key in self.meta_dinfo_headers:
            values[key] = fits_extractor.extract(key, hdulist)

        return values
179920
def read_spectral_data(hdu):
    
    ebins = read_energy_bounds(hdu)
    fluxes = np.ndarray((len(ebins)))
    try:
        fluxes[0:-1] = hdu.data.field("E_MIN_FL")
        fluxes[-1] = hdu.data.field("E_MAX_FL")[-1]
        npreds = hdu.data.field("NPRED")
    except:
        fluxes = np.ones((len(ebins)))
        npreds = np.ones((len(ebins)))
    return ebins, fluxes, npreds
915673
def _build_model(self):
        """"""

        with tf.variable_scope("init"):
            x = self._conv("init_conv", self._images, 3, 3, 16,
                           self._stride_arr(1))

        strides = [1, 2, 2]
        activate_before_residual = [True, False, False]
        if self.hps.use_bottleneck:
            res_func = self._bottleneck_residual
            filters = [16, 64, 128, 256]
        else:
            res_func = self._residual
            filters = [16, 16, 32, 64]

        with tf.variable_scope("unit_1_0"):
            x = res_func(x, filters[0], filters[1], self._stride_arr(
                strides[0]), activate_before_residual[0])
        for i in range(1, self.hps.num_residual_units):
            with tf.variable_scope("unit_1_%d" % i):
                x = res_func(x, filters[1], filters[1], self._stride_arr(1),
                             False)

        with tf.variable_scope("unit_2_0"):
            x = res_func(x, filters[1], filters[2], self._stride_arr(
                strides[1]), activate_before_residual[1])
        for i in range(1, self.hps.num_residual_units):
            with tf.variable_scope("unit_2_%d" % i):
                x = res_func(x, filters[2], filters[2], self._stride_arr(1),
                             False)

        with tf.variable_scope("unit_3_0"):
            x = res_func(x, filters[2], filters[3], self._stride_arr(
                strides[2]), activate_before_residual[2])
        for i in range(1, self.hps.num_residual_units):
            with tf.variable_scope("unit_3_%d" % i):
                x = res_func(x, filters[3], filters[3], self._stride_arr(1),
                             False)
        with tf.variable_scope("unit_last"):
            x = self._batch_norm("final_bn", x)
            x = self._relu(x, self.hps.relu_leakiness)
            x = self._global_avg_pool(x)

        with tf.variable_scope("logit"):
            logits = self._fully_connected(x, self.hps.num_classes)
            self.predictions = tf.nn.softmax(logits)

        with tf.variable_scope("costs"):
            xent = tf.nn.softmax_cross_entropy_with_logits(
                logits=logits, labels=self.labels)
            self.cost = tf.reduce_mean(xent, name="xent")
            self.cost += self._decay()

            if self.mode == "eval":
                tf.summary.scalar("cost", self.cost)
309935
def create_background_map(data, bsx, bsy):
    """"""
    sx, sy = data.shape
    mx = sx // bsx
    my = sy // bsy
    comp = []
    rms = []
    # Rows
    sp = numpy.split(data, numpy.arange(bsx, sx, bsx), axis=0)
    for s in sp:
        # Columns
        rp = numpy.split(s, numpy.arange(bsy, sy, bsy), axis=1)
        for r in rp:
            b, r = background_estimator(r)
            comp.append(b)
            rms.append(r)

    # Reconstructed image
    z = numpy.array(comp)
    z.shape = (mx, my)
    # median filter
    ndfilter.median_filter(z, size=(3, 3), output=z)

    # Interpolate to the original size
    new = _interpolation(z, sx, sy, mx, my)

    # Interpolate the rms
    z = numpy.array(rms)
    z.shape = (mx, my)
    nrms = _interpolation(z, sx, sy, mx, my)

    return new, nrms
246288
def serialize_hdr(self):
        
        return struct.pack(self._PACK_HDR_STR, self.auth_type, self.auth_len)
1330851
def set_hsb(self, hue, saturation, brightness=None, *, index=0,
                transition_time=None):
        """"""
        self._value_validate(hue, RANGE_HUE, "Hue")
        self._value_validate(saturation, RANGE_SATURATION, "Saturation")

        values = {
            ATTR_LIGHT_COLOR_SATURATION: saturation,
            ATTR_LIGHT_COLOR_HUE: hue
        }

        if brightness is not None:
            values[ATTR_LIGHT_DIMMER] = brightness
            self._value_validate(brightness, RANGE_BRIGHTNESS, "Brightness")

        if transition_time is not None:
            values[ATTR_TRANSITION_TIME] = transition_time

        return self.set_values(values, index=index)
1274033
def create_from_hdu(cls, hdu, ebins=None):
        
        convname = HPX.identify_HPX_convention(hdu.header)
        conv = HPX_FITS_CONVENTIONS[convname]
        try:
            pixels = hdu.data[conv.idxstring]
        except KeyError:
            pixels = None
        return cls.create_from_header(hdu.header, ebins, pixels)
624132
def trim(hdu, datasec='DATASEC'):
    """"""
    datasec = re.findall(r'(\d+)',
                         hdu.header.get(datasec))
    l = int(datasec[0]) - 1
    r = int(datasec[1])
    b = int(datasec[2]) - 1
    t = int(datasec[3])
    logger.info("Trimming [%d:%d,%d:%d]" % ( l, r, b, t))
    hdu.data = hdu.data[b:t, l:r]
    hdu.header.update('DATASEC',
                      "[%d:%d,%d:%d]" % (1, r - l + 1, 1, t - b + 1),
                      comment="Image was trimmed")
    hdu.header.update('ODATASEC',
                      "[%d:%d,%d:%d]" % (l + 1, r, b + 1, t),
                      comment="previous DATASEC")
    return
403144
def project(vx, vy, occlusion):
    """"""
    p = np.zeros(vx.shape)
    div = -0.5 * (np.roll(vx, -1, axis=1) - np.roll(vx, 1, axis=1)
                + np.roll(vy, -1, axis=0) - np.roll(vy, 1, axis=0))
    div = make_continuous(div, occlusion)

    for k in range(50):
        p = (div + np.roll(p, 1, axis=1) + np.roll(p, -1, axis=1)
                 + np.roll(p, 1, axis=0) + np.roll(p, -1, axis=0))/4.0
        p = make_continuous(p, occlusion)

    vx = vx - 0.5*(np.roll(p, -1, axis=1) - np.roll(p, 1, axis=1))
    vy = vy - 0.5*(np.roll(p, -1, axis=0) - np.roll(p, 1, axis=0))

    vx = occlude(vx, occlusion)
    vy = occlude(vy, occlusion)
    return vx, vy
716062
def light(self):
        
        sun = self.chart.getObject(const.SUN)
        return light(self.obj, sun)
687770
def getdarkimg(self,chip):
        
        sci_chip = self._image[self.scienceExt,chip]

        # First attempt to get the dark image specified by the "DARKFILE"
        # keyword in the primary keyword of the science data.
        try:
            filename = self.header["DARKFILE"]
            handle = fileutil.openImage(filename, mode='readonly', memmap=False)
            hdu = fileutil.getExtn(handle,extn="sci,1")
            darkobj = hdu.data[sci_chip.ltv2:sci_chip.size2,sci_chip.ltv1:sci_chip.size1]

        # If the darkfile cannot be located, create the dark image from
        # what we know about the detector dark current and assume a
        # constant dark current for the whole image.
        except:
            darkobj = (np.ones(sci_chip.image_shape,
                               dtype=sci_chip.image_dtype) *
                       self.getdarkcurrent())
        return darkobj
407745
def make_cdisk_kernel(psf, sigma, npix, cdelt, xpix, ypix, psf_scale_fn=None,
                      normalize=False):
    

    sigma /= 0.8246211251235321

    dtheta = psf.dtheta
    egy = psf.energies

    x = make_pixel_distance(npix, xpix, ypix)
    x *= cdelt

    k = np.zeros((len(egy), npix, npix))
    for i in range(len(egy)):
        def fn(t): return psf.eval(i, t, scale_fn=psf_scale_fn)
        psfc = convolve2d_disk(fn, dtheta, sigma)
        k[i] = np.interp(np.ravel(x), dtheta, psfc).reshape(x.shape)

    if normalize:
        k /= (np.sum(k, axis=0)[np.newaxis, ...] * np.radians(cdelt) ** 2)

    return k
1276231
def set_state(self, hdr):
        """"""

        self.conf_f = hdr.get('CSUCONFF', 'UNKNOWN')
        # Read CSUPOS and set position in model
        # The bars
        for idx in self.bars:
            key = "CSUP{}".format(idx)
            # UNIT is mm

            # set CSUPOS for BAR
            # Using the model, this sets the X,Y coordinate
            self.bars[idx].csupos = hdr[key]

        self._update_slits(hdr)
422720
private static int  hslToRgb(float hue, float sat, float light)
   {
      hue = (hue >= 0f) ? hue % 360f : (hue % 360f) + 360f;  // positive modulo (ie. -10 => 350)
      hue /= 60f;    // [0, 360] -> [0, 6]
      sat /= 100;   // [0, 100] -> [0, 1]
      light /= 100; // [0, 100] -> [0, 1]
      sat = (sat < 0f) ? 0f : (sat > 1f) ? 1f : sat;
      light = (light < 0f) ? 0f : (light > 1f) ? 1f : light;
      float  t1, t2;
      if (light <= 0.5f) {
         t2 = light * (sat + 1f);
      } else {
         t2 = light + sat - (light * sat);
      }
      t1 = light * 2f - t2;
      float  r = hueToRgb(t1, t2, hue + 2f);
      float  g = hueToRgb(t1, t2, hue);
      float  b = hueToRgb(t1, t2, hue - 2f);
      return clamp255(r * 256f)<<16 | clamp255(g * 256f)<<8 | clamp255(b * 256f);
   }
9604
def fromfits(infile, hdu = 0, verbose = True):
    
    
    pixelarray, hdr = ft.getdata(infile, hdu, header=True)
    pixelarray = np.asarray(pixelarray).transpose()
    #print pixelarray
    
    pixelarrayshape = pixelarray.shape
    if verbose :
        print "Input shape : (%i, %i)" % (pixelarrayshape[0], pixelarrayshape[1])
        print "Input file BITPIX : %s" % (hdr["BITPIX"])
    pixelarrayshape = np.asarray(pixelarrayshape)
    if verbose :
        print "Internal array type :", pixelarray.dtype.name
    
    return f2nimage(pixelarray, verbose = verbose)
39225
def makeHDU(self, mag_1, mag_err_1, mag_2, mag_err_2, lon, lat, mc_source_id):
        
        if self.config['catalog']['coordsys'].lower() == 'cel' \
           and self.config['coords']['coordsys'].lower() == 'gal':
            lon, lat = ugali.utils.projector.gal2cel(lon, lat)
        elif self.config['catalog']['coordsys'].lower() == 'gal' \
           and self.config['coords']['coordsys'].lower() == 'cel':
            lon, lat = ugali.utils.projector.cel2gal(lon, lat)

        columns = [
            pyfits.Column(name=self.config['catalog']['objid_field'],
                          format = 'D',array = np.arange(len(lon))),
            pyfits.Column(name=self.config['catalog']['lon_field'],
                          format = 'D',array = lon),
            pyfits.Column(name = self.config['catalog']['lat_field'],          
                          format = 'D',array = lat), 
            pyfits.Column(name = self.config['catalog']['mag_1_field'],        
                          format = 'E',array = mag_1),
            pyfits.Column(name = self.config['catalog']['mag_err_1_field'],    
                          format = 'E',array = mag_err_1),
            pyfits.Column(name = self.config['catalog']['mag_2_field'],        
                          format = 'E',array = mag_2),
            pyfits.Column(name = self.config['catalog']['mag_err_2_field'],    
                          format = 'E',array = mag_err_2),
            pyfits.Column(name = self.config['catalog']['mc_source_id_field'], 
                          format = 'I',array = mc_source_id),
        ]

        hdu = pyfits.new_table(columns)
        return hdu