fitsio

package module
v0.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Feb 28, 2023 License: BSD-3-Clause Imports: 13 Imported by: 14

README

fitsio

GitHub release CI codecov GoDoc

fitsio is a pure-Go package to read and write FITS files.

Installation

$ go get github.com/astrogo/fitsio

Documentation

https://godoc.org/github.com/astrogo/fitsio

Contribute

astrogo/fitsio is released under BSD-3. Please send a pull request to astrogo/license, adding yourself to the AUTHORS and/or CONTRIBUTORS file.

Example

import fits "github.com/astrogo/fitsio"

func dumpFitsTable(fname string) {
    r, err := os.Open(fname)
    if err != nil {
        panic(err)
    }
    defer r.Close()
	f, err := fits.Open(r)
	if err != nil {
		panic(err)
	}
	defer f.Close()

	// get the second HDU
	table := f.HDU(1).(*fits.Table)
	nrows := table.NumRows()
    rows, err := table.Read(0, nrows)
    if err != nil {
        panic(err)
    }
    defer rows.Close()
	for rows.Next() {
        var x, y float64
        var id int64
        err = rows.Scan(&id, &x, &y)
        if err != nil {
            panic(err)
        }
        fmt.Printf(">>> %v %v %v\n", id, x, y)
	}
    err = rows.Err()
    if err != nil { panic(err) }
    
    // using a struct
    xx := struct{
        Id int     `fits:"ID"`
        X  float64 `fits:"x"`
        Y  float64 `fits:"y"`
    }{}
    // using a map
    yy := make(map[string]interface{})
    
    rows, err = table.Read(0, nrows)
    if err != nil {
        panic(err)
    }
    defer rows.Close()
	for rows.Next() {
        err = rows.Scan(&xx)
        if err != nil {
            panic(err)
        }
        fmt.Printf(">>> %v\n", xx)

        err = rows.Scan(&yy)
        if err != nil {
            panic(err)
        }
        fmt.Printf(">>> %v\n", yy)
	}
    err = rows.Err()
    if err != nil { panic(err) }
    
}

TODO

  • [DONE] add support for writing tables from structs
  • [DONE] add support for writing tables from maps
  • [DONE] add support for variable length array
  • provide benchmarks wrt CFITSIO
  • add support for TUNITn
  • add support for TSCALn
  • add suport for TDIMn
  • add support for (fast, low-level) copy of FITS tables

Documentation

Overview

fitsio provides read and write access to FITS files.

Example (CreateImage3x4F64)
package main

import (
	"log"
	"os"

	"github.com/astrogo/fitsio"
)

func main() {
	f, err := os.Create("testdata/ex-img-bitpix-64.fits")
	if err != nil {
		log.Fatalf("could not create file: %+v", err)
	}
	defer f.Close()

	fits, err := fitsio.Create(f)
	if err != nil {
		log.Fatalf("could not create FITS file: %+v", err)
	}
	defer fits.Close()

	// create primary HDU image
	var (
		bitpix = -64
		axes   = []int{3, 4}
		data   = []float64{
			0, 1, 2, 3,
			4, 5, 6, 7,
			8, 9, 0, 1,
		}
	)
	img := fitsio.NewImage(bitpix, axes)
	defer img.Close()

	err = img.Header().Append(
		fitsio.Card{
			"EXTNAME",
			"primary hdu",
			"the primary HDU",
		},
		fitsio.Card{
			"EXTVER",
			2,
			"the primary hdu version",
		},
	)
	if err != nil {
		log.Fatalf("could append cards: %+v", err)
	}

	err = img.Write(data)
	if err != nil {
		log.Fatalf("could not write data to image: %+v", err)
	}

	err = fits.Write(img)
	if err != nil {
		log.Fatalf("could not write image to FITS file: %+v", err)
	}

	err = fits.Close()
	if err != nil {
		log.Fatalf("could not close FITS file: %+v", err)
	}

	err = f.Close()
	if err != nil {
		log.Fatalf("could not close file: %+v", err)
	}

}
Output:

