View Javadoc
1   package nom.tam.fits;
2   
3   import java.io.PrintStream;
4   
5   import nom.tam.fits.header.IFitsHeader;
6   import nom.tam.fits.header.Standard;
7   import nom.tam.util.ArrayDataOutput;
8   import nom.tam.util.ArrayFuncs;
9   import nom.tam.util.ColumnTable;
10  import nom.tam.util.Cursor;
11  
12  /*
13   * #%L
14   * nom.tam FITS library
15   * %%
16   * Copyright (C) 2004 - 2024 nom-tam-fits
17   * %%
18   * This is free and unencumbered software released into the public domain.
19   *
20   * Anyone is free to copy, modify, publish, use, compile, sell, or
21   * distribute this software, either in source code form or as a compiled
22   * binary, for any purpose, commercial or non-commercial, and by any
23   * means.
24   *
25   * In jurisdictions that recognize copyright laws, the author or authors
26   * of this software dedicate any and all copyright interest in the
27   * software to the public domain. We make this dedication for the benefit
28   * of the public at large and to the detriment of our heirs and
29   * successors. We intend this dedication to be an overt act of
30   * relinquishment in perpetuity of all present and future rights to this
31   * software under copyright law.
32   *
33   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
34   * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
35   * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
36   * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
37   * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
38   * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
39   * OTHER DEALINGS IN THE SOFTWARE.
40   * #L%
41   */
42  
43  import static nom.tam.fits.header.Standard.NAXIS1;
44  import static nom.tam.fits.header.Standard.NAXIS2;
45  import static nom.tam.fits.header.Standard.TDIMn;
46  import static nom.tam.fits.header.Standard.TDISPn;
47  import static nom.tam.fits.header.Standard.TFIELDS;
48  import static nom.tam.fits.header.Standard.TFORMn;
49  import static nom.tam.fits.header.Standard.TNULLn;
50  import static nom.tam.fits.header.Standard.TSCALn;
51  import static nom.tam.fits.header.Standard.TTYPEn;
52  import static nom.tam.fits.header.Standard.TUNITn;
53  import static nom.tam.fits.header.Standard.TZEROn;
54  import static nom.tam.fits.header.Standard.XTENSION;
55  
56  /**
57   * Binary table header/data unit.
58   * 
59   * @see BinaryTable
60   * @see AsciiTableHDU
61   */
62  @SuppressWarnings("deprecation")
63  public class BinaryTableHDU extends TableHDU<BinaryTable> {
64  
65      /** The standard column keywords for a binary table. */
66      private static final IFitsHeader[] KEY_STEMS = {TTYPEn, TFORMn, TUNITn, TNULLn, TSCALn, TZEROn, TDISPn, TDIMn};
67  
68      /**
69       * Creates a new binary table HDU from the specified FITS header and associated table data
70       * 
71       * @deprecated       (<i>for internal use</i>) Its visibility should be reduced to package level in the future.
72       * 
73       * @param      hdr   the FITS header describing the data and any user-specific keywords
74       * @param      datum the corresponding data object
75       */
76      public BinaryTableHDU(Header hdr, BinaryTable datum) {
77          super(hdr, datum);
78      }
79  
80      /**
81       * Wraps the specified table in an HDU, creating a header for it with the essential table description. Users may
82       * want to complete the table description with optional FITS keywords such as <code>TTYPEn</code>,
83       * <code>TUNITn</code> etc. It is strongly recommended that the table structure (rows or columns) isn't altered
84       * after the table is encompassed in an HDU, since there is no guarantee that the header description will be kept in
85       * sync.
86       * 
87       * @param  tab           the binary table to wrap into a new HDU
88       * 
89       * @return               A new HDU encompassing and describing the supplied table.
90       * 
91       * @throws FitsException if the table structure is invalid, and cannot be described in a header (should never really
92       *                           happen, but we keep the possibility open to it).
93       * 
94       * @see                  BinaryTable#toHDU()
95       * 
96       * @since                1.18
97       */
98      public static BinaryTableHDU wrap(BinaryTable tab) throws FitsException {
99          BinaryTableHDU hdu = new BinaryTableHDU(new Header(), tab);
100         tab.fillHeader(hdu.myHeader);
101         return hdu;
102     }
103 
104     @Override
105     protected final String getCanonicalXtension() {
106         return Standard.XTENSION_BINTABLE;
107     }
108 
109     /**
110      * @deprecated               (<i>for internal use</i>) Use {@link BinaryTable#fromColumnMajor(Object[])} or
111      *                               {@link BinaryTable#fromRowMajor(Object[][])} instead. Will reduce visibility in the
112      *                               future.
113      *
114      * @return                   Encapsulate data in a BinaryTable data type
115      *
116      * @param      o             data to encapsulate
117      *
118      * @throws     FitsException if the type of the data is not usable as data
119      */
120     @Deprecated
121     public static BinaryTable encapsulate(Object o) throws FitsException {
122         if (o instanceof ColumnTable) {
123             return new BinaryTable((ColumnTable<?>) o);
124         }
125         if (o instanceof Object[][]) {
126             return BinaryTable.fromRowMajor((Object[][]) o);
127         }
128         if (o instanceof Object[]) {
129             return BinaryTable.fromColumnMajor((Object[]) o);
130         }
131         throw new FitsException("Unable to encapsulate object of type:" + o.getClass().getName() + " as BinaryTable");
132     }
133 
134     /**
135      * Check if this data object is consistent with a binary table.
136      *
137      * @param      o a column table object, an Object[][], or an Object[]. This routine doesn't check that the
138      *                   dimensions of arrays are properly consistent.
139      * 
140      * @return       <code>true</code> if the data object can be represented as a FITS binary table, otherwise
141      *                   <code>false</code>.
142      *
143      * @deprecated   (<i>for internal use</i>) Will reduce visibility in the future
144      */
145     @Deprecated
146     public static boolean isData(Object o) {
147         return o instanceof nom.tam.util.ColumnTable || o instanceof Object[][] || o instanceof Object[];
148     }
149 
150     /**
151      * Check that this is a valid binary table header.
152      *
153      * @deprecated        (<i>for internal use</i>) Will reduce visibility in the future
154      *
155      * @param      header to validate.
156      *
157      * @return            <CODE>true</CODE> if this is a binary table header.
158      */
159     @Deprecated
160     public static boolean isHeader(Header header) {
161         String xten = header.getStringValue(XTENSION);
162         if (xten == null) {
163             return false;
164         }
165         xten = xten.trim();
166         return xten.equals(Standard.XTENSION_BINTABLE) || xten.equals("A3DTABLE");
167     }
168 
169     /**
170      * Prepares a data object into which the actual data can be read from an input subsequently or at a later time.
171      *
172      * @deprecated               (<i>for internal use</i>) Will reduce visibility in the future
173      *
174      * @param      header        The FITS header that describes the data
175      *
176      * @return                   A data object that support reading content from a stream.
177      *
178      * @throws     FitsException if the data could not be prepared to prescriotion.
179      */
180     @Deprecated
181     public static BinaryTable manufactureData(Header header) throws FitsException {
182         return new BinaryTable(header);
183     }
184 
185     /**
186      * @deprecated               (<i>for internal use</i>) Will reduce visibility in the future
187      *
188      * @return                   a newly created binary table HDU from the supplied data.
189      *
190      * @param      data          the data used to build the binary table. This is typically some kind of array of
191      *                               objects.
192      *
193      * @throws     FitsException if there was a problem with the data.
194      */
195     @Deprecated
196     public static Header manufactureHeader(Data data) throws FitsException {
197         Header hdr = new Header();
198         data.fillHeader(hdr);
199         return hdr;
200     }
201 
202     @Override
203     public int addColumn(Object data) throws FitsException {
204         int n = myData.addColumn(data);
205         myHeader.addValue(Standard.NAXISn.n(1), myData.getRowBytes());
206         Cursor<String, HeaderCard> c = myHeader.iterator();
207         c.end();
208         myData.fillForColumn(myHeader, c, n - 1);
209         return super.addColumn(data);
210     }
211 
212     /**
213      * For internal use. Returns the FITS header key stems to use for describing binary tables.
214      * 
215      * @return an array of standatd header colum knetwords stems.
216      */
217     protected static IFitsHeader[] binaryTableColumnKeyStems() {
218         return KEY_STEMS;
219     }
220 
221     @Override
222     protected IFitsHeader[] columnKeyStems() {
223         return BinaryTableHDU.KEY_STEMS;
224     }
225 
226     @Override
227     public void info(PrintStream stream) {
228         stream.println("  Binary Table");
229         stream.println("      Header Information:");
230 
231         int nhcol = myHeader.getIntValue(TFIELDS, -1);
232         int nrow = myHeader.getIntValue(NAXIS2, -1);
233         int rowsize = myHeader.getIntValue(NAXIS1, -1);
234 
235         stream.print("          " + nhcol + " fields");
236         stream.println(", " + nrow + " rows of length " + rowsize);
237 
238         for (int i = 1; i <= nhcol; i++) {
239             stream.print("           " + i + ":");
240             prtField(stream, "Name", TTYPEn.n(i).key());
241             prtField(stream, "Format", TFORMn.n(i).key());
242             prtField(stream, "Dimens", TDIMn.n(i).key());
243             stream.println("");
244         }
245 
246         stream.println("      Data Information:");
247         stream.println("          Number of rows=" + myData.getNRows());
248         stream.println("          Number of columns=" + myData.getNCols());
249         stream.println("          Heap size is: " + myData.getParameterSize() + " bytes");
250 
251         Object[] cols = myData.getFlatColumns();
252         for (int i = 0; i < cols.length; i++) {
253             stream.println("           " + i + ":" + ArrayFuncs.arrayDescription(cols[i]));
254         }
255     }
256 
257     /**
258      * Check that this HDU has a valid header.
259      *
260      * @deprecated (<i>for internal use</i>) Will reduce visibility in the future
261      *
262      * @return     <CODE>true</CODE> if this HDU has a valid header.
263      */
264     @Deprecated
265     public boolean isHeader() {
266         return isHeader(myHeader);
267     }
268 
269     private void prtField(PrintStream stream, String type, String field) {
270         String val = myHeader.getStringValue(field);
271         if (val != null) {
272             stream.print(type + '=' + val + "; ");
273         }
274     }
275 
276     /**
277      * Returns a copy of the column descriptor of a given column in this table
278      * 
279      * @param  col the zero-based column index
280      * 
281      * @return     a copy of the column's descriptor
282      * 
283      * @see        BinaryTable#getDescriptor(int)
284      * 
285      * @since      1.18
286      */
287     public BinaryTable.ColumnDesc getColumnDescriptor(int col) {
288         return myData.getDescriptor(col);
289     }
290 
291     @Override
292     public void setColumnName(int index, String name, String comment)
293             throws IndexOutOfBoundsException, HeaderCardException {
294         super.setColumnName(index, name, comment);
295         getColumnDescriptor(index).name(name);
296     }
297 
298     /**
299      * Converts a column from FITS logical values to bits. Null values (allowed in logical columns) will map to
300      * <code>false</code>. It is legal to call this on a column that is already containing bits.
301      *
302      * @param  col           The zero-based index of the column to be reset.
303      *
304      * @return               Whether the conversion was possible. *
305      * 
306      * @throws FitsException if the header could not be updated
307      * 
308      * @since                1.18
309      */
310     public final boolean convertToBits(int col) throws FitsException {
311         if (!myData.convertToBits(col)) {
312             return false;
313         }
314 
315         // Update TFORM keyword
316         myHeader.getCard(Standard.TFORMn.n(col + 1)).setValue(getColumnDescriptor(col).getTFORM());
317 
318         return true;
319     }
320 
321     /**
322      * Convert a column in the table to complex. Only tables with appropriate types and dimensionalities can be
323      * converted. It is legal to call this on a column that is already complex.
324      *
325      * @param  index         The zero-based index of the column to be converted.
326      *
327      * @return               Whether the column can be converted
328      *
329      * @throws FitsException if the header could not be updated
330      * 
331      * @see                  BinaryTableHDU#setComplexColumn(int)
332      */
333     public boolean setComplexColumn(int index) throws FitsException {
334         if (!myData.setComplexColumn(index)) {
335             return false;
336         }
337 
338         // Update TFORM keyword
339         myHeader.getCard(Standard.TFORMn.n(index + 1)).setValue(getColumnDescriptor(index).getTFORM());
340 
341         // Update or remove existing TDIM keyword
342         if (myHeader.containsKey(Standard.TDIMn.n(index + 1))) {
343             String tdim = getColumnDescriptor(index).getTDIM();
344             if (tdim != null) {
345                 myHeader.getCard(Standard.TDIMn.n(index + 1)).setValue(tdim);
346             } else {
347                 myHeader.deleteKey(Standard.TDIMn.n(index + 1));
348             }
349         }
350 
351         return true;
352     }
353 
354     // Need to tell header about the Heap before writing.
355     @Override
356     public void write(ArrayDataOutput out) throws FitsException {
357         myData.fillHeader(myHeader, false);
358         super.write(out);
359     }
360 }