Coder Social home page Coder Social logo

esheldon / fitsio Goto Github PK

View Code? Open in Web Editor NEW
132.0 13.0 57.0 19.46 MB

A python package for FITS input/output wrapping cfitsio

License: GNU General Public License v2.0

C 78.10% TeX 12.61% Fortran 1.69% C++ 0.01% Shell 0.19% Smarty 0.05% Makefile 0.15% CMake 0.18% Python 4.24% Lex 0.22% Yacc 2.58%
python cfitsio astrophysics astronomy

fitsio's Introduction

A python library to read from and write to FITS files.

Build Status (master) tests

Description

This is a python extension written in c and python. Data are read into numerical python arrays.

A version of cfitsio is bundled with this package, there is no need to install your own, nor will this conflict with a version you have installed.

Some Features

  • Read from and write to image, binary, and ascii table extensions.
  • Read arbitrary subsets of table columns and rows without loading all the data to memory.
  • Read image subsets without reading the whole image. Write subsets to existing images.
  • Write and read variable length table columns.
  • Read images and tables using slice notation similar to numpy arrays. This is like a more powerful memmap, since it is column-aware for tables.
  • Append rows to an existing table. Delete row sets and row ranges. Resize tables, or insert rows.
  • Query the columns and rows in a table.
  • Read and write header keywords.
  • Read and write images in tile-compressed format (RICE,GZIP,PLIO,HCOMPRESS).
  • Read/write gzip files directly. Read unix compress (.Z,.zip) and bzip2 (.bz2) files.
  • TDIM information is used to return array columns in the correct shape.
  • Write and read string table columns, including array columns of arbitrary shape.
  • Read and write complex, bool (logical), unsigned integer, signed bytes types.
  • Write checksums into the header and verify them.
  • Insert new columns into tables in-place.
  • Iterate over rows in a table. Data are buffered for efficiency.
  • python 3 support, including python 3 strings

Examples

import fitsio
from fitsio import FITS,FITSHDR

# Often you just want to quickly read or write data without bothering to
# create a FITS object.  In that case, you can use the read and write
# convienience functions.

# read all data from the first hdu that has data
filename='data.fits'
data = fitsio.read(filename)

# read a subset of rows and columns from a table
data = fitsio.read(filename, rows=[35,1001], columns=['x','y'], ext=2)

# read the header
h = fitsio.read_header(filename)
# read both data and header
data,h = fitsio.read(filename, header=True)

# open the file and write a new binary table extension with the data
# array, which is a numpy array with fields, or "recarray".

data = np.zeros(10, dtype=[('id','i8'),('ra','f8'),('dec','f8')])
fitsio.write(filename, data)

# Write an image to the same file. By default a new extension is
# added to the file.  use clobber=True to overwrite an existing file
# instead.  To append rows to an existing table, see below.

fitsio.write(filename, image)

#
# the FITS class gives the you the ability to explore the data, and gives
# more control
#

# open a FITS file for reading and explore
fits=fitsio.FITS('data.fits')

# see what is in here; the FITS object prints itself
print(fits)

file: data.fits
mode: READONLY
extnum hdutype         hduname
0      IMAGE_HDU
1      BINARY_TBL      mytable

# at the python or ipython prompt the fits object will
# print itself
>>> fits
file: data.fits
... etc

# explore the extensions, either by extension number or
# extension name if available
>>> fits[0]

file: data.fits
extension: 0
type: IMAGE_HDU
image info:
  data type: f8
  dims: [4096,2048]

# by name; can also use fits[1]
>>> fits['mytable']

file: data.fits
extension: 1
type: BINARY_TBL
extname: mytable
rows: 4328342
column info:
  i1scalar            u1
  f                   f4
  fvec                f4  array[2]
  darr                f8  array[3,2]
  dvarr               f8  varray[10]
  s                   S5
  svec                S6  array[3]
  svar                S0  vstring[8]
  sarr                S2  array[4,3]

# See bottom for how to get more information for an extension

# [-1] to refers the last HDU
>>> fits[-1]
...

# if there are multiple HDUs with the same name, and an EXTVER
# is set, you can use it.  Here extver=2
#    fits['mytable',2]


# read the image from extension zero
img = fits[0].read()
img = fits[0][:,:]

# read a subset of the image without reading the whole image
img = fits[0][25:35, 45:55]


# read all rows and columns from a binary table extension
data = fits[1].read()
data = fits['mytable'].read()
data = fits[1][:]

# read a subset of rows and columns. By default uses a case-insensitive
# match. The result retains the names with original case.  If columns is a
# sequence, a numpy array with fields, or recarray is returned
data = fits[1].read(rows=[1,5], columns=['index','x','y'])

# Similar but using slice notation
# row subsets
data = fits[1][10:20]
data = fits[1][10:20:2]
data = fits[1][[1,5,18]]

# Using EXTNAME and EXTVER values
data = fits['SCI',2][10:20]

# Slicing with reverse (flipped) striding
data = fits[1][40:25]
data = fits[1][40:25:-5]

# all rows of column 'x'
data = fits[1]['x'][:]

# Read a few columns at once. This is more efficient than separate read for
# each column
data = fits[1]['x','y'][:]

# General column and row subsets.
columns=['index','x','y']
rows = [1, 5]
data = fits[1][columns][rows]

# data are returned in the order requested by the user
# and duplicates are preserved
rows = [2, 2, 5]
data = fits[1][columns][rows]

# iterate over rows in a table hdu
# faster if we buffer some rows, let's buffer 1000 at a time
fits=fitsio.FITS(filename,iter_row_buffer=1000)
for row in fits[1]:
    print(row)

# iterate over HDUs in a FITS object
for hdu in fits:
    data=hdu.read()

# Note dvarr shows type varray[10] and svar shows type vstring[8]. These
# are variable length columns and the number specified is the maximum size.
# By default they are read into fixed-length fields in the output array.
# You can over-ride this by constructing the FITS object with the vstorage
# keyword or specifying vstorage when reading.  Sending vstorage='object'
# will store the data in variable size object fields to save memory; the
# default is vstorage='fixed'.  Object fields can also be written out to a
# new FITS file as variable length to save disk space.

fits = fitsio.FITS(filename,vstorage='object')
# OR
data = fits[1].read(vstorage='object')
print(data['dvarr'].dtype)
    dtype('object')


# you can grab a FITS HDU object to simplify notation
hdu1 = fits[1]
data = hdu1['x','y'][35:50]

# get rows that satisfy the input expression.  See "Row Filtering
# Specification" in the cfitsio manual (note no temporary table is
# created in this case, contrary to the cfitsio docs)
w=fits[1].where("x > 0.25 && y < 35.0")
data = fits[1][w]

# read the header
h = fits[0].read_header()
print(h['BITPIX'])
    -64

fits.close()


# now write some data
fits = FITS('test.fits','rw')


# create a rec array.  Note vstr
# is a variable length string
nrows=35
data = np.zeros(nrows, dtype=[('index','i4'),('vstr','O'),('x','f8'),
                              ('arr','f4',(3,4))])
data['index'] = np.arange(nrows,dtype='i4')
data['x'] = np.random.random(nrows)
data['vstr'] = [str(i) for i in xrange(nrows)]
data['arr'] = np.arange(nrows*3*4,dtype='f4').reshape(nrows,3,4)

