-
Notifications
You must be signed in to change notification settings - Fork 22
/
decode.go
437 lines (377 loc) · 8.99 KB
/
decode.go
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
// Copyright 2015 The astrogo Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package fitsio
import (
"fmt"
"io"
"io/ioutil"
"reflect"
"strconv"
"strings"
)
type Decoder interface {
DecodeHDU() (HDU, error)
}
// NewDecoder creates a new Decoder according to the capabilities of the underlying io.Reader
func NewDecoder(r io.Reader) Decoder {
// FIXME(sbinet)
// if rr, ok := r.(io.ReadSeeker); ok {
// return &seekDecoder{r: rr}
// }
return &streamDecoder{r: r}
}
// streamDecoder is a decoder which can not perform random access
// into the underlying Reader
type streamDecoder struct {
r io.Reader
}
func (dec *streamDecoder) DecodeHDU() (HDU, error) {
var err error
var hdu HDU
cards := make(map[string]int, 30)
slice := make([]Card, 0, 1)
get_card := func(k string) (Card, bool) {
i, ok := cards[k]
if ok {
return slice[i], ok
}
return Card{}, ok
}
add_card := func(c *Card) {
n := c.Name
if n == "COMMENT" || n == "HISTORY" || n == "" {
slice = append(slice, *c)
return
}
// For compatibility with C FITSIO, silently swallow duplicate card keys.
// See:
// https://github.com/astrogo/fitsio/issues/38
//
// _, dup := cards[n]
// if dup {
// panic(fmt.Errorf("fitsio: duplicate keyword [%s]", n))
// }
cards[n] = len(slice)
slice = append(slice, *c)
}
axes := []int{}
buf := make([]byte, blockSize)
iblock := -1
blocks_loop:
for {
iblock += 1
_, err = io.ReadFull(dec.r, buf)
if err != nil {
return nil, err
}
// each FITS header block is comprised of up to 36 80-byte lines
const maxlines = 36
for i := 0; i < maxlines; i++ {
card, err := parseHeaderLine(buf[i*80 : (i+1)*80])
if err != nil {
return nil, err
}
if card.Name == "CONTINUE" {
idx := len(slice) - 1
last := slice[idx]
str := last.Value.(string)
if len(str) > 0 {
last.Value = str[:len(str)-1] + card.Comment
}
slice[idx] = last
continue
}
add_card(card)
if card.Name == "END" {
break
}
}
_, ends := get_card("END")
if ends {
card, ok := get_card("NAXIS")
if ok {
n := card.Value.(int)
axes = make([]int, n)
for i := 0; i < n; i++ {
k := fmt.Sprintf("NAXIS%d", i+1)
c, ok := get_card(k)
if !ok {
return nil, fmt.Errorf("fitsio: missing '%s' key", k)
}
axes[i] = c.Value.(int)
}
}
break blocks_loop
}
}
htype, primary, err := hduTypeFrom(slice)
if err != nil {
return nil, err
}
bitpix := 0
if card, ok := get_card("BITPIX"); ok {
bitpix = int(reflect.ValueOf(card.Value).Int())
} else {
return nil, fmt.Errorf("fitsio: missing 'BITPIX' card")
}
hdr := NewHeader(slice, htype, bitpix, axes)
switch htype {
case IMAGE_HDU:
var data []byte
data, err = dec.loadImage(hdr)
if err != nil {
return nil, fmt.Errorf("fitsio: error loading image: %v", err)
}
switch primary {
case true:
hdu = &primaryHDU{
imageHDU: imageHDU{
hdr: *hdr,
raw: data,
},
}
case false:
hdu = &imageHDU{
hdr: *hdr,
raw: data,
}
}
case BINARY_TBL:
hdu, err = dec.loadTable(hdr, htype)
if err != nil {
return nil, fmt.Errorf("fitsio: error loading binary table: %v", err)
}
case ASCII_TBL:
hdu, err = dec.loadTable(hdr, htype)
if err != nil {
return nil, fmt.Errorf("fitsio: error loading ascii table: %v", err)
}
case ANY_HDU:
fallthrough
default:
return nil, fmt.Errorf("fitsio: invalid HDU Type (%v)", htype)
}
return hdu, err
}
func (dec *streamDecoder) loadImage(hdr *Header) ([]byte, error) {
var err error
var buf []byte
nelmts := 1
for _, dim := range hdr.Axes() {
nelmts *= dim
}
if len(hdr.Axes()) <= 0 {
nelmts = 0
}
pixsz := hdr.Bitpix() / 8
if pixsz < 0 {
pixsz = -pixsz
}
buf = make([]byte, nelmts*pixsz)
if nelmts == 0 {
return buf, nil
}
n, err := io.ReadFull(dec.r, buf)
if err != nil {
return nil, fmt.Errorf("fitsio: error reading %d bytes (got %d): %v", len(buf), n, err)
}
// data array is also aligned at 2880-bytes blocks
pad := padBlock(n)
if pad > 0 {
if n, err := io.CopyN(ioutil.Discard, dec.r, int64(pad)); err != nil {
return nil, fmt.Errorf("fitsio: error reading %d bytes (got %d): %v", pad, n, err)
}
}
return buf, err
}
func (dec *streamDecoder) loadTable(hdr *Header, htype HDUType) (*Table, error) {
var err error
var table *Table
isbinary := true
switch htype {
case ASCII_TBL:
isbinary = false
case BINARY_TBL:
isbinary = true
default:
return nil, fmt.Errorf("fitsio: invalid HDU type (%v)", htype)
}
rowsz := hdr.Axes()[0]
nrows := int64(hdr.Axes()[1])
ncols := 0
if card := hdr.Get("TFIELDS"); card != nil && card.Value != nil {
ncols = card.Value.(int)
}
datasz := int(nrows) * rowsz
heapsz := 0
if card := hdr.Get("PCOUNT"); card != nil && card.Value != nil {
heapsz = card.Value.(int)
}
blocksz := alignBlock(datasz + heapsz)
block := make([]byte, blocksz)
n, err := io.ReadFull(dec.r, block)
if err != nil {
return nil, fmt.Errorf("fitsio: error reading %d bytes (got %d): %v", len(block), n, err)
}
gapsz := 0
if card := hdr.Get("THEAP"); card != nil && card.Value != nil {
gapsz = card.Value.(int)
}
data := block[:datasz]
heap := block[datasz+gapsz:]
cols := make([]Column, ncols)
colidx := make(map[string]int, ncols)
get := func(str string, ii int) *Card {
return hdr.Get(fmt.Sprintf(str+"%d", ii+1))
}
offset := 0
for i := 0; i < ncols; i++ {
col := &cols[i]
switch htype {
case BINARY_TBL:
col.write = col.writeBin
col.read = col.readBin
case ASCII_TBL:
col.write = col.writeTxt
col.read = col.readTxt
default:
return nil, fmt.Errorf("fitsio: invalid HDUType (%v)", htype)
}
col.offset = offset
card := get("TTYPE", i)
col.Name = card.Value.(string)
card = get("TFORM", i)
if card == nil {
return nil, fmt.Errorf("fitsio: missing 'TFORM%d' for column '%s'", i+1, col.Name)
} else {
col.Format = card.Value.(string)
}
card = get("TUNIT", i)
if card != nil && card.Value != nil {
col.Unit = card.Value.(string)
}
card = get("TNULL", i)
if card != nil && card.Value != nil {
col.Null = fmt.Sprintf("%v", card.Value)
}
card = get("TSCAL", i)
if card != nil && card.Value != nil {
switch vv := card.Value.(type) {
case float64:
col.Bscale = vv
case int64:
col.Bscale = float64(vv)
case int:
col.Bscale = float64(vv)
default:
return nil, fmt.Errorf("fitsio: unhandled type [%T]", vv)
}
} else {
col.Bscale = 1.0
}
card = get("TZERO", i)
if card != nil && card.Value != nil {
switch vv := card.Value.(type) {
case float64:
col.Bzero = vv
case int64:
col.Bzero = float64(vv)
case int:
col.Bzero = float64(vv)
default:
return nil, fmt.Errorf("fitsio: unhandled type [%T]", vv)
}
} else {
col.Bzero = 0.0
}
card = get("TDISP", i)
if card != nil && card.Value != nil {
col.Display = card.Value.(string)
}
card = get("TDIM", i)
if card != nil && card.Value != nil {
dims := card.Value.(string)
dims = strings.Replace(dims, "(", "", -1)
dims = strings.Replace(dims, ")", "", -1)
toks := make([]string, 0)
for _, tok := range strings.Split(dims, ",") {
tok = strings.Trim(tok, " \t\n")
if tok == "" {
continue
}
toks = append(toks, tok)
}
col.Dim = make([]int64, 0, len(toks))
for _, tok := range toks {
dim, err := strconv.ParseInt(tok, 10, 64)
if err != nil {
return nil, err
}
col.Dim = append(col.Dim, dim)
}
}
card = get("TBCOL", i)
if card != nil && card.Value != nil {
col.Start = int64(card.Value.(int))
}
col.dtype, err = typeFromForm(col.Format, htype)
if err != nil {
return nil, err
}
offset += col.dtype.dsize * col.dtype.len
if htype == ASCII_TBL {
col.txtfmt = txtfmtFromForm(col.Format)
}
colidx[col.Name] = i
}
table = &Table{
hdr: *hdr,
binary: isbinary,
data: data,
heap: heap,
rowsz: rowsz,
nrows: nrows,
cols: cols,
colidx: colidx,
}
return table, err
}
// seekDecoder is a decoder which can perform random access into
// the underlying Reader
type seekDecoder struct {
r io.ReadSeeker
}
func (dec *seekDecoder) DecodeHDU() (HDU, error) {
panic("not implemented")
}
func hduTypeFrom(cards []Card) (HDUType, bool, error) {
var err error
var htype HDUType = -1
var primary bool
keys := make([]string, 0, len(cards))
for _, card := range cards {
keys = append(keys, card.Name)
switch card.Name {
case "SIMPLE":
primary = true
return IMAGE_HDU, primary, nil
case "XTENSION":
str := card.Value.(string)
switch str {
case "IMAGE":
htype = IMAGE_HDU
case "TABLE":
htype = ASCII_TBL
case "BINTABLE":
htype = BINARY_TBL
case "ANY", "ANY_HDU":
htype = ANY_HDU
default:
return htype, primary, fmt.Errorf("fitsio: invalid 'XTENSION' value: %q", str)
}
return htype, primary, err
}
}
return htype, primary, fmt.Errorf("fitsio: invalid header (missing 'SIMPLE' or 'XTENSION' card): keys=%v", keys)
}