Create a FITS table HDU representation of a MOC.
967761
def write_moc_fits_hdu(moc):
    

    # Ensure data are normalized.
    moc.normalize()

    # Determine whether a 32 or 64 bit column is required.
    if moc.order < 14:
        moc_type = np.int32
        col_type = 'J'
    else:
        moc_type = np.int64
        col_type = 'K'

    # Convert to the NUNIQ value which guarantees that one of the
    # top two bits is set so that the order of the value can be
    # determined.
    nuniq = []
    for (order, cells) in moc:
        uniq_prefix = 4 * (4 ** order)
        for npix in cells:
            nuniq.append(npix + uniq_prefix)

    # Prepare the data, and sort into numerical order.
    nuniq = np.array(nuniq, dtype=moc_type)
    nuniq.sort()

    # Create the FITS file.
    col = fits.Column(name='UNIQ', format=col_type, array=nuniq)

    cols = fits.ColDefs([col])
    rec = fits.FITS_rec.from_columns(cols)
    tbhdu = fits.BinTableHDU(rec)

    # Mandatory Keywords.
    tbhdu.header['PIXTYPE'] = 'HEALPIX'
    tbhdu.header['ORDERING'] = 'NUNIQ'
    tbhdu.header['COORDSYS'] = 'C'
    tbhdu.header['MOCORDER'] = moc.order
    tbhdu.header.comments['PIXTYPE'] = 'HEALPix magic code'
    tbhdu.header.comments['ORDERING'] = 'NUNIQ coding method'
    tbhdu.header.comments['COORDSYS'] = 'ICRS reference frame'
    tbhdu.header.comments['MOCORDER'] = 'MOC resolution (best order)'

    # Optional Keywords.
    tbhdu.header['MOCTOOL'] = 'PyMOC ' + version
    tbhdu.header.comments['MOCTOOL'] = 'Name of MOC generator'
    if moc.type is not None:
        tbhdu.header['MOCTYPE'] = moc.type
        tbhdu.header.comments['MOCTYPE'] = 'Source type (IMAGE or CATALOG)'
    if moc.id is not None:
        tbhdu.header['MOCID'] = moc.id
        tbhdu.header.comments['MOCID'] = 'Identifier of the collection'
    if moc.origin is not None:
        tbhdu.header['ORIGIN'] = moc.origin
        tbhdu.header.comments['ORIGIN'] = 'MOC origin'
    tbhdu.header['DATE'] = datetime.utcnow().replace(
        microsecond=0).isoformat()
    tbhdu.header.comments['DATE'] = 'MOC creation date'
    if moc.name is not None:
        tbhdu.header['EXTNAME'] = moc.name
        tbhdu.header.comments['EXTNAME'] = 'MOC name'

    return tbhdu
933808
def _gen_dimension_table(self):
        
        headers = ['Dimension Name', 'Description',
            'Global Size', 'Extents']

        table = []
        for dimval in sorted(self.dimensions(copy=False).itervalues(),
                             key=lambda dval: dval.name.upper()):

            table.append([dimval.name,
                dimval.description,
                dimval.global_size,
                (dimval.lower_extent, dimval.upper_extent)])

        return table, headers
962767
def standardize_table(cls, table):
        '''
        
        '''

        print(cls)
        identifiers = {n+'-id':table[n] for n in cls.identifier_keys}

        # create skycoord objects
        N = len(table)
        coordinates = dict(  ra=table['_RAJ2000'].data.data*u.deg,
                             dec=table['_DEJ2000'].data.data*u.deg,
                             pm_ra_cosdec=table['pmRA'].data.data*u.arcsec/u.year,
                             pm_dec=table['pmDE'].data.data*u.arcsec/u.year,
                             radial_velocity=np.nan*np.ones(N)*u.km/u.s,
                             distance=np.nan*np.ones(N)*u.pc,#distance=1000*u.pc/table['parallax'].data, # weirdly, messed with RA + Dec signs if parallax is zero
                             obstime=cls.epoch*np.ones(N)*u.year)#Time(, format='decimalyear'))
        for k in coordinates:
            print(k, coordinates[k])
        magnitudes = {f+'-mag':table[f+'mag'].data for f in cls.filters}

        standardized = hstack([Table(identifiers),
                               Table(coordinates),
                               Table(magnitudes)])
        standardized.meta['catalog'] = 'Gaia'

        return standardized
500742
def fromfits(infilename, hdu = 0, verbose = True):
    
    
    pixelarray, hdr = pyfits.getdata(infilename, hdu, header=True)
    pixelarray = np.asarray(pixelarray).transpose()
    
    pixelarrayshape = pixelarray.shape
    if verbose :
        print "FITS import shape : (%i, %i)" % (pixelarrayshape[0], pixelarrayshape[1])
        print "FITS file BITPIX : %s" % (hdr["BITPIX"])
        print "Internal array type :", pixelarray.dtype.name
    
    return pixelarray, hdr
