File: fits.rb

package info (click to toggle)
libnarray-ruby 0.5.9-1
  • links: PTS
  • area: main
  • in suites: etch, etch-m68k
  • size: 564 kB
  • ctags: 564
  • sloc: ansic: 4,620; ruby: 1,513; python: 70; makefile: 5
file content (97 lines) | stat: -rw-r--r-- 1,804 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# A simple class for handling FITS images
#	by Masahiro TANAKA 1999/12/19
#    No document, sorry.
#
# Require:  Ruby/NArray
#    http://koala.astro.isas.ac.jp/~masa/ruby/
#
# Example:
#    f = Fits.read('somthing.fits')
#    f.data # => 2-dimentional NArray data

require 'narray'

class Fits
  attr_accessor :data
  attr_accessor :header

  def initialize
    @data   = ""
    @header = []
  end

  def data_to_narray(data,type,shape)
    NArray.to_na( data, type, *shape ).ntoh
  end


  def read(fname)
    f = File.open(fname, "r")
    @header = []
    nbytes = 0
    foo = {}

    while 
      line = f.read(80)
      nbytes += 80;

      @header.push line

      name = line[0,8].strip!
      break if name=="END"

      rest = line[8..-1]
      if rest =~ /^= +('[^']*')/ #'
	foo[name] = $1
      elsif rest =~ /^= +([^\s\/]+)/
	foo[name] = $1
      end
    end

    # skip extra space
    nbytes %= 2880
    f.read(2880-nbytes) if nbytes > 0

    naxis = foo["NAXIS"].to_i

    case foo["BITPIX"]
    when "8";	elm_size = 1; type = NArray::BYTE
    when "16";	elm_size = 2; type = NArray::SINT
    when "32";	elm_size = 4; type = NArray::LINT
    when "-32";	elm_size = 4; type = NArray::SFLOAT
    when "-64";	elm_size = 8; type = NArray::DFLOAT
    end

    size = 1
    dims = []
    for i in 1..naxis
      key = "NAXIS#{i}"
      if foo.key? key
	n = foo[key].to_i
	size = size * n
	dims.push n
	#printf "%s=%i\n", key,n
      end
    end

    @data = data_to_narray( f.read(size*elm_size), type, dims )
    f.close

    if foo.key? "BSCALE"
      s = foo["BSCALE"].to_f
      @data = @data.to_f.mul!(s) if s != 1
    end

    if foo.key? "BZERO"
      s = foo["BZERO"].to_f
      @data = @data.to_f.add!(s) if s != 0
    end

    self
  end

end

def Fits.read(*a)
  Fits.new.read(*a)
end