-
Notifications
You must be signed in to change notification settings - Fork 22
/
table.go
606 lines (532 loc) · 12.1 KB
/
table.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
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
// 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"
"reflect"
)
type Table struct {
hdr Header
binary bool
data []byte // main data table
heap []byte // heap data table (for variable length arrays)
rowsz int // size of each row in bytes (ie: NAXIS1)
nrows int64 // number of rows (ie: NAXIS2)
cols []Column
colidx map[string]int // associates a column name to its index
}
// Close closes this HDU, cleaning up cycles (if any) for garbage collection
func (t *Table) Close() error {
return nil
}
// Header returns the Header part of this HDU block.
func (t *Table) Header() *Header {
return &t.hdr
}
// Type returns the Type of this HDU
func (t *Table) Type() HDUType {
return t.hdr.Type()
}
// Name returns the value of the 'EXTNAME' Card.
func (t *Table) Name() string {
card := t.hdr.Get("EXTNAME")
if card == nil {
return ""
}
return card.Value.(string)
}
// Version returns the value of the 'EXTVER' Card (or 1 if none)
func (t *Table) Version() int {
card := t.hdr.Get("EXTVER")
if card == nil {
return 1
}
return card.Value.(int)
}
// Data returns the image payload
func (t *Table) Data() (Value, error) {
panic("not implemented")
}
func (t *Table) NumRows() int64 {
return t.nrows
}
func (t *Table) NumCols() int {
return len(t.cols)
}
func (t *Table) Cols() []Column {
return t.cols
}
func (t *Table) Col(i int) *Column {
return &t.cols[i]
}
// Index returns the index of the first column with name `n` or -1
func (t *Table) Index(n string) int {
idx, ok := t.colidx[n]
if !ok {
return -1
}
return idx
}
// 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 (t *Table) ReadRange(beg, end, inc int64) (*Rows, error) {
var err error
var rows *Rows
maxrows := t.NumRows()
if end > maxrows {
end = maxrows
}
if beg < 0 {
beg = 0
}
cols := make([]int, len(t.cols))
for i := range t.cols {
cols[i] = i
}
rows = &Rows{
table: t,
cols: cols,
i: beg,
n: end,
inc: inc,
cur: beg - inc,
err: nil,
icols: make(map[reflect.Type][][2]int),
}
return rows, err
}
// 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 (t *Table) Read(beg, end int64) (*Rows, error) {
return t.ReadRange(beg, end, 1)
}
// NewTable creates a new table in the given FITS file
func NewTable(name string, cols []Column, hdutype HDUType) (*Table, error) {
var err error
isbinary := true
switch hdutype {
case ASCII_TBL:
isbinary = false
case BINARY_TBL:
isbinary = true
default:
return nil, fmt.Errorf("fitsio: invalid HDUType (%v)", hdutype)
}
ncols := len(cols)
table := &Table{
hdr: Header{},
binary: isbinary,
data: make([]byte, 0),
heap: make([]byte, 0),
rowsz: 0, // NAXIS1 in bytes
nrows: 0, // NAXIS2
cols: make([]Column, ncols),
colidx: make(map[string]int, ncols),
}
copy(table.cols, cols)
cards := make([]Card, 0, len(cols)+2)
cards = append(
cards,
Card{
Name: "TFIELDS",
Value: ncols,
Comment: "number of fields in each row",
},
)
offset := 0
for i := 0; i < ncols; i++ {
col := &table.cols[i]
col.offset = offset
switch hdutype {
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)", hdutype)
}
table.colidx[col.Name] = i
if col.Format == "" {
return nil, fmt.Errorf("fitsio: column (col=%s) has NO valid format", col.Name)
}
cards = append(cards,
Card{
Name: fmt.Sprintf("TTYPE%d", i+1),
Value: col.Name,
Comment: fmt.Sprintf("label for column %d", i+1),
},
Card{
Name: fmt.Sprintf("TFORM%d", i+1),
Value: col.Format,
Comment: fmt.Sprintf("data format for column %d", i+1),
},
)
col.dtype, err = typeFromForm(col.Format, hdutype)
if err != nil {
return nil, err
}
offset += col.dtype.dsize * col.dtype.len
col.txtfmt = txtfmtFromForm(col.Format)
if offset == 0 && i > 0 {
return nil, fmt.Errorf("fitsio: invalid data-layout")
}
if col.Unit != "" {
cards = append(cards,
Card{
Name: fmt.Sprintf("TUNIT%d", i+1),
Value: col.Unit,
Comment: fmt.Sprintf("unit for column %d", i+1),
},
)
}
if col.Null != "" {
cards = append(cards,
Card{
Name: fmt.Sprintf("TNULL%d", i+1),
Value: col.Null,
Comment: fmt.Sprintf("default value for column %d", i+1),
},
)
}
cards = append(cards,
Card{
Name: fmt.Sprintf("TSCAL%d", i+1),
Value: col.Bscale,
Comment: fmt.Sprintf("scaling offset for column %d", i+1),
},
)
cards = append(cards,
Card{
Name: fmt.Sprintf("TZERO%d", i+1),
Value: col.Bzero,
Comment: fmt.Sprintf("zero value for column %d", i+1),
},
)
if col.Start != 0 {
cards = append(cards,
Card{
Name: fmt.Sprintf("TBCOL%d", i+1),
Value: int(col.Start),
},
)
} else {
cards = append(cards,
Card{
Name: fmt.Sprintf("TBCOL%d", i+1),
Value: offset - col.dtype.dsize*col.dtype.len + 1,
},
)
}
if col.Display != "" {
cards = append(cards,
Card{
Name: fmt.Sprintf("TDISP%d", i+1),
Value: col.Display,
Comment: fmt.Sprintf("display format for column %d", i+1),
},
)
}
if len(col.Dim) > 0 {
str := "("
for idim, dim := range col.Dim {
str += fmt.Sprintf("%d", dim)
if idim+1 < len(col.Dim) {
str += ","
}
}
str += ")"
cards = append(cards,
Card{
Name: fmt.Sprintf("TDIM%d", i+1),
Value: str,
},
)
}
}
cards = append(
cards,
Card{
Name: "EXTNAME",
Value: name,
Comment: "name of this table extension",
},
)
bitpix := 8
hdr := newHeader(cards, hdutype, bitpix, []int{offset, 0})
table.hdr = *hdr
table.rowsz = offset
return table, err
}
// NewTableFrom creates a new table in the given FITS file, using the struct v as schema
func NewTableFrom(name string, v Value, hdutype HDUType) (*Table, error) {
rv := reflect.Indirect(reflect.ValueOf(v))
rt := rv.Type()
if rt.Kind() != reflect.Struct {
return nil, fmt.Errorf("fitsio: NewTableFrom takes a struct value. got: %T", v)
}
nmax := rt.NumField()
cols := make([]Column, 0, nmax)
for i := 0; i < nmax; i++ {
ft := rt.Field(i)
name := ft.Tag.Get("fits")
if name == "" {
name = ft.Name
}
field := rv.Field(i)
form := formFromGoType(field.Type(), hdutype)
if form == "" {
return nil, fmt.Errorf("fitsio: no FITS TFORM for field [%d] %#v", i, field.Interface())
}
cols = append(cols,
Column{
Name: name,
Format: form,
},
)
}
return NewTable(name, cols, hdutype)
}
// Write writes the data into the columns at the current row.
func (t *Table) Write(args ...interface{}) error {
var err error
t.data = append(t.data, make([]byte, t.rowsz)...)
switch len(args) {
case 0:
return fmt.Errorf("fitsio: Rows.Scan needs at least one argument")
case 1:
// maybe special case: map? struct?
rt := reflect.TypeOf(args[0]).Elem()
switch rt.Kind() {
case reflect.Map:
err = t.writeMap(*args[0].(*map[string]interface{}))
case reflect.Struct:
err = t.writeStruct(args[0])
default:
err = t.write(args[0])
}
default:
err = t.write(args...)
}
if err != nil {
return err
}
t.nrows += 1
t.hdr.axes[1] += 1
return err
}
func (t *Table) write(args ...interface{}) error {
var err error
if len(args) != len(t.cols) {
return fmt.Errorf(
"fitsio.Table.Write: invalid number of arguments (got %d. expected %d)",
len(args),
len(t.cols),
)
}
for i := range t.cols {
err = t.cols[i].write(t, i, t.nrows, args[i])
if err != nil {
return err
}
}
return err
}
func (t *Table) writeMap(data map[string]interface{}) error {
var err error
icols := make([]int, 0, len(data))
switch len(data) {
case 0:
icols = make([]int, len(t.cols))
for i := range t.cols {
icols[i] = i
}
default:
for k := range data {
icol := t.Index(k)
if icol >= 0 {
icols = append(icols, icol)
}
}
}
for _, icol := range icols {
col := t.Col(icol)
val := reflect.New(col.Type())
err = col.write(t, icol, t.nrows, val.Interface())
if err != nil {
return err
}
data[col.Name] = val.Elem().Interface()
}
return err
}
func (t *Table) writeStruct(data interface{}) error {
var err error
rt := reflect.TypeOf(data).Elem()
rv := reflect.ValueOf(data).Elem()
icols := make([][2]int, 0, rt.NumField())
if true { // fixme: devise a cache ?
for i := 0; i < rt.NumField(); i++ {
f := rt.Field(i)
n := f.Tag.Get("fits")
if n == "" {
n = f.Name
}
icol := t.Index(n)
if icol >= 0 {
icols = append(icols, [2]int{i, icol})
}
}
}
for _, icol := range icols {
col := &t.cols[icol[1]]
field := rv.Field(icol[0])
value := field.Addr().Interface()
err = col.write(t, icol[1], t.nrows, value)
if err != nil {
return err
}
}
return err
}
// freeze freezes a Table before writing, calculating offsets and finalizing header values.
func (t *Table) freeze() error {
var err error
nrows := t.nrows
t.hdr.axes[1] = int(nrows)
if card := t.Header().Get("XTENSION"); card == nil {
hduext := ""
if t.binary {
hduext = "BINTABLE"
} else {
hduext = "TABLE "
}
cards := []Card{
{
Name: "XTENSION",
Value: hduext,
Comment: "table extension",
},
{
Name: "BITPIX",
Value: t.Header().Bitpix(),
Comment: "number of bits per data pixel",
},
{
Name: "NAXIS",
Value: len(t.Header().Axes()),
Comment: "number of data axes",
},
{
Name: "NAXIS1",
Value: t.Header().Axes()[0],
Comment: "length of data axis 1",
},
{
Name: "NAXIS2",
Value: t.Header().Axes()[1],
Comment: "length of data axis 2",
},
{
Name: "PCOUNT",
Value: len(t.heap),
Comment: "heap area size (bytes)",
},
{
Name: "GCOUNT",
Value: 1,
Comment: "one data group",
},
}
err = t.hdr.prepend(cards...)
if err != nil {
return err
}
}
if card := t.Header().Get("THEAP"); card == nil {
err = t.hdr.Append([]Card{
{
Name: "THEAP",
Value: 0,
Comment: "gap size (bytes)",
},
}...)
}
return err
}
// CopyTable copies all the rows from src into dst.
func CopyTable(dst, src *Table) error {
return CopyTableRange(dst, src, 0, src.NumRows())
}
// CopyTableRange copies the rows interval [beg,end) from src into dst
func CopyTableRange(dst, src *Table, beg, end int64) error {
var err error
if dst == nil {
return fmt.Errorf("fitsio: dst pointer is nil")
}
if src == nil {
return fmt.Errorf("fitsio: src pointer is nil")
}
vla := false
for _, col := range src.Cols() {
if col.dtype.tc < 0 {
vla = true
break
}
}
// FIXME(sbinet)
// need to also handle VLAs
// src.heap -> dst.heap
// convert offsets into dst.heap
//
// for the time being: go the slow way
switch vla {
case true:
rows, err := src.Read(beg, end)
if err != nil {
return err
}
defer rows.Close()
ncols := len(src.Cols())
data := make([]interface{}, ncols)
for i := range src.Cols() {
col := &src.cols[i]
rt := col.dtype.gotype
rv := reflect.New(rt)
xx := rv.Interface()
data[i] = xx
}
for rows.Next() {
err = rows.Scan(data...)
if err != nil {
return err
}
err = dst.Write(data...)
if err != nil {
return err
}
}
err = rows.Err()
if err != nil {
return err
}
return err
case false:
nrows := end - beg
// reserve enough capacity for the new rows
dst.data = dst.data[:len(dst.data) : len(dst.data)+int(nrows)*src.rowsz]
for irow := beg; irow < end; irow++ {
pstart := src.rowsz * int(irow)
pend := pstart + src.rowsz
row := src.data[pstart:pend]
dst.data = append(dst.data, row...)
}
dst.nrows += nrows
dst.hdr.Axes()[1] += int(nrows)
}
return err
}