667216
def fetch_rrlyrae_fitdata(**kwargs):
    
    save_loc = _get_download_or_cache('table3.dat.gz', **kwargs)

    dtype = [('id', 'i'), ('RA', 'f'), ('DEC', 'f'), ('rExt', 'f'),
             ('d', 'f'), ('RGC', 'f'),
             ('u', 'f'), ('g', 'f'), ('r', 'f'),
             ('i', 'f'), ('z', 'f'), ('V', 'f'),
             ('ugmin', 'f'), ('ugmin_err', 'f'),
             ('grmin', 'f'), ('grmin_err', 'f')]

    return np.loadtxt(save_loc, dtype=dtype)
733385
def std_table(rows):
    """"""

    result = ""
    if len(rows) > 1:
        headers = rows[0]._fields
        lens = []
        for i in range(len(rows[0])):
            lens.append(len(max([x[i] for x in rows] + [headers[i]],
                                key=lambda x: len(str(x)))))
        formats = []
        hformats = []
        for i in range(len(rows[0])):
            if isinstance(rows[0][i], int):
                formats.append("%%%dd" % lens[i])
            else:
                formats.append("%%-%ds" % lens[i])
            hformats.append("%%-%ds" % lens[i])
        pattern = " | ".join(formats)
        hpattern = " | ".join(hformats)
        separator = "-+-".join(['-' * n for n in lens])
        result += hpattern % tuple(headers) + " \n"
        result += separator + "\n"

        for line in rows:
            result += pattern % tuple(t for t in line) + "\n"
    elif len(rows) == 1:
        row = rows[0]
        hwidth = len(max(row._fields, key=lambda x: len(x)))
        for i in range(len(row)):
            result += "%*s = %s" % (hwidth, row._fields[i], row[i]) + "\n"

    return result
1041657
def assemble_pysb():
    """"""
    if request.method == 'OPTIONS':
        return {}
    response = request.body.read().decode('utf-8')
    body = json.loads(response)
    stmts_json = body.get('statements')
    export_format = body.get('export_format')
    stmts = stmts_from_json(stmts_json)
    pa = PysbAssembler()
    pa.add_statements(stmts)
    pa.make_model()
    try:
        for m in pa.model.monomers:
            pysb_assembler.set_extended_initial_condition(pa.model, m, 0)
    except Exception as e:
        logger.exception(e)

    if not export_format:
        model_str = pa.print_model()
    elif export_format in ('kappa_im', 'kappa_cm'):
        fname = 'model_%s.png' % export_format
        root = os.path.dirname(os.path.abspath(fname))
        graph = pa.export_model(format=export_format, file_name=fname)
        with open(fname, 'rb') as fh:
            data = 'data:image/png;base64,%s' % \
                base64.b64encode(fh.read()).decode() 
            return {'image': data}
    else:
        try:
            model_str = pa.export_model(format=export_format)
        except Exception as e:
            logger.exception(e)
            model_str = ''
    res = {'model': model_str}
    return res
1125309
def write_to_fitsfile(self, fitsfile, clobber=True):
        
        from fermipy.skymap import Map
        hpx_header = self._hpx.make_header()
        index_map = Map(self.ipixs, self.wcs)
        mult_map = Map(self.mult_val, self.wcs)
        prim_hdu = index_map.create_primary_hdu()
        mult_hdu = index_map.create_image_hdu()
        for key in ['COORDSYS', 'ORDERING', 'PIXTYPE',
                    'ORDERING', 'ORDER', 'NSIDE',
                    'FIRSTPIX', 'LASTPIX']:
            prim_hdu.header[key] = hpx_header[key]
            mult_hdu.header[key] = hpx_header[key]

        hdulist = fits.HDUList([prim_hdu, mult_hdu])
        hdulist.writeto(fitsfile, overwrite=clobber)
850972
def _load_fits(self, h5file):
        
        fits = {}
        for key in ['mf']:
            fits[key] = self._load_scalar_fit(fit_key=key, h5file=h5file)
        for key in ['chif', 'vf']:
            fits[key] = self._load_vector_fit(key, h5file)
        return fits
284719
def update_image(hdu_in, hdu=None):
    
    if hdu is None:
        hdu = fits.ImageHDU(
            data=hdu_in.data, header=hdu_in.header, name=hdu_in.name)
    else:
        hdu.data += hdu_in.data
    return hdu
1159661
def HiResHDU(model):
    '''
    

    '''

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

    # Add EVEREST info
    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)
    if model.hires is not None:
        hdu = pyfits.ImageHDU(
            data=model.hires, header=header, name='HI RES IMAGE')
    else:
        hdu = pyfits.ImageHDU(data=np.empty(
            (0, 0), dtype=float), header=header, name='HI RES IMAGE')
    return hdu
257578
def movnam_hdu(self, extname, hdutype=ANY_HDU, extver=0):
        
        extname = mks(extname)
        hdu = self._FITS.movnam_hdu(hdutype, extname, extver)
        return hdu
