View Javadoc
1   package nom.tam.util;
2   
3   /*
4    * #%L
5    * nom.tam FITS library
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.math.BigDecimal;
35  import java.math.BigInteger;
36  import java.math.RoundingMode;
37  import java.text.DecimalFormat;
38  import java.text.DecimalFormatSymbols;
39  import java.util.Locale;
40  
41  import nom.tam.fits.FitsFactory;
42  import nom.tam.fits.HeaderCard;
43  import nom.tam.fits.LongValueException;
44  
45  /**
46   * Formatting number values for use in FITS headers.
47   * 
48   * @author Attila Kovacs
49   * @since 1.16
50   */
51  public class FlexFormat {
52  
53      /**
54       * Constant to specify the precision (number of decimal places shown) should
55       * be the natural precision of the number type, or reduced at most to
56       * {@link #DOUBLE_DECIMALS} as necessary to fit in the alotted space.
57       */
58      public static final int AUTO_PRECISION = -1;
59  
60      /**
61       * The maximum number of decimal places to show (after the leading figure)
62       * for double-precision (64-bit) values.
63       */
64      public static final int DOUBLE_DECIMALS = 16;
65  
66      /**
67       * The maximum number of decimal places to show (after the leading figure)
68       * for single-precision (32-bit) values.
69       */
70      public static final int FLOAT_DECIMALS = 7;
71  
72      /**
73       * The minimum number of decimal places to show (after the leading figure)
74       * for big-decimal values. 64-bit longs are in the +-1E19 range, so they
75       * provide 18 decimals after the leading figure. We want big integer to
76       * provideat least as many decimal places as a long, when in exponential
77       * form...
78       */
79      public static final int MIN_BIGINT_EFORM_DECIMALS = 18;
80  
81      /**
82       * The exclusive upper limit floating point value that can be shown in fixed
83       * format. Values larger or equals to it will always be shown in exponential
84       * format. This is juist for human readability. If there are more than 5
85       * figures in front of the decimal place, they become harder to comprehend
86       * at first sight than the explicit powers of 10 of the exponential format.
87       */
88      private static final double MAX_FIXED = 1e6;
89  
90      /**
91       * The smallest floating point value that can be shown in fixed format.
92       * Values smallert than this value will always be printed in exponential
93       * format. This is juist for human readability. If there are more than 2
94       * leading zeroes in front of the decimal place, they become harder to
95       * comprehend at first sight than the explicit powers of 10 of the
96       * exponential format.
97       */
98      private static final double MIN_FIXED = 0.001;
99  
100     /**
101      * The maximum number of decimal places to show after the leading figure
102      * (i.e. fractional digits in exponential format). If the value has more
103      * precision than this value it will be rounded to the specified decimal
104      * place. The special value {@link #AUTO_PRECISION} can be used to display
105      * as many of the available decimal places as can fit into the space that is
106      * available (see {@link #setWidth(int)}.
107      */
108     private int decimals = AUTO_PRECISION;
109 
110     /**
111      * The maximum number of characters available for showing number values.
112      * This class will always return numbers that fit in that space, or else
113      * throw an exception.
114      */
115     private int width = HeaderCard.FITS_HEADER_CARD_SIZE;
116 
117     private static final DecimalFormatSymbols SYMBOLS = DecimalFormatSymbols.getInstance(Locale.US);
118 
119     /**
120      * Instantiates flexible-width number formatting for numbers in FITS
121      * headers.
122      */
123     public FlexFormat() {
124     }
125 
126     /**
127      * Sets the maximum number of decimal places to show after the leading
128      * figure (i.e. fractional digits in exponential format). If the value has
129      * more precision than this value it will be rounded to the specified
130      * decimal place. The special value {@link #AUTO_PRECISION} can be used to
131      * display as many of the available decimal places as can fit into the space
132      * that is available (see {@link #setWidth(int)}.
133      * 
134      * @param nDecimals
135      *            the requested new number of decimal places to show after the
136      *            leading figure, or {@link #AUTO_PRECISION}. If an explicit
137      *            value is set, all decimal values will be printed in
138      *            exponential format with up to that many fractional digits
139      *            showing before the exponent symbol.
140      * @return itself
141      * @see #autoPrecision()
142      * @see #getPrecision()
143      * @see #setWidth(int)
144      * @see #format(Number)
145      */
146     public synchronized FlexFormat setPrecision(int nDecimals) {
147         decimals = nDecimals < 0 ? AUTO_PRECISION : nDecimals;
148         return this;
149     }
150 
151     /**
152      * Selects flexible precision formatting of floating point values. The
153      * values will be printed either in fixed format or exponential format, with
154      * up to the number of decimal places supported by the underlying value. For
155      * {@link BigDecimal} and {@link BigInteger} types, the precision may be
156      * reduced at most down to {@link #DOUBLE_DECIMALS} to make it fit in the
157      * available space.
158      * 
159      * @return itself
160      * @see #setPrecision(int)
161      * @see #getPrecision()
162      * @see #setWidth(int)
163      * @see #format(Number)
164      */
165     public synchronized FlexFormat autoPrecision() {
166         return setPrecision(AUTO_PRECISION);
167     }
168 
169     /**
170      * Returns the maximum number of decimal places that will be shown when
171      * formatting floating point values in exponential form, or
172      * {@link #AUTO_PRECISION} if either fixed or exponential form may be used
173      * with up to the native precision of the value, or whatever precision can
174      * be shown in the space available.
175      * 
176      * @return the maximum number of decimal places that will be shown when
177      *         formatting floating point values, or {@link #AUTO_PRECISION}.
178      * @see #setPrecision(int)
179      * @see #autoPrecision()
180      * @see #setWidth(int)
181      */
182     public final synchronized int getPrecision() {
183         return decimals;
184     }
185 
186     /**
187      * Sets the number of characters that this formatter can use to print number
188      * values. Subsequent calls to {@link #format(Number)} will guarantee to
189      * return only values that are shorter or equals to the specified width, or
190      * else throw an exception.
191      * 
192      * @param nChars
193      *            the new maximum length for formatted values.
194      * @return itself
195      * @see #getWidth()
196      * @see #forCard(HeaderCard)
197      * @see #setPrecision(int)
198      * @see #format(Number)
199      */
200     public synchronized FlexFormat setWidth(int nChars) {
201         width = nChars > 0 ? nChars : 0;
202         return this;
203     }
204 
205     /**
206      * Sets the number of characters that this formatter can use to print number
207      * values to the space available for the value field in the specified header
208      * card. It is essentially a shorthand for
209      * <code>setWidth(card.spaceForValue())</code>.
210      * 
211      * @param card
212      *            the header card in which the formatted number values must fit.
213      * @return itself
214      */
215     public final FlexFormat forCard(HeaderCard card) {
216         return setWidth(card.spaceForValue());
217     }
218 
219     /**
220      * Returns the number of characters that this formatter can use to print
221      * number values
222      * 
223      * @return the maximum length for formatted values.
224      */
225     public final synchronized int getWidth() {
226         return width;
227     }
228 
229     /**
230      * Checks if the specified number is a decimal (non-integer) type.
231      * 
232      * @param value
233      *            the number to check
234      * @return <code>true</code> if the specified number is a decimal type
235      *         value, or else <code>false</code> if it is an integer type.
236      */
237     private static boolean isDecimal(Number value) {
238         return value instanceof Float || value instanceof Double || value instanceof BigDecimal;
239     }
240 
241     /**
242      * Returns a string representation of a decimal number, in the available
243      * space, using either fixed decimal format or exponential notitation. It
244      * will use the notation that either gets closer to the required fixed
245      * precision while filling the available space, or if both notations can fit
246      * it will return the more compact one. If neither notation can be
247      * accomodated in the space available, then an exception is thrown.
248      * 
249      * @param value
250      *            the decimal value to print
251      * @return the string representing the value, or an empty string if the
252      *         value was <code>null</code>.
253      * @throws LongValueException
254      *             if the decimal value cannot be represented in the alotted
255      *             space with any precision
256      * @see #setPrecision(int)
257      * @see #setWidth(int)
258      * @see #forCard(HeaderCard)
259      */
260     public synchronized String format(Number value) throws LongValueException {
261 
262         if (value == null) {
263             return "";
264         }
265 
266         // The value in fixed notation...
267         String fixed = null;
268 
269         if (!isDecimal(value)) {
270             // For integer types, always consider the fixed format...
271             fixed = value.toString();
272             if (fixed.length() <= width) {
273                 return fixed;
274             }
275             if (!(value instanceof BigInteger)) {
276                 throw new LongValueException(width, fixed);
277             }
278             // We'll try exponential with reduced precision...
279             fixed = null;
280         } else if (decimals < 0) {
281             // Don"t do fixed format if precision is set explicitly
282             // (It's not really trivial to control the number of significant
283             // gigures in the fixed format...)
284             double a = Math.abs(value.doubleValue());
285             if (a >= MIN_FIXED && a < MAX_FIXED) {
286                 // Fixed format only in a resonable data...
287                 try {
288                     fixed = format(value, "0.#", AUTO_PRECISION, false);
289                 } catch (LongValueException e) {
290                     // We'll try with exponential notation...
291                 }
292             }
293         }
294 
295         // The value in exponential notation...
296         String exp = null;
297 
298         try {
299             exp = format(value, "0.#E0", decimals, FitsFactory.isUseExponentD());
300             if (fixed == null) {
301                 return exp;
302             }
303             // Go with whichever is more compact.
304             return exp.length() < fixed.length() ? exp : fixed;
305 
306         } catch (LongValueException e) {
307             if (fixed == null) {
308                 throw e;
309             }
310         }
311 
312         return fixed;
313     }
314 
315     /**
316      * Returns a fixed decimal representation of a value in the available space.
317      * For BigInteger and BigDecimal types, we allow reducing the precision at
318      * most down to to doube precision, if necessary to fit the number in the
319      * alotted space. If it's not at all possible to fit the fixed
320      * representation in the space available, then an exception is.
321      * 
322      * @param value
323      *            the decimal value to set
324      * @param fmt
325      *            the string that describes the base format (e.g. "0.#" or
326      *            "0E0").
327      * @param nDecimals
328      *            the number of decimal places to show
329      * @param allowUseD
330      *            if 'D' may be used instead of 'E' to precede the exponent when
331      *            value has more than 32-bit floating-point precision.
332      * @return the fixed format decimal representation of the value in the
333      *         alotted space.
334      * @throws LongValueException
335      *             if the decimal value cannot be represented in the alotted
336      *             space with the specified precision
337      */
338     private synchronized String format(Number value, String fmt, int nDecimals, boolean allowUseD) throws LongValueException {
339         if (width < 1) {
340             throw new LongValueException(width);
341         }
342 
343         DecimalFormat f = new DecimalFormat(fmt);
344         f.setDecimalFormatSymbols(SYMBOLS);
345         f.setDecimalSeparatorAlwaysShown(true);
346         f.setRoundingMode(RoundingMode.HALF_UP);
347 
348         if (nDecimals < 0) {
349             // Determine precision based on the type.
350             if (value instanceof BigDecimal || value instanceof BigInteger) {
351                 nDecimals = width;
352             } else if (value instanceof Double) {
353                 nDecimals = DOUBLE_DECIMALS;
354             } else {
355                 nDecimals = FLOAT_DECIMALS;
356             }
357         }
358 
359         f.setMinimumFractionDigits(fmt.indexOf('E') < 0 ? 1 : 0);
360         f.setMaximumFractionDigits(nDecimals);
361 
362         String text = f.format(value);
363 
364         // Iterate to make sure we get where we want...
365         while (text.length() > width) {
366             int delta = text.length() - width;
367             nDecimals -= delta;
368 
369             if ((value instanceof BigInteger && nDecimals < MIN_BIGINT_EFORM_DECIMALS) || (!(value instanceof BigInteger) && nDecimals < DOUBLE_DECIMALS)) {
370                 // We cannot show enough decimals for big types...
371                 throw new LongValueException(width, text);
372             }
373 
374             f.setMaximumFractionDigits(nDecimals);
375             text = f.format(value);
376         }
377 
378         if (allowUseD && nDecimals > FLOAT_DECIMALS) {
379             // If we want 'D' instead of 'E', just replace the letter in the
380             // result.
381             text = text.replace('E', 'D');
382         }
383 
384         return text;
385     }
386 }