Example (CreateImage3x4I64)
package main

import (
	"log"
	"os"

	"github.com/astrogo/fitsio"
)

func main() {
	f, err := os.Create("testdata/ex-img-bitpix+64.fits")
	if err != nil {
		log.Fatalf("could not create file: %+v", err)
	}
	defer f.Close()

	fits, err := fitsio.Create(f)
	if err != nil {
		log.Fatalf("could not create FITS file: %+v", err)
	}
	defer fits.Close()

	// create primary HDU image
	var (
		bitpix = 64
		axes   = []int{3, 4}
		data   = []int64{
			0, 1, 2, 3,
			4, 5, 6, 7,
			8, 9, 0, 1,
		}
	)
	img := fitsio.NewImage(bitpix, axes)
	defer img.Close()

	err = img.Header().Append(
		fitsio.Card{
			"EXTNAME",
			"primary hdu",
			"the primary HDU",
		},
		fitsio.Card{
			"EXTVER",
			2,
			"the primary hdu version",
		},
	)
	if err != nil {
		log.Fatalf("could append cards: %+v", err)
	}

	err = img.Write(data)
	if err != nil {
		log.Fatalf("could not write data to image: %+v", err)
	}

	err = fits.Write(img)
	if err != nil {
		log.Fatalf("could not write image to FITS file: %+v", err)
	}

	err = fits.Close()
	if err != nil {
		log.Fatalf("could not close FITS file: %+v", err)
	}

	err = f.Close()
	if err != nil {
		log.Fatalf("could not close file: %+v", err)
	}

}
Output:

Example (CreateImage3x4I8)
package main

import (
	"log"
	"os"

	"github.com/astrogo/fitsio"
)

func main() {
	f, err := os.Create("testdata/ex-img-bitpix+8.fits")
	if err != nil {
		log.Fatalf("could not create file: %+v", err)
	}
	defer f.Close()

	fits, err := fitsio.Create(f)
	if err != nil {
		log.Fatalf("could not create FITS file: %+v", err)
	}
	defer fits.Close()

	// create primary HDU image
	var (
		bitpix = 8
		axes   = []int{3, 4}
		data   = []int8{
			0, 1, 2, 3,
			4, 5, 6, 7,
			8, 9, 0, 1,
		}
	)
	img := fitsio.NewImage(bitpix, axes)
	defer img.Close()

	err = img.Header().Append(
		fitsio.Card{
			"EXTNAME",
			"primary hdu",
			"the primary HDU",
		},
		fitsio.Card{
			"EXTVER",
			2,
			"the primary hdu version",
		},
	)
	if err != nil {
		log.Fatalf("could append cards: %+v", err)
	}

	err = img.Write(data)
	if err != nil {
		log.Fatalf("could not write data to image: %+v", err)
	}

	err = fits.Write(img)
	if err != nil {
		log.Fatalf("could not write image to FITS file: %+v", err)
	}

	err = fits.Close()
	if err != nil {
		log.Fatalf("could not close FITS file: %+v", err)
	}

	err = f.Close()
	if err != nil {
		log.Fatalf("could not close file: %+v", err)
	}

}
Output:

Example (Open)
package main

import (
	"fmt"
	"log"
	"os"

	"github.com/astrogo/fitsio"
)

func main() {
	f, err := os.Open("testdata/file-img2-bitpix+08.fits")
	if err != nil {
		log.Fatalf("could not open file: %+v", err)
	}
	defer f.Close()

	fits, err := fitsio.Open(f)
	if err != nil {
		log.Fatalf("could not open FITS file: %+v", err)
	}
	defer fits.Close()

	for i, hdu := range fits.HDUs() {
		fmt.Printf("Header listing for HDU #%d:\n", i)
		hdr := hdu.Header()
		for k := range hdr.Keys() {
			card := hdr.Card(k)
			fmt.Printf(
				"%-8s= %-29s / %s\n",
				card.Name,
				fmt.Sprintf("%v", card.Value),
				card.Comment)
		}
		fmt.Printf("END\n\n")
	}

}
Output:

