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  import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
57  
58  /**
59   * Binary table header/data unit.
60   * 
61   * @see BinaryTable
62   * @see AsciiTableHDU
63   */
64  @SuppressWarnings("deprecation")
65  public class BinaryTableHDU extends TableHDU<BinaryTable> {
66  
67      /** The standard column keywords for a binary table. */
68      private static final IFitsHeader[] KEY_STEMS = {TTYPEn, TFORMn, TUNITn, TNULLn, TSCALn, TZEROn, TDISPn, TDIMn};
69  
70      /**
71       * Creates a new binary table HDU from the specified FITS header and associated table data
72       * 
73       * @deprecated       (<i>for internal use</i>) Its visibility should be reduced to package level in the future.
74       * 
75       * @param      hdr   the FITS header describing the data and any user-specific keywords
76       * @param      datum the corresponding data object
77       */
78      public BinaryTableHDU(Header hdr, BinaryTable datum) {
79          super(hdr, datum);
80      }
81  
82      /**
83       * Wraps the specified table in an HDU, creating a header for it with the essential table description. Users may
84       * want to complete the table description with optional FITS keywords such as <code>TTYPEn</code>,
85       * <code>TUNITn</code> etc. It is strongly recommended that the table structure (rows or columns) isn't altered
86       * after the table is encompassed in an HDU, since there is no guarantee that the header description will be kept in
87       * sync.
88       * 
89       * @param  tab           the binary table to wrap into a new HDU
90       * 
91       * @return               A new HDU encompassing and describing the supplied table.
92       * 
93       * @throws FitsException if the table structure is invalid, and cannot be described in a header (should never really
94       *                           happen, but we keep the possibility open to it).
95       * 
96       * @see                  BinaryTable#toHDU()
97       * 
98       * @since                1.18
99       */
100     public static BinaryTableHDU wrap(BinaryTable tab) throws FitsException {
101         BinaryTableHDU hdu = new BinaryTableHDU(new Header(), tab);
102         tab.fillHeader(hdu.myHeader);
103         return hdu;
104     }
105 
106     @Override
107     protected final String getCanonicalXtension() {
108         return Standard.XTENSION_BINTABLE;
109     }
110 
111     /**
112      * @deprecated               (<i>for internal use</i>) Use {@link BinaryTable#fromColumnMajor(Object[])} or
113      *                               {@link BinaryTable#fromRowMajor(Object[][])} instead. Will reduce visibility in the
114      *                               future.
115      *
116      * @return                   Encapsulate data in a BinaryTable data type
117      *
118      * @param      o             data to encapsulate
119      *
120      * @throws     FitsException if the type of the data is not usable as data
121      */
122     @Deprecated
123     public static BinaryTable encapsulate(Object o) throws FitsException {
124         if (o instanceof ColumnTable) {
125             return new BinaryTable((ColumnTable<?>) o);
126         }
127         if (o instanceof Object[][]) {
128             return BinaryTable.fromRowMajor((Object[][]) o);
129         }
130         if (o instanceof Object[]) {
131             return BinaryTable.fromColumnMajor((Object[]) o);
132         }
133         throw new FitsException("Unable to encapsulate object of type:" + o.getClass().getName() + " as BinaryTable");
134     }
135 
136     /**
137      * Check if this data object is consistent with a binary table.
138      *
139      * @param      o a column table object, an Object[][], or an Object[]. This routine doesn't check that the
140      *                   dimensions of arrays are properly consistent.
141      * 
142      * @return       <code>true</code> if the data object can be represented as a FITS binary table, otherwise
143      *                   <code>false</code>.
144      *
145      * @deprecated   (<i>for internal use</i>) Will reduce visibility in the future
146      */
147     @SuppressFBWarnings(value = "HSM_HIDING_METHOD", justification = "deprecated existing method, kept for compatibility")
148     @Deprecated
149     public static boolean isData(Object o) {
150         return o instanceof nom.tam.util.ColumnTable || o instanceof Object[][] || o instanceof Object[];
151     }
152 
153     /**
154      * Check that this is a valid binary table header.
155      *
156      * @deprecated        (<i>for internal use</i>) Will reduce visibility in the future
157      *
158      * @param      header to validate.
159      *
160      * @return            <CODE>true</CODE> if this is a binary table header.
161      */
162     @SuppressFBWarnings(value = "HSM_HIDING_METHOD", justification = "deprecated existing method, kept for compatibility")
163     @Deprecated
164     public static boolean isHeader(Header header) {
165         String xten = header.getStringValue(XTENSION);
166         if (xten == null) {
167             return false;
168         }
169         xten = xten.trim();
170         return xten.equals(Standard.XTENSION_BINTABLE) || xten.equals("A3DTABLE");
171     }
172 
173     /**
174      * Prepares a data object into which the actual data can be read from an input subsequently or at a later time.
175      *
176      * @deprecated               (<i>for internal use</i>) Will reduce visibility in the future
177      *
178      * @param      header        The FITS header that describes the data
179      *
180      * @return                   A data object that support reading content from a stream.
181      *
182      * @throws     FitsException if the data could not be prepared to prescriotion.
183      */
184     @Deprecated
185     public static BinaryTable manufactureData(Header header) throws FitsException {
186         return new BinaryTable(header);
187     }
188 
189     /**
190      * @deprecated               (<i>for internal use</i>) Will reduce visibility in the future
191      *
192      * @return                   a newly created binary table HDU from the supplied data.
193      *
194      * @param      data          the data used to build the binary table. This is typically some kind of array of
195      *                               objects.
196      *
197      * @throws     FitsException if there was a problem with the data.
198      */
199     @Deprecated
200     public static Header manufactureHeader(Data data) throws FitsException {
201         Header hdr = new Header();
202         data.fillHeader(hdr);
203         return hdr;
204     }
205 
206     @Override
207     public int addColumn(Object data) throws FitsException {
208         int n = myData.addColumn(data);
209         myHeader.addValue(Standard.NAXISn.n(1), myData.getRowBytes());
210         Cursor<String, HeaderCard> c = myHeader.iterator();
211         c.end();
212         myData.fillForColumn(myHeader, c, n - 1);
213         return super.addColumn(data);
214     }
215 
216     /**
217      * For internal use. Returns the FITS header key stems to use for describing binary tables.
218      * 
219      * @return an array of standatd header colum knetwords stems.
220      */
221     protected static IFitsHeader[] binaryTableColumnKeyStems() {
222         return KEY_STEMS;
223     }
224 
225     @Override
226     protected IFitsHeader[] columnKeyStems() {
227         return BinaryTableHDU.KEY_STEMS;
228     }
229 
230     @Override
231     public void info(PrintStream stream) {
232         stream.println("  Binary Table");
233         stream.println("      Header Information:");
234 
235         int nhcol = myHeader.getIntValue(TFIELDS, -1);
236         int nrow = myHeader.getIntValue(NAXIS2, -1);
237         int rowsize = myHeader.getIntValue(NAXIS1, -1);
238 
239         stream.print("          " + nhcol + " fields");
240         stream.println(", " + nrow + " rows of length " + rowsize);
241 
242         for (int i = 1; i <= nhcol; i++) {
243             stream.print("           " + i + ":");
244             prtField(stream, "Name", TTYPEn.n(i).key());
245             prtField(stream, "Format", TFORMn.n(i).key());
246             prtField(stream, "Dimens", TDIMn.n(i).key());
247             stream.println("");
248         }
249 
250         stream.println("      Data Information:");
251         stream.println("          Number of rows=" + myData.getNRows());
252         stream.println("          Number of columns=" + myData.getNCols());
253         stream.println("          Heap size is: " + myData.getParameterSize() + " bytes");
254 
255         Object[] cols = myData.getFlatColumns();
256         for (int i = 0; i < cols.length; i++) {
257             stream.println("           " + i + ":" + ArrayFuncs.arrayDescription(cols[i]));
258         }
259     }
260 
261     /**
262      * Check that this HDU has a valid header.
263      *
264      * @deprecated (<i>for internal use</i>) Will reduce visibility in the future
265      *
266      * @return     <CODE>true</CODE> if this HDU has a valid header.
267      */
268     @Deprecated
269     public boolean isHeader() {
270         return isHeader(myHeader);
271     }
272 
273     private void prtField(PrintStream stream, String type, String field) {
274         String val = myHeader.getStringValue(field);
275         if (val != null) {
276             stream.print(type + '=' + val + "; ");
277         }
278     }
279 
280     /**
281      * Returns a copy of the column descriptor of a given column in this table
282      * 
283      * @param  col the zero-based column index
284      * 
285      * @return     a copy of the column's descriptor
286      * 
287      * @see        BinaryTable#getDescriptor(int)
288      * 
289      * @since      1.18
290      */
291     public BinaryTable.ColumnDesc getColumnDescriptor(int col) {
292         return myData.getDescriptor(col);
293     }
294 
295     @Override
296     public void setColumnName(int index, String name, String comment)
297             throws IndexOutOfBoundsException, HeaderCardException {
298         super.setColumnName(index, name, comment);
299         getColumnDescriptor(index).name(name);
300     }
301 
302     /**
303      * Converts a column from FITS logical values to bits. Null values (allowed in logical columns) will map to
304      * <code>false</code>. It is legal to call this on a column that is already containing bits.
305      *
306      * @param  col           The zero-based index of the column to be reset.
307      *
308      * @return               Whether the conversion was possible. *
309      * 
310      * @throws FitsException if the header could not be updated
311      * 
312      * @since                1.18
313      */
314     public final boolean convertToBits(int col) throws FitsException {
315         if (!myData.convertToBits(col)) {
316             return false;
317         }
318 
319         // Update TFORM keyword
320         myHeader.getCard(Standard.TFORMn.n(col + 1)).setValue(getColumnDescriptor(col).getTFORM());
321 
322         return true;
323     }
324 
325     /**
326      * Convert a column in the table to complex. Only tables with appropriate types and dimensionalities can be
327      * converted. It is legal to call this on a column that is already complex.
328      *
329      * @param  index         The zero-based index of the column to be converted.
330      *
331      * @return               Whether the column can be converted
332      *
333      * @throws FitsException if the header could not be updated
334      * 
335      * @see                  BinaryTableHDU#setComplexColumn(int)
336      */
337     public boolean setComplexColumn(int index) throws FitsException {
338         if (!myData.setComplexColumn(index)) {
339             return false;
340         }
341 
342         // Update TFORM keyword
343         myHeader.getCard(Standard.TFORMn.n(index + 1)).setValue(getColumnDescriptor(index).getTFORM());
344 
345         // Update or remove existing TDIM keyword
346         if (myHeader.containsKey(Standard.TDIMn.n(index + 1))) {
347             String tdim = getColumnDescriptor(index).getTDIM();
348             if (tdim != null) {
349                 myHeader.getCard(Standard.TDIMn.n(index + 1)).setValue(tdim);
350             } else {
351                 myHeader.deleteKey(Standard.TDIMn.n(index + 1));
352             }
353         }
354 
355         return true;
356     }
357 
358     // Need to tell header about the Heap before writing.
359     @Override
360     public void write(ArrayDataOutput out) throws FitsException {
361         myData.fillHeader(myHeader, false);
362         super.write(out);
363     }
364 }