859875
def make_table(headers=None, rows=None):
    """"""
    if callable(headers):
        headers = headers()
    if callable(rows):
        rows = rows()
    assert isinstance(headers, list)
    assert isinstance(rows, list)
    assert all(len(row) == len(headers) for row in rows)

    plain_headers = [strip_ansi(six.text_type(v)) for v in headers]
    plain_rows = [row for row in [strip_ansi(six.text_type(v)) for v in rows]]

    plain_headers = []
    column_widths = []

    for k, v in enumerate(headers):
        v = six.text_type(v)
        plain = strip_ansi(v)
        plain_headers.append(plain)
        column_widths.append(len(plain))

        if len(v) == len(plain):
            # Value was unstyled, make it bold
            v = click.style(v, bold=True)

        headers[k] = v

    plain_rows = []
    for row in rows:
        plain_row = []
        for k, v in enumerate(row):
            v = six.text_type(v)
            plain = strip_ansi(v)
            plain_row.append(plain)
            column_widths[k] = max(column_widths[k], len(plain))

        plain_rows.append(plain_row)

    return Table(
        headers=headers,
        plain_headers=plain_headers,
        rows=rows,
        plain_rows=plain_rows,
        column_widths=column_widths,
    )
647587
def convert_table(app, docname, source):
    """"""
    num_tables = 0
    for i,j in enumerate(source):
        table = []
        output = ''
        in_table = False
        for l in j.split('\n'):
            r = l.strip()
            if r.startswith('|'):
                table.append(r)
                in_table = True
            else:
                if in_table is True:
                    converted = _convert_md_table_to_rst(table)
                    if converted is '':
                        print("Failed to convert the markdown table")
                        print(table)
                    else:
                        num_tables += 1
                    output += converted
                    in_table = False
                    table = []
                output += l + '\n'
        source[i] = output
    if num_tables > 0:
        print('Converted %d tables in %s' % (num_tables, docname))
296388
def rst_table(self, array):
        """"""
        # Determine cell width for each column
        cell_dict = {}
        for i, row in enumerate(array):
            for j, val in enumerate(row):
                if j not in cell_dict:
                    cell_dict[j] = []
                cell_dict[j].append(val)
        for item in cell_dict:
            cell_dict[item] = max([len(x) for x in cell_dict[item]]) + 1  # Contains adapted width for each column

        # Format top line
        num_cols = len(array[0])
        form = '+'
        for col in range(num_cols):
            form += (cell_dict[col] + 1) * '-'
            form += '+'
        form += '\n'

        # Format values
        for i, row in enumerate(array):
            form += '| '
            for j, val in enumerate(row):
                cell_width = cell_dict[j]
                form += str(val) + (cell_width - len(val)) * ' ' + '| '
            form.rstrip()
            form += '\n'

            # Seperation lines
            form += '+'
            if i == 0:
                sign = '='
            else:
                sign = '-'
            for col in range(num_cols):
                form += (cell_dict[col] + 1) * sign
                form += '+'
            form += '\n'
        return form
157593
def assemble_cx():
    """"""
    if request.method == 'OPTIONS':
        return {}
    response = request.body.read().decode('utf-8')
    body = json.loads(response)
    stmts_json = body.get('statements')
    stmts = stmts_from_json(stmts_json)
    ca = CxAssembler(stmts)
    model_str = ca.make_model()
    res = {'model': model_str}
    return res
254532
def as_rest_table(data, full=False):
    
    data = data if data else [["No Data"]]
    table = []
    # max size of each column
    sizes = list(map(max, zip(*[[len(str(elt)) for elt in member] for member in data])))
    num_elts = len(sizes)

    if full:
        start_of_line = "| "
        vertical_separator = " | "
        end_of_line = " |"
        line_marker = "-"
    else:
        start_of_line = ""
        vertical_separator = "  "
        end_of_line = ""
        line_marker = "="

    meta_template = vertical_separator.join(
        ["{{{{{0}:{{{0}}}}}}}".format(i) for i in range(num_elts)]
    )
    template = "{0}{1}{2}".format(
        start_of_line, meta_template.format(*sizes), end_of_line
    )
    # determine top/bottom borders
    if full:
        to_separator = maketrans("| ", "+-")
    else:
        to_separator = maketrans("|", "+")
    start_of_line = start_of_line.translate(to_separator)
    vertical_separator = vertical_separator.translate(to_separator)
    end_of_line = end_of_line.translate(to_separator)
    separator = "{0}{1}{2}".format(
        start_of_line,
        vertical_separator.join([x * line_marker for x in sizes]),
        end_of_line,
    )
    # determine header separator
    th_separator_tr = maketrans("-", "=")
    start_of_line = start_of_line.translate(th_separator_tr)
    line_marker = line_marker.translate(th_separator_tr)
    vertical_separator = vertical_separator.translate(th_separator_tr)
    end_of_line = end_of_line.translate(th_separator_tr)
    th_separator = "{0}{1}{2}".format(
        start_of_line,
        vertical_separator.join([x * line_marker for x in sizes]),
        end_of_line,
    )
    # prepare result
    table.append(separator)
    # set table header
    titles = data[0]
    table.append(template.format(*titles))
    table.append(th_separator)

    for d in data[1:-1]:
        table.append(template.format(*d))
        if full:
            table.append(separator)
    table.append(template.format(*data[-1]))
    table.append(separator)

    return "\n".join(table)