# create a new table extension and write the data
fits.write(data)

# can also be a list of ordinary arrays if you send the names
array_list=[xarray,yarray,namearray]
names=['x','y','name']
fits.write(array_list, names=names)

# similarly a dict of arrays
fits.write(dict_of_arrays)
fits.write(dict_of_arrays, names=names) # control name order

# append more rows to the table.  The fields in data2 should match columns
# in the table.  missing columns will be filled with zeros
fits[-1].append(data2)

# insert a new column into a table
fits[-1].insert_column('newcol', data)

# insert with a specific colnum
fits[-1].insert_column('newcol', data, colnum=2)

# overwrite rows
fits[-1].write(data)

# overwrite starting at a particular row. The table will grow if needed
fits[-1].write(data, firstrow=350)


# create an image
img=np.arange(2*3,dtype='i4').reshape(2,3)

# write an image in a new HDU (if this is a new file, the primary HDU)
fits.write(img)

# write an image with rice compression
fits.write(img, compress='rice')

# control the compression
fimg=np.random.normal(size=2*3).reshape(2, 3)
fits.write(img, compress='rice', qlevel=16, qmethod='SUBTRACTIVE_DITHER_2')

# lossless gzip compression for integers or floating point
fits.write(img, compress='gzip', qlevel=None)
fits.write(fimg, compress='gzip', qlevel=None)

# overwrite the image
fits[ext].write(img2)

# write into an existing image, starting at the location [300,400]
# the image will be expanded if needed
fits[ext].write(img3, start=[300,400])

# change the shape of the image on disk
fits[ext].reshape([250,100])

# add checksums for the data
fits[-1].write_checksum()

# can later verify data integridy
fits[-1].verify_checksum()

# you can also write a header at the same time.  The header can be
#   - a simple dict (no comments)
#   - a list of dicts with 'name','value','comment' fields
#   - a FITSHDR object

hdict = {'somekey': 35, 'location': 'kitt peak'}
fits.write(data, header=hdict)
hlist = [{'name':'observer', 'value':'ES', 'comment':'who'},
         {'name':'location','value':'CTIO'},
         {'name':'photometric','value':True}]
fits.write(data, header=hlist)
hdr=FITSHDR(hlist)
fits.write(data, header=hdr)

# you can add individual keys to an existing HDU
fits[1].write_key(name, value, comment="my comment")

# Write multiple header keys to an existing HDU. Here records
# is the same as sent with header= above
fits[1].write_keys(records)

# write special COMMENT fields
fits[1].write_comment("observer JS")
fits[1].write_comment("we had good weather")

# write special history fields
fits[1].write_history("processed with software X")
fits[1].write_history("re-processed with software Y")

fits.close()

# using a context, the file is closed automatically after leaving the block
with FITS('path/to/file') as fits:
    data = fits[ext].read()

    # you can check if a header exists using "in":
    if 'blah' in fits:
        data=fits['blah'].read()
    if 2 in f:
        data=fits[2].read()

# methods to get more information about extension.  For extension 1:
f[1].get_info()             # lots of info about the extension
f[1].has_data()             # returns True if data is present in extension
f[1].get_extname()
f[1].get_extver()
f[1].get_extnum()           # return zero-offset extension number
f[1].get_exttype()          # 'BINARY_TBL' or 'ASCII_TBL' or 'IMAGE_HDU'
f[1].get_offsets()          # byte offsets (header_start, data_start, data_end)
f[1].is_compressed()        # for images. True if tile-compressed
f[1].get_colnames()         # for tables
f[1].get_colname(colnum)    # for tables find the name from column number
f[1].get_nrows()            # for tables
f[1].get_rec_dtype()        # for tables
f[1].get_rec_column_descr() # for tables
f[1].get_vstorage()         # for tables, storage mechanism for variable
                            # length columns

# public attributes you can feel free to change as needed
f[1].lower           # If True, lower case colnames on output
f[1].upper           # If True, upper case colnames on output
f[1].case_sensitive  # if True, names are matched case sensitive

Installation

The easiest way is using pip or conda. To get the latest release

pip install fitsio

# update fitsio (and everything else)
pip install fitsio --upgrade

# if pip refuses to update to a newer version
pip install fitsio --upgrade --ignore-installed

# if you only want to upgrade fitsio
pip install fitsio --no-deps --upgrade --ignore-installed

# for conda, use conda-forge
conda install -c conda-forge fitsio

You can also get the latest source tarball release from

https://pypi.python.org/pypi/fitsio

or the bleeding edge source from github or use git. To check out the code for the first time

git clone https://github.com/esheldon/fitsio.git

Or at a later time to update to the latest

cd fitsio
git update

Use tar xvfz to untar the file, enter the fitsio directory and type

python setup.py install

optionally with a prefix

python setup.py install --prefix=/some/path

Requirements

  • python 2 or python 3
  • a C compiler and build tools like make, patch, etc.
  • numpy (See the note below. Generally, numpy 1.11 or later is better.)

Do not use numpy 1.10.0 or 1.10.1

There is a serious performance regression in numpy 1.10 that results in fitsio running tens to hundreds of times slower. A fix may be forthcoming in a later release. Please comment here if this has already impacted your work numpy/numpy#6467

Tests

The unit tests should all pass for full support.

pytest fitsio

Some tests may fail if certain libraries are not available, such as bzip2. This failure only implies that bzipped files cannot be read, without affecting other functionality.

Notes on Usage and Features

cfitsio bundling

We bundle cfitsio partly because many deployed versions of cfitsio in the wild do not have support for interesting features like tiled image compression. Bundling a version that meets our needs is a safe alternative.

array ordering

Since numpy uses C order, FITS uses fortran order, we have to write the TDIM and image dimensions in reverse order, but write the data as is. Then we need to also reverse the dims as read from the header when creating the numpy dtype, but read as is.

distutils vs setuptools

As of version 1.0.0, fitsio has been transitioned to setuptools for packaging and installation. There are many reasons to do this (and to not do this). However, at a practical level, what this means for you is that you may have trouble uninstalling older versions with pip via pip uninstall fitsio. If you do, the best thing to do is to manually remove the files manually. See this stackoverflow question for example.

python 3 strings

As of version 1.0.0, fitsio now supports Python 3 strings natively. This support means that for Python 3, native strings are read from and written correctly to FITS files. All byte string columns are treated as ASCII-encoded unicode strings as well. For FITS files written with a previous version of fitsio, the data in Python 3 will now come back as a string and not a byte string. Note that this support is not the same as full unicode support. Internally, fitsio only supports the ASCII character set.

TODO

  • HDU groups: does anyone use these? If so open an issue!

fitsio's People

Contributors

albireox avatar at88mph avatar aurel32 avatar beckermr avatar cbonnett avatar conda-forge-daemon avatar craigloomis avatar dstndstn avatar edwardbetts avatar erykoff avatar esheldon avatar imichka avatar kadrlica avatar liuxiang88 avatar lorddavidiii avatar menanteau avatar ntessore avatar olebole avatar rainwoodman avatar rmjarvis avatar saimn avatar sbailey avatar simonrw avatar taldcroft avatar ussegliog avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fitsio's Issues

