View Javadoc
1   package nom.tam.fits.header;
2   
3   /*-
4    * #%L
5    * nom.tam.fits
6    * %%
7    * Copyright (C) 1996 - 2024 nom-tam-fits
8    * %%
9    * This is free and unencumbered software released into the public domain.
10   * 
11   * Anyone is free to copy, modify, publish, use, compile, sell, or
12   * distribute this software, either in source code form or as a compiled
13   * binary, for any purpose, commercial or non-commercial, and by any
14   * means.
15   * 
16   * In jurisdictions that recognize copyright laws, the author or authors
17   * of this software dedicate any and all copyright interest in the
18   * software to the public domain. We make this dedication for the benefit
19   * of the public at large and to the detriment of our heirs and
20   * successors. We intend this dedication to be an overt act of
21   * relinquishment in perpetuity of all present and future rights to this
22   * software under copyright law.
23   * 
24   * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
25   * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
26   * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
27   * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
28   * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
29   * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
30   * OTHER DEALINGS IN THE SOFTWARE.
31   * #L%
32   */
33  
34  import java.util.AbstractMap;
35  import java.util.ArrayList;
36  import java.util.Map;
37  import java.util.StringTokenizer;
38  
39  import nom.tam.fits.FitsException;
40  import nom.tam.fits.Header;
41  
42  /**
43   * <p>
44   * A mapping of image coordinate values for a coordinate axis with {@link WCS#CTYPEna} = <code>'STOKES'</code> (or
45   * equivalent), specifying polarization (or cross-polarization) data products along the image direction. The FITS
46   * standard (4.0) defines a mapping of pixel coordinate values along an image imension to Stokes parameters, and this
47   * enum provides an implementation of that for this library.
48   * </p>
49   * <p>
50   * A dataset may typically contain 4 or 8 Stokes parameters (or fewer), which depending on the type of measurement can
51   * be (I, Q, U, [V]), or (RR, LL, RL, LR) and/or (XX, YY, XY, YX). As such, the corresponding {@link WCS#CRPIXna} is
52   * typically 0 and {@link WCS#CDELTna} is +/- 1, and depending on the type of measurement {@link WCS#CRVALna} is 1, or
53   * -1, or -5. You can use the {@link Parameters} subclass to help populate or interpret Stokes parameters in headers.
54   * </p>
55   * 
56   * @author Attila Kovacs
57   * 
58   * @since  1.20
59   * 
60   * @see    WCS
61   * @see    #parameters()
62   */
63  public enum Stokes {
64      /** Stokes I: total (polarized + unpolarized) power */
65      I(1),
66  
67      /** Stokes Q: linear polarization Q component */
68      Q(2),
69  
70      /** Stokes U: linear polarization U component */
71      U(3),
72  
73      /** Stokes V: circular polarization */
74      V(4),
75  
76      /** circular cross-polarization between two right-handed wave components */
77      RR(-1),
78  
79      /** circular cross-polarization between two left-handed wave components */
80      LL(-2),
81  
82      /** circular cross-polarization between a right-handed (input 1) and a left-handed (input 2) wave component */
83      RL(-3),
84  
85      /** circular cross-polarization between a left-handed (input 1) and a right-handed (input 2) wave component */
86      LR(-4),
87  
88      /** linear cross-polarization between two 'horizontal' wave components (in local orientation) */
89      XX(-5),
90  
91      /** linear cross-polarization between two 'vertical' wave components (in local orientation) */
92      YY(-6),
93  
94      /**
95       * linear cross-polarization between a 'horizontal' (input 1) and a 'vertical' (input 2) wave component (in local
96       * orientation)
97       */
98      XY(-7),
99  
100     /**
101      * linear cross-polarization between a 'vertical' (input 1) and a 'horizontal' (input 2) wave component (in local
102      * orientation)
103      */
104     YX(-8);
105 
106     /** The value to use for CTYPE type keywords to indicate Stokes parameter data */
107     public static final String CTYPE = "STOKES";
108 
109     private int index;
110 
111     private static Stokes[] ordered = {YX, XY, YY, XX, LR, RL, LL, RR, null, I, Q, U, V};
112 
113     private static final int STANDARD_PARAMETER_COUNT = 4;
114     private static final int FULL_PARAMETER_COUNT = 8;
115 
116     Stokes(int value) {
117         this.index = value;
118     }
119 
120     /**
121      * Returns the WCS coordinate value corresponding to this Stokes parameter for an image coordinate with
122      * {@link WCS#CTYPEna} = <code>'STOKES'</code>.
123      * 
124      * @return the WCS coordinate value corresponding to this Stokes parameter.
125      * 
126      * @see    #forCoordinateValue(int)
127      * @see    WCS#CTYPEna
128      * @see    WCS#CRVALna
129      */
130     public final int getCoordinateValue() {
131         return index;
132     }
133 
134     /**
135      * Returns the Stokes parameter for the given pixel coordinate value for an image coordinate with
136      * {@link WCS#CTYPEna} = <code>'STOKES'</code>.
137      * 
138      * @param  value                     The image coordinate value
139      * 
140      * @return                           The Stokes parameter, which corresponds to that coordinate value. For values
141      *                                       1--4, the singular Stokes parameters I, Q, U, or V is returned. For
142      *                                       negative values, -1 through -8, the cross polarization parameters are
143      *                                       returned. For all other values and `IndexOutOfBoundsException` is thrown
144      * 
145      * @throws IndexOutOfBoundsException if the coordinate value is 0 or out of the range of acceptable Stokes
146      *                                       coordinate values.
147      * 
148      * @see                              #getCoordinateValue()
149      */
150     public static Stokes forCoordinateValue(int value) throws IndexOutOfBoundsException {
151         if (value == 0) {
152             throw new IndexOutOfBoundsException(
153                     "Value must be in the range [1:4] for single-ended or else [-1:-8] for cross-polarization.");
154         }
155         return ordered[value - YX.getCoordinateValue()];
156     }
157 
158     /**
159      * Helper class for setting or interpreting a set of measured Stokes parameters stored along an array dimension. Two
160      * instances of Stokes parameters are considered equal if they measure the same polarization terms, in the same
161      * order.
162      * 
163      * @author Attila Kovacs
164      * 
165      * @since  1.20
166      */
167     public static final class Parameters {
168         private int flags;
169         private int offset;
170         private int step;
171         private int count;
172 
173         private Parameters(int flags) {
174             this.flags = flags;
175 
176             boolean reversed = (flags & REVERSED_ORDER) != 0;
177 
178             step = reversed ? -1 : 1;
179             count = STANDARD_PARAMETER_COUNT;
180 
181             if ((flags & FULL_CROSS_POLARIZATION) == 0) {
182                 offset = reversed ? Stokes.V.getCoordinateValue() : Stokes.I.getCoordinateValue();
183             } else {
184                 step = -step;
185 
186                 if ((flags & CIRCULAR_CROSS_POLARIZATION) == 0) {
187                     offset = reversed ? Stokes.YX.getCoordinateValue() : Stokes.XX.getCoordinateValue();
188                 } else if ((flags & LINEAR_CROSS_POLARIZATION) == 0) {
189                     offset = reversed ? Stokes.LR.getCoordinateValue() : Stokes.RR.getCoordinateValue();
190                 } else {
191                     offset = reversed ? Stokes.YX.getCoordinateValue() : Stokes.RR.getCoordinateValue();
192                     count = FULL_PARAMETER_COUNT;
193                 }
194             }
195         }
196 
197         private Parameters(int offset, int step, int n) {
198             this.offset = offset;
199             this.step = step;
200             this.count = n;
201 
202             if (offset < 0) {
203                 int end = offset + (n - 1) * step;
204 
205                 if (Math.min(offset, end) <= XX.index) {
206                     flags |= LINEAR_CROSS_POLARIZATION;
207                 }
208 
209                 if (Math.max(offset, end) > XX.index) {
210                     flags |= CIRCULAR_CROSS_POLARIZATION;
211                 }
212 
213                 step = -step;
214             }
215 
216             if (step < 0) {
217                 flags |= REVERSED_ORDER;
218             }
219         }
220 
221         @Override
222         public int hashCode() {
223             return flags ^ Integer.hashCode(offset) ^ Integer.hashCode(step);
224         }
225 
226         @Override
227         public boolean equals(Object o) {
228             if (!(o instanceof Parameters)) {
229                 return false;
230             }
231             Parameters p = (Parameters) o;
232             if (p.flags != flags) {
233                 return false;
234             }
235             if (p.offset != offset) {
236                 return false;
237             }
238             if (p.step != step) {
239                 return false;
240             }
241             return true;
242         }
243 
244         boolean isReversedOrder() {
245             return (flags & REVERSED_ORDER) != 0;
246         }
247 
248         /**
249          * Checks if the parameters are for measuring cross-polarization between two inputs.
250          * 
251          * @return <code>true</code> if it is for cross polarization, otherwise <code>false</code>.
252          */
253         public boolean isCrossPolarization() {
254             return (flags & FULL_CROSS_POLARIZATION) != 0;
255         }
256 
257         /**
258          * Checks if the parameters include linear polarization terms.
259          * 
260          * @return <code>true</code> if linear polarization is measured, otherwise <code>false</code>.
261          */
262         public boolean hasLinearPolarization() {
263             return (flags & FULL_CROSS_POLARIZATION) != CIRCULAR_CROSS_POLARIZATION;
264         }
265 
266         /**
267          * Checks if the parameters include circular polarization term(s).
268          * 
269          * @return <code>true</code> if cirular cross polarization is measured, otherwise <code>false</code>.
270          */
271         public boolean hasCircularPolarization() {
272             return (flags & FULL_CROSS_POLARIZATION) != LINEAR_CROSS_POLARIZATION;
273         }
274 
275         /**
276          * Returns the Stokes parameter for a given Java array index for a dimension that corresponds to the Stokes
277          * parameters described by this instance.
278          * 
279          * @param  idx                       the zero-based Java array index, typically [0:3] for single-ended
280          *                                       polarization or circular or linear-only cross-polarization, or else
281          *                                       [0:7] for full cross-polarization.
282          * 
283          * @return                           The specific Stokes parameter corresponding to the specified array index.
284          * 
285          * @throws IndexOutOfBoundsException if the index is outside of the expected range.
286          * 
287          * @see                              #getAvailableParameters()
288          * 
289          * @since                            1.19.1
290          */
291         public Stokes getParameter(int idx) throws IndexOutOfBoundsException {
292             if (idx < 0 || idx >= count) {
293                 throw new IndexOutOfBoundsException();
294             }
295             return Stokes.forCoordinateValue(offset + step * idx);
296         }
297 
298         /**
299          * Returns the ordered list of parameters, which can be used to translate array indexes to Stokes values,
300          * supported by this parameter set.
301          * 
302          * @return the ordered list of available Stokes parameters in this measurement set.
303          * 
304          * @see    #getParameter(int)
305          */
306         public ArrayList<Stokes> getAvailableParameters() {
307             ArrayList<Stokes> list = new ArrayList<>(count);
308             for (int i = 0; i < count; i++) {
309                 list.add(getParameter(i));
310             }
311             return list;
312         }
313 
314         /**
315          * Returns the Java array index corresponding to a given Stokes parameters for this set of parameters.
316          * 
317          * @param  s the Stokes parameter of interest
318          * 
319          * @return   the zero-based Java array index corresponding to the given Stokes parameter.
320          * 
321          * @see      #getParameter(int)
322          * 
323          * @since    1.20
324          */
325         public int getArrayIndex(Stokes s) {
326             return (s.getCoordinateValue() - offset) / step;
327         }
328 
329         /**
330          * Adds WCS description for the coordinate axis containing Stokes parameters. The header must already contain a
331          * NAXIS keyword specifying the dimensionality of the data, or else a FitsException will be thrown.
332          * 
333          * @param  header                    the FITS header to populate (it must already have an NAXIS keyword
334          *                                       present).
335          * @param  coordinateIndex           The 0-based Java coordinate index for the array dimension that corresponds
336          *                                       to the stokes parameter.
337          * 
338          * @throws IndexOutOfBoundsException if the coordinate index is negative or out of bounds for the array
339          *                                       dimensions
340          * @throws FitsException             if the header does not contain an NAXIS keyword, or if the header is not
341          *                                       accessible
342          * 
343          * @see                              #fillTableHeader(Header, int, int)
344          * @see                              Stokes#fromImageHeader(Header)
345          * 
346          * @since                            1.20
347          */
348         public void fillImageHeader(Header header, int coordinateIndex) throws FitsException {
349             int n = header.getIntValue(Standard.NAXIS);
350             if (n == 0) {
351                 throw new FitsException("Missing NAXIS in header");
352             }
353             if (coordinateIndex < 0 || coordinateIndex >= n) {
354                 throw new IndexOutOfBoundsException(
355                         "Invalid Java coordinate index " + coordinateIndex + " (for " + n + " dimensions)");
356             }
357 
358             int i = n - coordinateIndex;
359 
360             header.addValue(WCS.CTYPEna.n(i), Stokes.CTYPE);
361             header.addValue(WCS.CRPIXna.n(i), 1);
362             header.addValue(WCS.CRVALna.n(i), offset);
363             header.addValue(WCS.CDELTna.n(i), step);
364         }
365 
366         /**
367          * Adds WCS description for the coordinate axis containing Stokes parameters to a table column containign
368          * images.
369          * 
370          * @param  header                    the binary table header to populate (it should already contain a TDIMn
371          *                                       keyword for the specified column, or else 1D data is assumed).
372          * @param  column                    the zero-based Java column index containing the 'image' array.
373          * @param  coordinateIndex           the zero-based Java coordinate index for the array dimension that
374          *                                       corresponds to the stokes parameter.
375          * 
376          * @throws IndexOutOfBoundsException if the coordinate index is negative or out of bounds for the array
377          *                                       dimensions, or if the column index is invalid.
378          * @throws FitsException             if the header does not specify the dimensionality of the array elements, or
379          *                                       if the header is not accessible
380          * 
381          * @see                              #fillImageHeader(Header, int)
382          * @see                              Stokes#fromTableHeader(Header, int)
383          * 
384          * @since                            1.20
385          */
386         public void fillTableHeader(Header header, int column, int coordinateIndex)
387                 throws IndexOutOfBoundsException, FitsException {
388             if (column < 0) {
389                 throw new IndexOutOfBoundsException("Invalid Java column index " + column);
390             }
391 
392             String dims = header.getStringValue(Standard.TDIMn.n(++column));
393             if (dims == null) {
394                 throw new FitsException("Missing TDIM" + column + " in header");
395             }
396 
397             StringTokenizer tokens = new StringTokenizer(dims, "(, )");
398             int n = tokens.countTokens();
399 
400             if (coordinateIndex < 0 || coordinateIndex >= n) {
401                 throw new IndexOutOfBoundsException(
402                         "Invalid Java coordinate index " + coordinateIndex + " (for " + n + " dimensions)");
403             }
404 
405             int i = n - coordinateIndex;
406 
407             header.addValue(WCS.nCTYPn.n(i, column), Stokes.CTYPE);
408             header.addValue(WCS.nCRPXn.n(i, column), 1);
409             header.addValue(WCS.nCRVLn.n(i, column), offset);
410             header.addValue(WCS.nCDLTn.n(i, column), step);
411         }
412     }
413 
414     /**
415      * Returns a new set of standard single-input Stokes parameters (I, Q, U, V).
416      * 
417      * @return the standard set of I, Q, U, V Stokes parameters.
418      * 
419      * @see    #parameters(int)
420      */
421     public static Parameters parameters() {
422         return parameters(0);
423     }
424 
425     /**
426      * Returns the set of Stokes parameters for the given bitwise flags, which may specify linear or cicular cross
427      * polarization, or both, and/or if the parameters are stored in reversed index order in the FITS. The flags can be
428      * bitwise OR'd, e.g. {@link #LINEAR_CROSS_POLARIZATION} | {@link #CIRCULAR_CROSS_POLARIZATION} will select Stokes
429      * parameters for measuring circular cross polarization, stored in reversed index order that is: (LR, RL, LL, RR).
430      * 
431      * @param  flags the bitwise flags specifying the type of Stokes parameters.
432      * 
433      * @return       the set of Stokes parameters for the given bitwise flags.
434      * 
435      * @see          #parameters()
436      * @see          #LINEAR_CROSS_POLARIZATION
437      * @see          #CIRCULAR_CROSS_POLARIZATION
438      * @see          #FULL_CROSS_POLARIZATION
439      */
440     public static Parameters parameters(int flags) {
441         return new Parameters(flags);
442     }
443 
444     /**
445      * Bitwise flag for Stokes parameters stored in reversed index order.
446      */
447     static final int REVERSED_ORDER = 1;
448 
449     /**
450      * Bitwise flag for dual-input linear cross polarization Stokes parameters (XX, YY, XY, YX)
451      */
452     public static final int LINEAR_CROSS_POLARIZATION = 2;
453 
454     /**
455      * Bitwise flag for dual-input circular cross polarization Stokes parameters (RR, LL, RL, LR)
456      */
457     public static final int CIRCULAR_CROSS_POLARIZATION = 4;
458 
459     /**
460      * Bitwise flag for dual-input full (linear + circular) cross polarization Stokes parameters (RR, LL, RL, LR, XX,
461      * YY, XY, YX). By definition tme as ({@link #CIRCULAR_CROSS_POLARIZATION} | {@link #LINEAR_CROSS_POLARIZATION}).
462      * 
463      * @see #CIRCULAR_CROSS_POLARIZATION
464      * @see #LINEAR_CROSS_POLARIZATION
465      */
466     public static final int FULL_CROSS_POLARIZATION = LINEAR_CROSS_POLARIZATION | CIRCULAR_CROSS_POLARIZATION;
467 
468     private static Parameters forCoords(double start, double delt, int count) throws FitsException {
469         int offset = (int) start;
470         if (start != offset) {
471             throw new FitsException("Invalid (non-integer) Stokes coordinate start: " + start);
472         }
473 
474         int step = (int) delt;
475         if (delt != step) {
476             throw new FitsException("Invalid (non-integer) Stokes coordinate step: " + delt);
477         }
478 
479         int end = offset + step * (count - 1);
480         if (Math.min(offset, end) <= 0 && Math.max(offset, end) >= 0) {
481             throw new FitsException("Invalid Stokes coordinate range: " + offset + ":" + end);
482         }
483 
484         return new Parameters(offset, step, count);
485     }
486 
487     /**
488      * Returns a mapping of a Java array dimension to a set of Stokes parameters, based on the WCS coordinate
489      * description in the image header. The header must already contain a NAXIS keyword specifying the dimensionality of
490      * the data, or else a FitsException will be thrown.
491      * 
492      * @param  header        the FITS header to populate (it must already have an NAXIS keyword present).
493      * 
494      * @return               A mapping from a zero-based Java array dimension which corresponds to the Stokes dimension
495      *                           of the data, to the set of stokes Parameters defined in that dimension; or
496      *                           <code>null</code> if the header does not contain a fully valid description of a Stokes
497      *                           coordinate axis.
498      * 
499      * @throws FitsException if the header does not contain an NAXIS keyword, necessary for translating Java array
500      *                           indices to FITS array indices, or if the CRVALn, CRPIXna or CDELTna values for the
501      *                           'STOKES' dimension are inconsistent with a Stokes coordinate definition.
502      * 
503      * @see                  #fromTableHeader(Header, int)
504      * @see                  Parameters#fillImageHeader(Header, int)
505      * 
506      * @since                1.20
507      */
508     @SuppressWarnings({"unchecked", "rawtypes"})
509     public static Map.Entry<Integer, Parameters> fromImageHeader(Header header) throws FitsException {
510         int n = header.getIntValue(Standard.NAXIS);
511         if (n <= 0) {
512             throw new FitsException("Missing, invalid, or insufficient NAXIS in header");
513         }
514 
515         for (int i = 1; i <= n; i++) {
516             if (Stokes.CTYPE.equalsIgnoreCase(header.getStringValue(WCS.CTYPEna.n(i)))) {
517                 if (header.getDoubleValue(WCS.CRPIXna.n(i), 1.0) != 1.0) {
518                     throw new FitsException("Invalid Stokes " + WCS.CRPIXna.n(i).key() + " value: "
519                             + header.getDoubleValue(WCS.CRPIXna.n(i)) + ", expected 1");
520                 }
521 
522                 Parameters p = forCoords(header.getDoubleValue(WCS.CRVALna.n(i), 0.0),
523                         header.getDoubleValue(WCS.CDELTna.n(i), 1.0), header.getIntValue(Standard.NAXISn.n(i), 1));
524 
525                 return new AbstractMap.SimpleImmutableEntry(n - i, p);
526             }
527         }
528 
529         return null;
530     }
531 
532     /**
533      * Returns a mapping of a Java array dimension to a set of Stokes parameters, based on the WCS coordinate
534      * description in the image header.
535      * 
536      * @param  header                    the FITS header to populate.
537      * @param  column                    the zero-based Java column index containing the 'image' array.
538      * 
539      * @return                           A mapping from a zero-based Java array dimension which corresponds to the
540      *                                       Stokes dimension of the data, to the set of stokes Parameters defined in
541      *                                       that dimension; or <code>null</code> if the header does not contain a fully
542      *                                       valid description of a Stokes coordinate axis.
543      * 
544      * @throws IndexOutOfBoundsException if the column index is invalid.
545      * @throws FitsException             if the header does not contain an TDIMn keyword for the column, necessary for
546      *                                       translating Java array indices to FITS array indices, or if the iCRVLn,
547      *                                       iCRPXn or iCDLTn values for the 'STOKES' dimension are inconsistent with a
548      *                                       Stokes coordinate definition.
549      * 
550      * @see                              #fromImageHeader(Header)
551      * @see                              Parameters#fillTableHeader(Header, int, int)
552      * 
553      * @since                            1.20
554      */
555     @SuppressWarnings({"unchecked", "rawtypes"})
556     public static Map.Entry<Integer, Parameters> fromTableHeader(Header header, int column)
557             throws IndexOutOfBoundsException, FitsException {
558         if (column < 0) {
559             throw new IndexOutOfBoundsException("Invalid Java column index " + column);
560         }
561 
562         String dims = header.getStringValue(Standard.TDIMn.n(++column));
563         if (dims == null) {
564             throw new FitsException("Missing TDIM" + column + " in header");
565         }
566 
567         StringTokenizer tokens = new StringTokenizer(dims, "(, )");
568         int n = tokens.countTokens();
569 
570         for (int i = 1; i <= n; i++) {
571             String d = tokens.nextToken();
572 
573             if (Stokes.CTYPE.equalsIgnoreCase(header.getStringValue(WCS.nCTYPn.n(i, column)))) {
574                 if (header.getDoubleValue(WCS.nCRPXn.n(i, column), 1.0) != 1.0) {
575                     throw new FitsException("Invalid Stokes " + WCS.nCRPXn.n(i, column).key() + " value: "
576                             + header.getDoubleValue(WCS.nCRPXn.n(i, column)) + ", expected 1");
577                 }
578 
579                 try {
580                     Parameters p = forCoords(header.getDoubleValue(WCS.nCRVLn.n(i, column), 0.0),
581                             header.getDoubleValue(WCS.nCDLTn.n(i, column), 1.0), Integer.parseInt(d));
582                     return new AbstractMap.SimpleImmutableEntry(n - i, p);
583                 } catch (NumberFormatException e) {
584                     throw new FitsException("Invalid " + Standard.TDIMn.n(column).key() + " value: '" + dims
585                             + "' (component: '" + d + "')");
586                 }
587             }
588         }
589 
590         return null;
591     }
592 }