Header listing for HDU #0:
SIMPLE  = true                          / primary HDU
BITPIX  = 8                             / number of bits per data pixel
NAXIS   = 2                             / number of data axes
NAXIS1  = 50                            / length of data axis 1
NAXIS2  = 50                            / length of data axis 2
IMAGENBR= 0                             / image number
END

Header listing for HDU #1:
XTENSION= IMAGE                         / IMAGE extension
BITPIX  = 8                             / number of bits per data pixel
NAXIS   = 2                             / number of data axes
NAXIS1  = 50                            / length of data axis 1
NAXIS2  = 50                            / length of data axis 2
IMAGENBR= 1                             / image number
END
Example (OpenImage3x4F64)
package main

import (
	"fmt"
	"log"
	"os"

	"github.com/astrogo/fitsio"
)

func main() {
	f, err := os.Open("testdata/example.fits")
	if err != nil {
		log.Fatalf("could not open file: %+v", err)
	}
	defer f.Close()

	fits, err := fitsio.Open(f)
	if err != nil {
		log.Fatalf("could not open FITS file: %+v", err)
	}
	defer fits.Close()

	var (
		hdu    = fits.HDU(0)
		hdr    = hdu.Header()
		img    = hdu.(fitsio.Image)
		bitpix = hdr.Bitpix()
		axes   = hdr.Axes()
	)
	fmt.Printf("bitpix: %d\n", bitpix)
	fmt.Printf("axes:   %v\n", axes)
	data := make([]float64, axes[0]*axes[1])
	err = img.Read(&data)
	if err != nil {
		log.Fatalf("could not read image: %+v", err)
	}
	fmt.Printf("data:   %v\n", data)

}
Output:

bitpix: -64
axes:   [3 4]
data:   [0 1 2 3 4 5 6 7 8 9 0 1]

Index

Examples

Constants

View Source
const (
	ReadOnly  Mode = Mode(os.O_RDONLY) // open the file read-only
	WriteOnly      = Mode(os.O_WRONLY) // open the file write-only
	ReadWrite      = Mode(os.O_RDWR)   // open the file read-write
)

Variables

This section is empty.

Functions

func CopyHDU

func CopyHDU(dst, src *File, i int) error

CopyHDU copies the i-th HDU from the src FITS file into the dst one.

func CopyTable

func CopyTable(dst, src *Table) error

CopyTable copies all the rows from src into dst.

func CopyTableRange

func CopyTableRange(dst, src *Table, beg, end int64) error

CopyTableRange copies the rows interval [beg,end) from src into dst

func NewImage

func NewImage(bitpix int, axes []int) *imageHDU

NewImage creates a new Image with bitpix size for the pixels and axes as its axes

Types

type Card

type Card struct {
	Name    string
	Value   Value
	Comment string
}

Card is a record block in a Header

type Column

type Column struct {
	Name    string  // column name, corresponding to “TTYPE“ keyword
	Format  string  // column format, corresponding to “TFORM“ keyword
	Unit    string  // column unit, corresponding to “TUNIT“ keyword
	Null    string  // null value, corresponding to “TNULL“ keyword
	Bscale  float64 // bscale value, corresponding to “TSCAL“ keyword
	Bzero   float64 // bzero value, corresponding to “TZERO“ keyword
	Display string  // display format, corresponding to “TDISP“ keyword
	Dim     []int64 // column dimension corresponding to “TDIM“ keyword
	Start   int64   // column starting position, corresponding to “TBCOL“ keyword
	// contains filtered or unexported fields
}

Column represents a column in a FITS table

func NewColumn

func NewColumn(name string, v interface{}) (Column, error)

NewColumn creates a new Column with name `name` and Format inferred from the type of value

func (*Column) Type

func (col *Column) Type() reflect.Type

Type returns the Go reflect.Type associated with this Column

type Decoder

type Decoder interface {
	DecodeHDU() (HDU, error)
}

func NewDecoder

func NewDecoder(r io.Reader) Decoder

NewDecoder creates a new Decoder according to the capabilities of the underlying io.Reader