Bug in cfitsio reading very large fpacked files

When reading from very large fpacked files, a memory leak occurs

I've tested this does not happen for smaller files

This needs to be reported upstream to the cfitsio maintainer

For now a workaround is to close and reopen the file periodically

Weird issue: FITS header with value "object" gets converted into the python TYPE 'object'!

I have a DECam image with "OBSTYPE = 'object'"

modhead /global/homes/d/dstn/desi/imaging/redux/decam/proc/20130330/C01/zband/DECam_00192404.01.p.w.fits OBSTYPE
OBSTYPE = 'object ' / Observation type

I read the header via

hdr = fitsio.read_header(fn)

and then try to write it out via

fitsio.write(outfn, None, header=hdr)

and it prints:

warning, keyword 'OBSTYPE' has non-standard value type <type 'type'>, Converting to string: '<type 'object'>'

and the output file has this weird value in the header:

modhead headers/20130330/C01/zband/DECam_00192404.01.p.w.fits OBSTYPE
OBSTYPE = '<type ''object''>' / Observation type

It appears to be coming from (this is not the root cause, but I'm getting there...):

fitslib.py:1204 -> hdr = FITSHDR(records_in)

where, in this case, records_in is already a FITSHDR.

If I can figure this out I'll send a pull request.

Please add a --with-system-fitsio flag to all setup.py targets

Currently (in 0.9.8), there is a flag --with-system-fitsio that works for the build_ext argument of setup.py. This is not very useful, since when I do a python setup.py build or python setup.py install, the flag cannot be added, and the extension is then rebuild with the internal copy of cfitsio.
It would be good, if build and install also would accept this flag. I need it for packaging on Debian #40.

Please consider creating a Debian/Ubuntu package

Hi,

I just read about python-fitsio on the astropy mailing list, and I wonder if you would like to create Debian/Ubuntu package?

Ideally, this should be done within the Debian Astronomy Working group . You could do it yourself, or anyone else can volunteer. As far as I investigated the package, the Debian package creation would be quite easy, so this can even be a task for a beginner.

The only change to the source code I would see now is to build it against the cfitsio library provided by Debian (which is version 3370 in the moment). There is already a pull request #27 for this. @esheldon the package require to be linked to some minimal cfitsio version, so we can make sure that all features are supported.

Please contact me directly, or via the mailing list if you need further information. We can guide you through the full process, and also finally upload your package to Debian. Once it is in Debian, it will automatically migrate to Distributions like Ubuntu or Mint.

Best regards

Ole

bug parsing 1-byte logical columns

An example Tractor catalog file from the DECam Legacy Survey is available here:

http://portal.nersc.gov/project/cosmo/data/legacysurvey/dr1/tractor/000/tractor-0001m002.fits

It contains a binary table that has some TFORMnn = 'L' columns for 1-byte LOGICAL, e.g. the column 'brick_primary'. These appear to be mis-parsed by fitsio, resulting in all False values. astropy.io.fits has many of these as True.

import fitsio
from astropy.io import fits

infile = "/project/projectdirs/cosmo/data/legacysurvey/dr1/tractor/000/tractor-0001p027.fits"
d1 = fitsio.read(infile)
d2 = fits.getdata(infile)

len(d1), np.count_nonzero(d1['brick_primary'])  #- (4984, 0)
len(d2), np.count_nonzero(d2['brick_primary'])  #- (4984, 4548)

howto: write out a cutout subset of an image with a new header

Hi Erin,

I want to use use fitsio to create a 'FITs object' in memory of a cutout.

With pyfits I do this:

fh = pyfits.open(filename)
head = fh[ext].header.copy()
...
various header manipulations to work out the pixel ranges
and update the new header
...
cutout = fh[ext].data[ymin:ymax,xmin:xmax]
newfh = pyfits.PrimaryHDU(data=cutout,header=head)

with fitsio I do

fh=fitsio.FITS(filename)
head = fh[ext].read_header()
....
work out the pixel range I want and update the header
....
cutout=fh[ext][ymin:ymax,xmin:xmax]

how do I make a FITs object from cutout, newhead that I can then pass out of my
function?

Also how do I write this to a new fits file?

This would be a useful example of how to create and write out a image cutout.

Thanks, r.

Fitsio works (only) with unaligned data structures

On systems like Sparc and (partly) ARM it is required that data pointers are aligned, and also on other architectures unaligned data may lead to a lower performance.
Numpy however seems to create non-aligned data structures which cause the unit tests to fail (segfault) under Sparc64 and armhf platforms.
Aligning the data in the tests does not work yet, since this creates an unknown column type "V" for table data.

Failure on (invalid) FITS tables from SDSS CasJobs

Hi Erin,

I found yesterday that the SDSS CasJobs system produces (slightly) invalid FITS tables: for string columns, with formats such as TFORM1 = '6A' , they have TDIM1 = '(1)'. Fitsverify complains about it, reporting the TDIM card as an error:

fitsverify surv.fits
fitsverify 4.16 (CFITSIO V3.310)
--------------------------------
[...]
=================== HDU 2: BINARY Table ====================

*** Error: Keyword #10, TDIM1: illegal TDIMn keyword value

And fitsio bombs trying to read it:

python -c "import fitsio; fitsio.read('surv.fits')"
Traceback (most recent call last):
File "", line 1, in
File "/home/dstn/software/fitsio-git/lib/python/fitsio/fitslib.py", line 111, in read
data = fits[item].read(**keys)
File "/home/dstn/software/fitsio-git/lib/python/fitsio/fitslib.py", line 1607, in read
data = self.read_all(**keys)
File "/home/dstn/software/fitsio-git/lib/python/fitsio/fitslib.py", line 1739, in read_all
dtype, offsets, isvar = self.get_rec_dtype(**keys)
File "/home/dstn/software/fitsio-git/lib/python/fitsio/fitslib.py", line 2437, in get_rec_dtype
dt,isvar = self.get_rec_column_descr(colnum, vstorage)
File "/home/dstn/software/fitsio-git/lib/python/fitsio/fitslib.py", line 2489, in get_rec_column_descr
shape = tdim2shape(tdim, is_string=(npy_type[0] == 'S'))
File "/home/dstn/software/fitsio-git/lib/python/fitsio/fitslib.py", line 2902, in tdim2shape
if len(tdim) > 1 or tdim[0] > 1:
TypeError: object of type 'NoneType' has no len()

And a little pdb'ing:

2900 def tdim2shape(tdim, is_string=False):
2901 shape=None
2902 -> if len(tdim) > 1 or tdim[0] > 1:
2903 if is_string:
2904 shape = list( reversed(tdim[1:]) )
2905 else:
2906 shape = list( reversed(tdim) )
2907
(Pdb) p tdim
None
(Pdb) up

/home/dstn/software/fitsio-git/lib/python/fitsio/fitslib.py(2489)get_rec_column_descr()
-> shape = tdim2shape(tdim, is_string=(npy_type[0] == 'S'))
(Pdb) l
2484 descr=(name,npy_type)
2485 else:
2486 descr=(name,npy_type,max_size)
2487 else:
2488 tdim = self._info['colinfo'][colnum]['tdim']
2489 -> shape = tdim2shape(tdim, is_string=(npy_type[0] == 'S'))
2490 if shape is not None:
2491 descr=(name,npy_type,shape)
2492 else:
2493 descr=(name,npy_type)
2494 return descr,isvar
(Pdb) p self._info['colinfo'][0]
{'repeat': 6L, 'tscale': 1.0, 'name': 'survey', 'tdim': None, 'tzero': 0.0, 'width': 1L, 'eqtype': 16L, 'tform': '6A', 'type': 16L}
(Pdb)

Anyway, not really your problem, but it would be convenient if you can see a way to work around it. I have reported it upstream to the SDSS Helpdesk.

cheers,
dustin

HISTORY, COMMENT and BLANK keywords

Is this fitsio module able to add multiple HISTORY, COMMENT or BLANK keywords to a header? I've tried adding with the write_key() method. I appears I can append values to a single HISTORY entry (for example), but then I have trouble reading it using the read_header() method.

Segfault reading ASCII table

To reproduce:

wget -O table1.fits http://cdsarc.u-strasbg.fr/viz-bin/nph-Cat/fits?J%2FApJ%2F686%2F749/table1.dat
import fitsio
fitsio.read("table1.fits", ext=1)

Doesn't segfault every time, just most times.

fitsio v0.9.7, Python 3.4 (anaconda), Linux.

Column slicing issues

When attempting the following code

import fitsio
f = fitsio.FITS('spec-3874-55280-0067.fits')
clolumn = f[2]['SUBCLASS']

column is returned as

file: ~/spec-3874-55280-0067.fits
  extension: 2
  type: BINARY_TBL
  rows: 1
  column subset:
    CLASS               S6  array[6]
    SUBCLASS           S21  array[21]
    U                   f4  array[5]
    L                   f8  
    B                   f8  

and attempting to take column[:] crashes iPython.

If I use

columns = f[2]['CLASS','SUBCLASS']

returns

file: ~/spec-3874-55280-0067.fits
  extension: 2
  type: BINARY_TBL
  rows: 1
  column subset:
    CLASS               S6  array[6]
    SUBCLASS           S21  array[21]

and columns[:] works fine in this case.

It looks like when specifying a single column, fitsio searches for any subset of the given column name.

issue writing data from a dict

I (@esheldon) am posting this for the user "Ivan"

Indeed, I was probably using it wrong, but maybe its error message can
be improved not to cause a confusion in similar cases, even though my
use case is somewhat weird. Here's the minimal test case I had
problems with (tested in numpy 1.8.1 and 1.9.2, fitsio 0.9.7):

import numpy as np
from fitsio import FITS

fits = FITS('test.fits', 'rw')
arr = [1L, 2L]
nparr = np.array(arr)
nulls = np.equal(arr, None)
nparr[nulls] = -1 # or whatever your FITS null value is
# arr = nparr.astype('int64') # uncomment this line and comment the
# next one to make it work
arr = np.array(nparr, dtype='int64')
fits.write({'test': arr})
fits.close()

This results in:

---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
/home/user/<ipython-input-92-b693c45fa56d> in <module>()
----> 1 fits.write({'test': arr})

/usr/local/lib/python2.7/dist-packages/fitsio/fitslib.pyc in
write(self, data, units, extname, extver, compress, tile_dims, header,
names, table_type, **keys)
    446                              extname=extname, extver=extver,
header=header,
    447                              names=names,
--> 448                              table_type=table_type)
    449
    450

/usr/local/lib/python2.7/dist-packages/fitsio/fitslib.pyc in
write_table(self, data, table_type, names, formats, units, extname,
extver, header)
    714             self[-1]._update_info()
    715
--> 716         self[-1].write(data,names=names)
    717
    718     def create_table_hdu(self, data=None, dtype=None,

/usr/local/lib/python2.7/dist-packages/fitsio/fitslib.pyc in
write(self, data, **keys)
   1506                 firstrow=keys.get('firstrow',0)
   1507                 self._FITS.write_columns(self._ext+1,
nonobj_colnums, nonobj_arrays,
-> 1508                                          firstrow=firstrow+1)
   1509
   1510         # writing the object arrays always occurs the same way


TypeError: Unsupported numpy table datatype 9

I'll explain why I needed this seemingly excessive numpy operations. I
have a list of long integers as an input and I need to check it for
None values (even though the test case does not have it), that's why I
make numpy array of objects nparr first and set Nones in it to a
dedicated integer value (let me know if there's a way to avoid this in
case your input has missing values). Then I naively expected that
doing np.array(nparr, dtype='int64') casts my array from numpy array
of objects to the array of long integers. I still do not get this
numpy magics, but if I change the type casting to the line which is
commented above arr = nparr.astype('int64') the fitsio error is
gone. I initially thought this weird problem has something to do with
int64 because changing data type in question to int32 also makes this
error disappear.

As for performance, with fitsio I'm now bottlenecked by my SQL
database which is how I expect things to happen with complex data
models. This is still not the case for astropy 1.0.2, which
bottlenecks my FITS writing procedure. I can prepare a test case if
someone is interested.

Compile and link args for pure 64-bit python on OS X

John Parejko noted that he was using a pure 64-bit python on darwin.
The last time I had a mac we needed to compile and link with

-arch i386 -arch x86_64

But on his version he had to remove the i386 to it to work.

Need to understand how to automatically figure this out during install.

test failures for fitsio on both linux and mac osx

The master branch of fitsio currently fails the test suite. I tried it on my mac and on linux machines at SLAC. On my mac, it appears that the library is not reading/writing little versus big endian correctly. See the output below. These tests pass in v0.9.7 and so the bug must be in commits after this release.

======================================================================
FAIL: testImageSlice (fitsio.test.TestReadWrite)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/u/ki/beckermr/.local/lib/python2.7/site-packages/fitsio/test.py", line 423, in testImageSlice
    self.compare_array(data[4:12,9:17], rdata, "images")
  File "/u/ki/beckermr/.local/lib/python2.7/site-packages/fitsio/test.py", line 1490, in compare_array
    self.assertEqual(w.size,0,"testing array '%s' dim %d are equal" % (name,i))
AssertionError: testing array 'images' dim 0 are equal

======================================================================
FAIL: testImageWriteRead (fitsio.test.TestReadWrite)
----------------------------------------------------------------------
Traceback (most recent call last):
  File "/u/ki/beckermr/.local/lib/python2.7/site-packages/fitsio/test.py", line 302, in testImageWriteRead
    self.compare_array(data, rdata, "images")
  File "/u/ki/beckermr/.local/lib/python2.7/site-packages/fitsio/test.py", line 1490, in compare_array
    self.assertEqual(w.size,0,"testing array '%s' dim %d are equal" % (name,i))
AssertionError: testing array 'images' dim 0 are equal

----------------------------------------------------------------------
Ran 27 tests in 0.725s

FAILED (failures=2)

testRiceTileCompressedWriteRead crashes on 32-bit machines

When I uploaded the python-fitsio package to Debian, I discoveres that on 32-bit machines (so far i386, powerpc) testRiceTileCompressedWriteRead crashes (full log from a Debian build):

testRiceTileCompressedWriteRead (fitsio.test.TestReadWrite) ...
*** Error in `python2.7': free(): invalid next size (fast): 0x08ac69c8 ***
======= Backtrace: =========
/lib/i386-linux-gnu/libc.so.6(+0x68b13)[0xf75a6b13]
/lib/i386-linux-gnu/libc.so.6(+0x6ed70)[0xf75acd70]
/lib/i386-linux-gnu/libc.so.6(+0x6f521)[0xf75ad521]
fitsio/_fitsio_wrap.so(+0x13f97)[0xf614df97]
python2.7(PyCFunction_Call+0x8e)[0x80f96ae]
python2.7(PyEval_EvalFrameEx+0x695c)[0x8112a6c]
python2.7(PyEval_EvalCodeEx+0x1fb)[0x810a8fb]
[...]

The Debian build was done with the (mainly unpatched) cfitsio-3380 that is in Debian unstable; I could however verify that this also happens with the cfitsio that comes fits the fitsio sources. 64-bit architectures compile fine so far (except sparc64).
With gdb, I could get the following stack trace:

(gdb) where
#0  0xf7dea6ec in raise () from /lib/i386-linux-gnu/libc.so.6
#1  0xf7debca7 in abort () from /lib/i386-linux-gnu/libc.so.6
#2  0xf7e27b18 in ?? () from /lib/i386-linux-gnu/libc.so.6
#3  0xf7e2dd70 in ?? () from /lib/i386-linux-gnu/libc.so.6
#4  0xf7e2e521 in ?? () from /lib/i386-linux-gnu/libc.so.6
#5  0xf6b99ba7 in set_compression (status=<optimized out>, 
    tile_dims_obj=<optimized out>, comptype=<optimized out>, fits=0x878c188)
    at fitsio/fitsio_pywrap.c:1163
#6  PyFITSObject_create_image_hdu (self=0xf7d91540, args=0xf68eb20c, 
    kwds=0xf69261c4) at fitsio/fitsio_pywrap.c:1266
#7  0x080f96ae in PyCFunction_Call ()
#8  0x08112a6c in PyEval_EvalFrameEx ()
#9  0x0810a8fb in PyEval_EvalCodeEx ()
#10 0x08111dc0 in PyEval_EvalFrameEx ()
[...]

Add support for random groups

Random groups is still how some radio astronomy data gets in to classic AIPS. This includes single dish data. We have some legacy c code using the cfitsio library that we'd like to migrate to python. pyfits handling of random groups appears to be similar to pyfits tables handling in that additional data can't be added to the HDU after creation.

Added fixes for compiling with mingw under windows 8

Hey guys,

I had to compile the library for windows and found two problems. First mingw must link to libgcc.a as otherwise the linker can't resolve two symbols.
I added this to setup.py:

if platform.system()=='Darwin':
extra_compile_args=['-arch','i386','-arch','x86_64']
extra_link_args=['-arch','i386','-arch','x86_64']
else:
extra_compile_args=[]
extra_link_args=['C:\MinGW\lib\gcc\mingw32\4.8.1\libgcc.a', ''] # HACK TO GET IT COMPILE ON MINGW

Second, in drvrfile.c

ifdef HAVE_FTRUNCATE

if defined(unix) || defined(unix) || defined(__unix)

include unistd.h /* needed for getcwd prototype on unix machines */

endif

endif

won't include _ftruncate under windows. i fixed it by removing all the preprocessor statements so that unistd.h will be included under mingw

hope that helps

I think you assume arrays are contiguous and in C order

Hi,

I recently encountered a problem where I'm building up a vector column in a BINTABLE like so:

X = []
for c in range(NColumns):
X.append([42] * NRows)
X = np.array(X).T
fitsio.FITS(fn,'rw').write([X], names=['X'])

Notice that I'm building it up by columns, and then using the ".T" view to transpose it, so it has the correct shape, but the memory isn't moved around, so in memory it is in Fortran order.

I think it should be possible to fix this with a PyArray_FromAny call;

http://docs.scipy.org/doc/numpy/reference/c-api.array.html?highlight=check#PyArray_FromAny

I'm looking at creating a patch but just thought I'd post this issue before I got started in case you've got different ideas.

cheers,
dustin

fitsio-v0.9.7 Windows install problem (pip or setup.py)

Collecting fitsio
Using cached fitsio-0.9.7.tar.gz
Complete output from command python setup.py egg_info:
'sh' is not recognized as an internal or external command,
operable program or batch file.
Traceback (most recent call last):
File "", line 20, in
File "C:\myuserpath\AppData\Local\Temp\pip-build-tm1tpw_t\fitsio\setup.py", line 62, in
configure_cfitsio()
File "C:\myuserpath\AppData\Local\Temp\pip-build-tm1tpw_t\fitsio\setup.py", line 42, in configure_cfitsio
raise ValueError("could not configure cfitsio %s" % cfitsio_version)
ValueError: could not configure cfitsio 3370

travis failing on conda update

Here is the error

$ conda update --yes conda

/home/travis/build.sh: line 41: conda: command not found

The command "conda update --yes conda" failed and exited with 127 during .

Reading specific elements from binary table column arrays

When reading columns from a binary FITS table, if a column is actually an array (e.g. the MAG_APER column in SExtractor output is an array of 12 floats) it would be nice to be able to specify particular elements to read, e.g. read only MAG_APER[4].
Thanks!

"'numpy/arrayobject.h' file not found" error compiling on Mac OS X 10.10.3

Hey Erin!

Trying to install the master branch of fitsio threw the following error:

python setup.py install
[snip]
creating build/lib.macosx-10.10-x86_64-2.7
creating build/lib.macosx-10.10-x86_64-2.7/fitsio
copying fitsio/__init__.py -> build/lib.macosx-10.10-x86_64-2.7/fitsio
copying fitsio/fitslib.py -> build/lib.macosx-10.10-x86_64-2.7/fitsio
copying fitsio/test.py -> build/lib.macosx-10.10-x86_64-2.7/fitsio
copying fitsio/util.py -> build/lib.macosx-10.10-x86_64-2.7/fitsio
running build_ext
building 'fitsio._fitsio_wrap' extension
gcc -fno-strict-aliasing -fno-common -dynamic -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -I/usr/local/include -I/usr/local/opt/sqlite/include -I/usr/local/Cellar/python/2.7.10/Frameworks/Python.framework/Versions/2.7/include/python2.7 -c fitsio/fitsio_pywrap.c -o build/temp.macosx-10.10-x86_64-2.7/fitsio/fitsio_pywrap.o -arch x86_64
fitsio/fitsio_pywrap.c:28:10: fatal error: 'numpy/arrayobject.h' file not found
#include <numpy/arrayobject.h> 
         ^
1 error generated.
error: command 'gcc' failed with exit status 1

I solved this by changing the following lines of setup.py from

ext=Extension("fitsio._fitsio_wrap", 
              sources,
              extra_objects=extra_objects,
              extra_compile_args=extra_compile_args, 
              extra_link_args=extra_link_args)

to

ext=Extension("fitsio._fitsio_wrap", 
              sources,
              extra_objects=extra_objects,
              extra_compile_args=extra_compile_args, 
              extra_link_args=extra_link_args,
              include_dirs=[cfitsio_dir,numpy.get_include()])

and everything built properly. I can submit a PR if you'd like.

file corruption with append()

I traced an odd bug to the following piece of code:

fits = fitsio.FITS(fitsfile, 'rw')
for counter in range(N):
    # initialized
    data = np.empty(n_gal, dtype=(...))
    # filled with some results
    data = fromSomeFancyCalculation()
    if counter == 0:
            fits.write(data)
    else:
            fits[-1].append(data)

The data portion of some of the entries has the right format, but the content is jumbled. I tried to reproduce it by working with the same input data, but the problem is intermittent. I could not confirm completely, but it seems that it's always entire blocks of data being corrupted, and the next call to fits[-1].append(data) works again as intended.

My suspicion is that append() tries to write data from a previous iteration that is already overwritten by data = np.empty(). However, there's no handle to wait for the completion of append(), right?

speed issues after install/upgrade of astropy and numpy

I recently upgraded astropy using pip, which installed version 1.0.5. It also caused an upgrade of numpy to 1.10.0. I then noticed that my use of fitsio was dramatically slower. I'm using fitsio to read a binary table HDU (single dish convention) and using astropy.fits.io (pyfits) to write out a random group FITS file. The fitsio speed issue is on a row iterator through that binary table with an iter_row_buffer size of 1000 rows [but that value isn't that important for values > 50 in previous tests I've done on this file]. The speed increased by close to 2 orders of magnitude (< 1 s to iterate through the file before to > 20 s now; that's just code involving just the fitsio row iterator - no direct use of astropy/pyfits or numpy).

I tried upgrading fitsio using pip (which brought it to 0.9.7 from 0.9.3 and also triggered a upgrade of numpy to 1.10.0.post2, not exactly the same as 1.10.0 that upgrading astropy triggered) with no change in speeds. I finally tried installing from the tar of the 0.9.8rc release candidate. No change.

Have you seen or heard of anyone else with this problem? Is this pilot error on my part? Any suggestions on what I should try next? Thanks.

missing header keywords in TableHDU

I found that reading the header does not include TUNIT keywords in the value from :func:TableHDU.get_info but I could access through the :func:TableHDU.read_header method

redo build_ext

We should merge build_ext from @rainwoodman but it currently contains another commit of travis.yaml so it just want to get clarification of how to move forward

strings read from binary tables should have spaces replaced will \0s

If you start with a numpy string column with null padded strings, this is written to file with trailing spaces (as per the fits standard, these nulls are replaces with spaces).

However, when reading in the file from a binary table all the strings now have trailing spaces, but these should be replaced with \0s.

import fitsio
import numpy as np
test=np.zeros(2,dtype=[('A','S10')])
test['A']='hello'
print test
fitsio.write('testbin.fit',test,clobber=True)
test2=fitsio.read('testbin.fit',ext=1)
print test2

This results in:

[('hello',) ('hello',)]
[('hello     ',) ('hello     ',)]

Note that (a) this works with ascii tables, and (b) this works with pyfits. (I also note that on writing pyfits replaces all trailing spaces with \0s which is not standard fits, but results in binary tables that aren't space-padded with fitsio!)

Fixing this looks to be a bit of a challenge. Since the binary tables are read in through direct copying binary data into memory (for speed), there is no chance to replace the spaces with built-in cfitsio string reading routines. Yet, it does result in undesirable behavior.

Writing many small HDUs gets progressively slower

I am writing a FITS file with many small HDUs and have noticed that the time to write each HDU increases ~linearly with the number of HDUs already written. The following test program shows the behavior:

import numpy as np
import fitsio
import time

fits = fitsio.FITS('test.fits',mode=fitsio.READWRITE,clobber=True)
cube = np.zeros((8,8,8),dtype=np.float32)
now = time.time()
for i in range(2000):
    fits.write_image(cube)
    if (i+1)%100 == 0:
        last = now
        now = time.time()
        print '%6d %6.1f' % (i+1,10.*(now-last))
fits.close()

I find that writing the first HDU takes ~0.02ms but that this slows down to ~1.0ms for the 2000th HDU. If you set clobber=False above, you can check that what matters is the number of HDUs in the file, not the number written by the current process.

Any idea if this is something peculiar about my system, a feature of the cfitsio library, or possibly due to the python wrapping of cfitsio? Any suggestions for avoiding this slowdown? I would like to be able to write ~100K HDUs.

.fz format MEF extension reading problem

Hi Erin,

When I try to read a specific extension in fz format I get no result back.
I can read the uncompressed version of the file OK.

MacOS 10.8.4 (Mountain Lion)
python 2.7.3
numpy: 1.7.1
fitsio: 0.9.3rc2

e.g.
DES0226-0416_g.fits.fz

image = fitsio.read(infile) works fine
help(image)
Help on ndarray object:

ext=1
image, hdr = fitsio.read(infile, ext=ext, header=True)

help(image)
Help on NoneType object:

fitsio write too slow on some file systems

We recently encountered a weird problem writing new fits files (DECam images) using fitsio 0.9.7 on NCSA Blue Waters (which uses a Lustre file system). Reading and DECam CCD image (80Mb) takes no time, but writing a copy to a new file, takes a about 3 minutes. Repeating the same exercise using pyfits instead takes only ~5 seconds.

A similar delay is observed in our cosmology cluster at NCSA (which uses GPFS file system). Using fitsio it takes ~35 sec and pyfits only 6s.
A quick inspection using strace indicates that fitsio is doing a lot of read() while doing write()

Build cfitsio outside of setup.py running

When running the setup.py file e.g. to extract metadata or just download the package with pip --download <DIR> fitsio the setup script compiles the packaged version of cfitsio. It would be better to only build this during the install phase.

clean up exceptions

Either define FITSError and put everything there, or make some betterchoices about how to use built-in errors.

should file not found errors be FITSError or IOError?

Trouble reading array column data from table

Hi,

I started using your library a couple days ago because it seems use much less memory than pyfits when working with large tables. I also need to append rows to an existing table and fitsio seems great for that. However, I'm having trouble reading data out of my table correctly when I read a subset of rows.

For example, if I try to read a column DATA with type "f4 array[8192]":

fits[1].read(rows=(1200,),columns=('DATA',))

I get data but it is incorrect. I tried other approaches that also didn't work:
fits[1]['DATA'][1200]
fits[1]['DATA'][1200:1201]
fits[1].read_column('DATA',rows=(1200,))

If I read all the data in the table with the .read() method on the fits extension, it seems OK. This isn't an option when my table is very large.

Am I missing something? Any help is appreciated!

A start on supporting Logical columns

Hi,

I just ran across the issue that logical (boolean) columns in bintables don't seem to be supported. The following diff starts to address that -- it's good enough for my purposes, but doesn't cover all code paths.

diff --git a/fitsio/fitsio_pywrap.c b/fitsio/fitsio_pywrap.c
index 7beac58..fe9625a 100644
--- a/fitsio/fitsio_pywrap.c
+++ b/fitsio/fitsio_pywrap.c
@@ -614,6 +614,8 @@ npy_to_fits_table_type(int npy_dtype) {

     char mess[255];
     switch (npy_dtype) {
+        case NPY_BOOL:
+            return TLOGICAL;
         case NPY_UINT8:
             return TBYTE;
         case NPY_INT8:
@@ -2253,6 +2256,21 @@ PyFITSObject_read_column(struct PyFITSObject* self, PyObject* args) {
             set_ioerr_string_from_status(status);
             return NULL;
         }
+
+       /*  I thought I was hitting this code path, but nope; 10% chance this works
+       if (PyArray_ISBOOL(array)) {
+         printf("Boolean array -- converting data\n");
+         // cfitsio reads as char 'T'/'F' -- convert data array to 0/1.
+         npy_intp i;
+         npy_int8* bdata = (npy_int8*)data;
+         for (i=0; i<nrows; i++) {
+           printf("0x%x ", bdata[stride*i]);
+           bdata[stride * i] = ((char)(bdata[stride * i]) == 'T') ? 1 : 0;
+         }
+         printf("\n");
+       }
+       */
+         
     }
     Py_RETURN_NONE;
 }
diff --git a/fitsio/fitslib.py b/fitsio/fitslib.py
index 743029c..6b8cdfd 100644
--- a/fitsio/fitslib.py
+++ b/fitsio/fitslib.py
@@ -1776,6 +1779,10 @@ class FITSHDU:
                 self._rescale_array(array[name], 
                                     self._info['colinfo'][colnum]['tscale'], 
                                     self._info['colinfo'][colnum]['tzero'])
+                # cfitsio reads as characters 'T' and 'F' -- convert to real boolean
+                if array[name].dtype == numpy.bool:
+                    array[name] = (array[name].astype(numpy.int8) == ord('T'))
+                   
         lower=keys.get('lower',False)
         upper=keys.get('upper',False)
         if self.lower or lower:
@@ -3623,7 +3630,7 @@ _hdu_type_map = {IMAGE_HDU:'IMAGE_HDU',
 # no support yet for complex
 _table_fits2npy = {11:'u1',
                    12: 'i1',
-                   14: 'i1', # logical. Note pyfits uses this for i1, cfitsio casts to char*
+                   14: 'b1', # logical. Note pyfits uses this for i1, cfitsio casts to char*
                    16: 'S',
                    20: 'u2',
                    21: 'i2',
@@ -3646,6 +3653,7 @@ _table_fits2npy_ascii = {16: 'S',

 # for TFORM
 _table_npy2fits_form = {'u1':'B',
+                        'b1':'L',
                         'i1':'S', # gets converted to unsigned
                         'S' :'A',
                         'u2':'U', # gets converted to signed

Python 3

Do you plan to make fitsio Python 3 compatible?

Currently I get this error after fixing a few trivial print statement fixes:

$ python3.2 -c 'import fitsio; fitsio.test.test()'
Traceback (most recent call last):
  File "<string>", line 1, in <module>
  File "/Users/deil/Library/Python/3.2/lib/python/site-packages/fitsio/__init__.py", line 244, in <module>
    from . import fitslib
  File "/Users/deil/Library/Python/3.2/lib/python/site-packages/fitsio/fitslib.py", line 35, in <module>
    from . import _fitsio_wrap
ImportError: dlopen(/Users/deil/Library/Python/3.2/lib/python/site-packages/fitsio/_fitsio_wrap.so, 2): Symbol not found: _PyInt_AsLong
  Referenced from: /Users/deil/Library/Python/3.2/lib/python/site-packages/fitsio/_fitsio_wrap.so
  Expected in: flat namespace
 in /Users/deil/Library/Python/3.2/lib/python/site-packages/fitsio/_fitsio_wrap.so

test cfitsio3370 branch

This branch uses the new bundled cfitsio 3370. The tests in test.py pass but need more real world tests.

Existing image data not overwritten if different shape

Hi, I've been trying to replace the data in an image HDU with new values.
In the documentation for fitsio.fitslib.ImageHDU.write it states that

If data already exist in this HDU, they will be overwritten

This works if the new image data is the same shape as the old image data, but
not if they are different. The code below shows an example where this is the
case. Perhaps a call to fits_resize_img could be done conditionally in
PyFITSObject_write_image? I'm happy to look into this if I get time.

Thanks,
Simon

import fitsio
import numpy as np

initial_data = np.zeros((5, 5))
replacement_data = np.ones((6, 6))

# Sanity check
assert replacement_data.shape != initial_data.shape

# Write the initial data and let fitsio flush to disc
with fitsio.FITS('output.fits', 'rw', clobber=True) as outfile:
    outfile.write(initial_data)

# Update the image data, and flush to disc. As quoted in the source:
#  "If data already exist in this HDU, they will be overwritten"
# https://github.com/esheldon/fitsio/blob/20dc93976a75116d74b2c98896cbbc4ff3bfdefd/fitsio/fitslib.py#L2904
with fitsio.FITS('output.fits', 'rw') as outfile:
    outfile[0].write(replacement_data)

with fitsio.FITS('output.fits') as infile:
    image_shape = infile[0].get_info()['dims']

    # Passing this test means at least the first element was overwritten
    assert infile[0],read()[0][0] == replacement_data[0][0]

    # Check the image shape. A failed assertion means the new array shape is
    # different
    expected = list(map(long, replacement_data.shape))
    assert image_shape == expected, (
        'image shape: %s, expected: %s' % (image_shape, expected)
    )

Unable to read binary table bit X type

I have a binary table (from Chandra standard data products) that has a field with TFORM2 = '263X'. When I try to read this I get an exception (shown below). The file reads with astropy.io.fits just fine, but the table has around 900 columns and I see about 10-20 times slowdown relative to fitsio.read(). For my application this is a problem.

Am I doing anything wrong, or is there just no support for the X type in fitsio? I can provide a sample file on request.

In [2]: import fitsio

In [3]: t = fitsio.read('test.fits')
---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-3-0557584cf732> in <module>()
----> 1 t = fitsio.read('test.fits')

/home/aldcroft/.local/lib/python2.7/site-packages/fitsio/fitslib.pyc in read(filename, ext, extver, **keys)
     92         item=_make_item(ext, extver=extver)
     93 
---> 94         data = fits[item].read(**keys)
     95         if header:
     96             h = fits[item].read_header()

/home/aldcroft/.local/lib/python2.7/site-packages/fitsio/fitslib.pyc in read(self, **keys)
   1704             data = self.read_rows(rows, **keys)
   1705         else:
-> 1706             data = self._read_all(**keys)
   1707 
   1708         return data

/home/aldcroft/.local/lib/python2.7/site-packages/fitsio/fitslib.pyc in _read_all(self, **keys)
   1725         """
   1726 
-> 1727         dtype, offsets, isvar = self.get_rec_dtype(**keys)
   1728 
   1729         w,=numpy.where(isvar == True)

/home/aldcroft/.local/lib/python2.7/site-packages/fitsio/fitslib.pyc in get_rec_dtype(self, **keys)
   2036         isvararray = numpy.zeros(len(colnums),dtype=numpy.bool)
   2037         for i,colnum in enumerate(colnums):
-> 2038             dt,isvar = self.get_rec_column_descr(colnum, vstorage)
   2039             descr.append(dt)
   2040             isvararray[i] = isvar

/home/aldcroft/.local/lib/python2.7/site-packages/fitsio/fitslib.pyc in get_rec_column_descr(self, colnum, vstorage)
   2098             See docs in read_columns
   2099         """
-> 2100         npy_type,isvar = self._get_tbl_numpy_dtype(colnum)
   2101         name = self._info['colinfo'][colnum]['name']
   2102 

/home/aldcroft/.local/lib/python2.7/site-packages/fitsio/fitslib.pyc in _get_tbl_numpy_dtype(self, colnum, include_endianness)
   2362         except KeyError:
   2363             raise KeyError("unsupported %s fits data "
-> 2364                            "type: %d" % (table_type_string, ftype))
   2365 
   2366         isvar=False

KeyError: 'unsupported BINARY_TBL fits data type: 1'

Here is the relevant part of the header:

XTENSION= 'BINTABLE'           / binary table extension
BITPIX  =                    8 / 8-bit bytes
NAXIS   =                    2 / 2-dimensional binary table
NAXIS1  =                   41 / width of table in bytes
NAXIS2  =                  200 / number of rows in table
PCOUNT  =                    0 / size of special data area
GCOUNT  =                    1 / one data group (required keyword)
TFIELDS =                    2 / number of fields in each row
EXTNAME = 'AXAF_OBC'           / name of this binary table extension
HDUNAME = 'AXAF_OBC'           / ASCDM block name
TTYPE1  = 'TIME    '           / Time-tag of the data record
TFORM1  = '1D      '           / format of field
TUNIT1  = 's       '
TTYPE2  = 'QUALITY '           / Quality Bitarray
TFORM2  = '263X    '           / format of field

Failure in installing fitsio using either pip or the standard way

Dear All,

I have come across some complaints when I tried to install the fitsio module on my system (OS X). For your information, I need "fitsio" as a prerequisite of the Astrometry.net code.

I tried both ways of installing "fitsio", either pip or downloading the tar file (untaring, and running "python setup.py"). None of has been successful. I get error that says a code (fitsio_pywrap.c in firsio directory) is missing the fitsio.h file:

fitsio/fitsio_pywrap.c:25:10: fatal error: 'fitsio.h' file not found

I was hoping if someone has ever come across this problem during the "fitsio" installation. I would sincerely appreciate any comments and help.

Thank you,

  • Mehdi

fix for PLIO compression

I reported the PLIO ushort bug (offsets of 2**15 on every number) and a fix came about in July last year, but has not made it into an official release yet.

Make a new directory cfitsio3370patch and put in the new version of imcompress.c until a new cfitsio is released

Problem compressing image extensions

Erin,
I have a little script to pull off the 8 F&A CCD's extensions from a raw image, but when I try to also use compression I get an error.

Here is the script:

import fitsio
hdu = fitsio.FITS("/Users/roodman/Astrophysics/DESData/DECam_00232698.fits.fz")
newhdu = fitsio.FITS('test.fits','rw')
newhdu.write(data=None,header=hdu[0].read_header())
newhdu.write_image(img=hdu['FS1'].read_image(),header=hdu['FS1'].read_header(),extname='FS1',compress='RICE')

Here is the error:

Traceback (most recent call last):
File "", line 1, in
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/fitsio/fitslib.py", line 469, in write_image
self[-1].write_image(img)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/fitsio/fitslib.py", line 1093, in write_image
self._FITS.write_image(self.ext+1, img_send)
IOError: FITSIO status = 302: column number < 1 or > tfields
Specified column number is out of range: 2
There are 1 columns in this table.

I have an existing script using pyfits which does work fine, but takes 12 seconds/image, and was hoping that fitsio would be much faster.

thanks, Aaron

ps. I am using the version of fitsio from pip.

error in new build_ext

@rainwoodman I'm seeing errors in the new build_ext from PR #64

It looks like the .so extension is not being built. You might not see it if
you haven't removed the /build directory

building 'fitsio._fitsio_wrap' extension
creating build/temp.linux-x86_64-2.7
creating build/temp.linux-x86_64-2.7/fitsio
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/esheldon/anaconda/envs/local/lib/python2.7/site-packages/numpy/core/include -I/home/esheldon/anaconda/envs/local/include/python2.7 -Icfitsio3370patch -c fitsio/fitsio_pywrap.c -o build/temp.linux-x86_64-2.7/fitsio/fitsio_pywrap.o
In file included from /home/esheldon/anaconda/envs/local/include/python2.7/Python.h:8:0,
                 from fitsio/fitsio_pywrap.c:24:
/home/esheldon/anaconda/envs/local/include/python2.7/pyconfig.h:1188:0: warning: "_POSIX_C_SOURCE" redefined [enabled by default]
 #define _POSIX_C_SOURCE 200112L
 ^
In file included from /usr/include/string.h:25:0,
                 from fitsio/fitsio_pywrap.c:23:
/usr/include/features.h:230:0: note: this is the location of the previous definition
 # define _POSIX_C_SOURCE 200809L
 ^
In file included from /home/esheldon/anaconda/envs/local/lib/python2.7/site-packages/numpy/core/include/numpy/ndarraytypes.h:1804:0,
                 from /home/esheldon/anaconda/envs/local/lib/python2.7/site-packages/numpy/core/include/numpy/ndarrayobject.h:17,
                 from /home/esheldon/anaconda/envs/local/lib/python2.7/site-packages/numpy/core/include/numpy/arrayobject.h:4,
                 from fitsio/fitsio_pywrap.c:28:
/home/esheldon/anaconda/envs/local/lib/python2.7/site-packages/numpy/core/include/numpy/npy_1_7_deprecated_api.h:15:2: warning: #warning "Using deprecated NumPy API, disable it by " "#defining NPY_NO_DEPRECATED_API NPY_1_7_API_VERSION" [-Wcpp]
 #warning "Using deprecated NumPy API, disable it by " \
  ^
gcc -pthread -shared -L/home/esheldon/anaconda/envs/local/lib -Wl,-rpath=/home/esheldon/anaconda/envs/local/lib,--no-as-needed build/temp.linux-x86_64-2.7/fitsio/fitsio_pywrap.o build/cfitsio3370patch/libcfitsio.a -L/home/esheldon/anaconda/envs/local/lib -lpython2.7 -o build/lib.linux-x86_64-2.7/fitsio/_fitsio_wrap.so
/usr/bin/ld: cannot open output file build/lib.linux-x86_64-2.7/fitsio/_fitsio_wrap.so: No such file or directory
collect2: error: ld returned 1 exit status
error: command 'gcc' failed with exit status 1

header __repr__ display old records

It appears that the repr of FITSHDR continues to display records that have been updated and should have been overwritten.

>>> import fitsio
>>> filename = 'DECam_00254560.fits.fz'
>>> hdr = fitsio.read_header(filename)
>>> key = hdr.keys()[-1]
>>> hdr[key] = 0
>>> print hdr
SIMPLE  =                    T / conforms to FITS standard
BITPIX  =                    8 / array data type
NAXIS   =                    0 / number of array dimensions
...
RECNO   =               124691  /  NOAO Science Archive sequence number
RECNO   =                    0

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.