type Encoder

type Encoder interface {
	EncodeHDU(hdu HDU) error
}

func NewEncoder

func NewEncoder(w io.Writer) Encoder

NewEncoder creates a new Encoder according to the capabilities of the underlying io.Writer

type File

type File struct {
	// contains filtered or unexported fields
}

File represents a FITS file.

func Create

func Create(w io.Writer) (*File, error)

Create creates a new FITS file in write-only mode

func Open

func Open(r io.Reader) (*File, error)

Open opens a FITS file in read-only mode.

func (*File) Close

func (f *File) Close() error

Close releases resources held by a FITS file.

It does not close the underlying io.Reader or io.Writer.

func (*File) Get

func (f *File) Get(name string) HDU

Get returns the HDU with name `name` or nil

func (*File) HDU

func (f *File) HDU(i int) HDU

HDU returns the i-th HDU

func (*File) HDUs

func (f *File) HDUs() []HDU

HDUs returns the list of all Header-Data Unit blocks in the file

func (*File) Has

func (f *File) Has(name string) bool

Has returns whether the File has a HDU with name `name`.

func (*File) Mode

func (f *File) Mode() Mode

Mode returns the access-mode of this FITS file

func (*File) Name

func (f *File) Name() string

Name returns the name of the FITS file

func (*File) Write

func (f *File) Write(hdu HDU) error

Write writes a HDU to file

type HDU

type HDU interface {
	Close() error
	Type() HDUType
	Name() string
	Version() int
	Header() *Header
}

HDU is a "Header-Data Unit" block

type HDUType

type HDUType int

HDUType is the type of a Header-Data Unit

const (
	IMAGE_HDU  HDUType = iota // Primary Array or IMAGE HDU
	ASCII_TBL                 // ASCII table HDU
	BINARY_TBL                // Binary table HDU
	ANY_HDU                   // matches any HDU type
)

func (HDUType) String

func (htype HDUType) String() string
type Header struct {
	// contains filtered or unexported fields
}

Header describes a Header-Data Unit of a FITS file

func NewDefaultHeader

func NewDefaultHeader() *Header

NewDefaultHeader creates a Header with CFITSIO default Cards, of type IMAGE_HDU and bitpix=8, no axes.

func NewHeader

func NewHeader(cards []Card, htype HDUType, bitpix int, axes []int) *Header

NewHeader creates a new Header from a set of Cards, HDU Type, bitpix and axes.

func (*Header) Append

func (hdr *Header) Append(cards ...Card) error

Append appends a set of Cards to this Header

func (*Header) Axes

func (hdr *Header) Axes() []int

Axes returns the axes for this Header.

func (*Header) Bitpix

func (hdr *Header) Bitpix() int

Bitpix returns the bitpix value.

func (*Header) Card

func (hdr *Header) Card(i int) *Card

Card returns the i-th card. Card panics if the index is out of range.

func (*Header) Clear

func (hdr *Header) Clear()

Clear resets the Header to the default state.

func (*Header) Comment

func (hdr *Header) Comment() string

Comment returns the whole comment string for this Header.

func (*Header) Get

func (hdr *Header) Get(n string) *Card

Get returns the Card with name n or nil if it doesn't exist. If multiple cards with the same name exist, the first one is returned.

func (*Header) History

func (hdr *Header) History() string

History returns the whole history string for this Header.

func (*Header) Index

func (hdr *Header) Index(n string) int

Index returns the index of the Card with name n, or -1 if it doesn't exist

func (*Header) Keys

func (hdr *Header) Keys() []string

Keys returns the name of all the Cards of this Header.

func (*Header) Set

func (hdr *Header) Set(n string, v interface{}, comment string)

Set modifies the value and comment of a Card with name n.

func (*Header) Text

func (hdr *Header) Text() string

Text returns the header's cards content as 80-byte lines

func (*Header) Type

func (hdr *Header) Type() HDUType

Type returns the Type of this Header

type Image

type Image interface {
	HDU
	Read(ptr interface{}) error
	Write(ptr interface{}) error
	Raw() []byte
	Image() image.Image
	// contains filtered or unexported methods
}

Image represents a FITS image

func NewPrimaryHDU

func NewPrimaryHDU(hdr *Header) (Image, error)

NewPrimaryHDU creates a new PrimaryHDU with Header hdr. If hdr is nil, a default Header will be created.

type Mode

type Mode int

Mode defines a FITS file access mode (r/w)

type Reader

type Reader struct {
	// contains filtered or unexported fields
}

func NewReader

func NewReader(r io.Reader) *Reader

type Rows

type Rows struct {
	// contains filtered or unexported fields
}

Rows is the result of a query on a FITS Table. Its cursors starts before the first row of the result set. Use Next to advance through the rows:

rows, err := table.Read(0, -1)
...
for rows.Next() {
    var id int
    var x float64
    err = rows.Scan(&id, &x)
    ...
}
err = rows.Err() // get any error encountered during iteration
...

func (*Rows) Close

func (rows *Rows) Close() error

Close closes the Rows, preventing further enumeration. Close is idempotent and does not affect the result of Err.

func (*Rows) Err

func (rows *Rows) Err() error

Err returns the error, if any, that was encountered during iteration. Err may be called after an explicit or implicit Close.

func (*Rows) Next

func (rows *Rows) Next() bool

Next prepares the next result row for reading with the Scan method. It returns true on success, false if there is no next result row. Every call to Scan, even the first one, must be preceded by a call to Next.

func (*Rows) Scan

func (rows *Rows) Scan(args ...interface{}) error

Scan copies the columns in the current row into the values pointed at by dest.

type Table

type Table struct {
	// contains filtered or unexported fields
}

func NewTable

func NewTable(name string, cols []Column, hdutype HDUType) (*Table, error)

NewTable creates a new table in the given FITS file

func NewTableFrom

func NewTableFrom(name string, v Value, hdutype HDUType) (*Table, error)

NewTableFrom creates a new table in the given FITS file, using the struct v as schema

func (*Table) Close

func (t *Table) Close() error

Close closes this HDU, cleaning up cycles (if any) for garbage collection

func (*Table) Col

func (t *Table) Col(i int) *Column

func (*Table) Cols

func (t *Table) Cols() []Column

func (*Table) Data

func (t *Table) Data() (Value, error)

Data returns the image payload

func (*Table) Header

func (t *Table) Header() *Header

Header returns the Header part of this HDU block.

func (*Table) Index

func (t *Table) Index(n string) int

Index returns the index of the first column with name `n` or -1

func (*Table) Name

func (t *Table) Name() string

Name returns the value of the 'EXTNAME' Card.

func (*Table) NumCols

func (t *Table) NumCols() int

func (*Table) NumRows

func (t *Table) NumRows() int64

func (*Table) Read

func (t *Table) Read(beg, end int64) (*Rows, error)

Read reads rows over the range [beg, end) and returns the corresponding iterator. if end > maxrows, the iteration will stop at maxrows ReadRange has the same semantics than a `for i=0; i < max; i++ {...}` loop

func (*Table) ReadRange

func (t *Table) ReadRange(beg, end, inc int64) (*Rows, error)

ReadRange reads rows over the range [beg, end) and returns the corresponding iterator. if end > maxrows, the iteration will stop at maxrows ReadRange has the same semantics than a `for i=0; i < max; i+=inc {...}` loop

func (*Table) Type

func (t *Table) Type() HDUType

Type returns the Type of this HDU

func (*Table) Version

func (t *Table) Version() int

Version returns the value of the 'EXTVER' Card (or 1 if none)

func (*Table) Write

func (t *Table) Write(args ...interface{}) error

Write writes the data into the columns at the current row.

type Type

type Type struct {
	// contains filtered or unexported fields
}

Type describes a FITS type and its associated Go type

type Value

type Value interface{}

Directories

Path Synopsis
cmd
fltimg provides image.Image implementations for the float32- and float64-image encodings of FITS.
fltimg provides image.Image implementations for the float32- and float64-image encodings of FITS.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL