View Javadoc
1   /*
2    * Licensed to the Apache Software Foundation (ASF) under one or more
3    * contributor license agreements.  See the NOTICE file distributed with
4    * this work for additional information regarding copyright ownership.
5    * The ASF licenses this file to You under the Apache License, Version 2.0
6    * (the "License"); you may not use this file except in compliance with
7    * the License.  You may obtain a copy of the License at
8    *
9    *      https://www.apache.org/licenses/LICENSE-2.0
10   *
11   * Unless required by applicable law or agreed to in writing, software
12   * distributed under the License is distributed on an "AS IS" BASIS,
13   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14   * See the License for the specific language governing permissions and
15   * limitations under the License.
16   */
17  
18  /*
19   * This is not the original file distributed by the Apache Software Foundation
20   * It has been modified by the Hipparchus project
21   */
22  
23  package org.hipparchus.complex;
24  
25  import java.text.FieldPosition;
26  import java.text.NumberFormat;
27  import java.text.ParsePosition;
28  import java.util.Locale;
29  
30  import org.hipparchus.exception.LocalizedCoreFormats;
31  import org.hipparchus.exception.MathIllegalArgumentException;
32  import org.hipparchus.exception.MathIllegalStateException;
33  import org.hipparchus.exception.NullArgumentException;
34  import org.hipparchus.util.CompositeFormat;
35  import org.hipparchus.util.MathUtils;
36  
37  /**
38   * Formats a Complex number in cartesian format "Re(c) + Im(c)i".  'i' can
39   * be replaced with 'j' (or anything else), and the number format for both real
40   * and imaginary parts can be configured.
41   */
42  public class ComplexFormat {
43  
44       /** The default imaginary character. */
45      private static final String DEFAULT_IMAGINARY_CHARACTER = "i";
46      /** The notation used to signify the imaginary part of the complex number. */
47      private final String imaginaryCharacter;
48      /** The format used for the imaginary part. */
49      private final NumberFormat imaginaryFormat;
50      /** The format used for the real part. */
51      private final NumberFormat realFormat;
52  
53      /**
54       * Create an instance with the default imaginary character, 'i', and the
55       * default number format for both real and imaginary parts.
56       */
57      public ComplexFormat() {
58          this.imaginaryCharacter = DEFAULT_IMAGINARY_CHARACTER;
59          this.imaginaryFormat = CompositeFormat.getDefaultNumberFormat();
60          this.realFormat = imaginaryFormat;
61      }
62  
63      /**
64       * Create an instance with a custom number format for both real and
65       * imaginary parts.
66       * @param format the custom format for both real and imaginary parts.
67       * @throws NullArgumentException if {@code realFormat} is {@code null}.
68       */
69      public ComplexFormat(NumberFormat format) throws NullArgumentException {
70          MathUtils.checkNotNull(format, LocalizedCoreFormats.IMAGINARY_FORMAT);
71          this.imaginaryCharacter = DEFAULT_IMAGINARY_CHARACTER;
72          this.imaginaryFormat = format;
73          this.realFormat = format;
74      }
75  
76      /**
77       * Create an instance with a custom number format for the real part and a
78       * custom number format for the imaginary part.
79       * @param realFormat the custom format for the real part.
80       * @param imaginaryFormat the custom format for the imaginary part.
81       * @throws NullArgumentException if {@code imaginaryFormat} is {@code null}.
82       * @throws NullArgumentException if {@code realFormat} is {@code null}.
83        */
84      public ComplexFormat(NumberFormat realFormat, NumberFormat imaginaryFormat)
85          throws NullArgumentException {
86          MathUtils.checkNotNull(imaginaryFormat, LocalizedCoreFormats.IMAGINARY_FORMAT);
87          MathUtils.checkNotNull(realFormat, LocalizedCoreFormats.REAL_FORMAT);
88  
89          this.imaginaryCharacter = DEFAULT_IMAGINARY_CHARACTER;
90          this.imaginaryFormat = imaginaryFormat;
91          this.realFormat = realFormat;
92      }
93  
94      /**
95       * Create an instance with a custom imaginary character, and the default
96       * number format for both real and imaginary parts.
97       * @param imaginaryCharacter The custom imaginary character.
98       * @throws NullArgumentException if {@code imaginaryCharacter} is
99       * {@code null}.
100      * @throws MathIllegalArgumentException if {@code imaginaryCharacter} is an
101      * empty string.
102      */
103     public ComplexFormat(String imaginaryCharacter)
104         throws MathIllegalArgumentException, NullArgumentException {
105         this(imaginaryCharacter, CompositeFormat.getDefaultNumberFormat());
106     }
107 
108     /**
109      * Create an instance with a custom imaginary character, and a custom number
110      * format for both real and imaginary parts.
111      * @param imaginaryCharacter The custom imaginary character.
112      * @param format the custom format for both real and imaginary parts.
113      * @throws NullArgumentException if {@code imaginaryCharacter} is
114      * {@code null}.
115      * @throws MathIllegalArgumentException if {@code imaginaryCharacter} is an
116      * empty string.
117      * @throws NullArgumentException if {@code format} is {@code null}.
118      */
119     public ComplexFormat(String imaginaryCharacter, NumberFormat format)
120         throws MathIllegalArgumentException, NullArgumentException {
121         this(imaginaryCharacter, format, format);
122     }
123 
124     /**
125      * Create an instance with a custom imaginary character, a custom number
126      * format for the real part, and a custom number format for the imaginary
127      * part.
128      *
129      * @param imaginaryCharacter The custom imaginary character.
130      * @param realFormat the custom format for the real part.
131      * @param imaginaryFormat the custom format for the imaginary part.
132      * @throws NullArgumentException if {@code imaginaryCharacter} is
133      * {@code null}.
134      * @throws MathIllegalArgumentException if {@code imaginaryCharacter} is an
135      * empty string.
136      * @throws NullArgumentException if {@code imaginaryFormat} is {@code null}.
137      * @throws NullArgumentException if {@code realFormat} is {@code null}.
138      */
139     public ComplexFormat(String imaginaryCharacter,
140                          NumberFormat realFormat,
141                          NumberFormat imaginaryFormat)
142         throws MathIllegalArgumentException, NullArgumentException {
143         if (imaginaryCharacter == null) {
144             throw new NullArgumentException();
145         }
146         if (imaginaryCharacter.length() == 0) {
147             throw new MathIllegalArgumentException(LocalizedCoreFormats.NO_DATA);
148         }
149         MathUtils.checkNotNull(imaginaryFormat, LocalizedCoreFormats.IMAGINARY_FORMAT);
150         MathUtils.checkNotNull(realFormat, LocalizedCoreFormats.REAL_FORMAT);
151 
152         this.imaginaryCharacter = imaginaryCharacter;
153         this.imaginaryFormat = imaginaryFormat;
154         this.realFormat = realFormat;
155     }
156 
157     /**
158      * Get the set of locales for which complex formats are available.
159      * <p>This is the same set as the {@link NumberFormat} set.</p>
160      * @return available complex format locales.
161      */
162     public static Locale[] getAvailableLocales() {
163         return NumberFormat.getAvailableLocales();
164     }
165 
166     /**
167      * This method calls {@link #format(Object,StringBuffer,FieldPosition)}.
168      *
169      * @param c Complex object to format.
170      * @return A formatted number in the form "Re(c) + Im(c)i".
171      */
172     public String format(Complex c) {
173         return format(c, new StringBuffer(), new FieldPosition(0)).toString();
174     }
175 
176     /**
177      * This method calls {@link #format(Object,StringBuffer,FieldPosition)}.
178      *
179      * @param c Double object to format.
180      * @return A formatted number.
181      */
182     public String format(Double c) {
183         return format(new Complex(c, 0), new StringBuffer(), new FieldPosition(0)).toString();
184     }
185 
186     /**
187      * Formats a {@link Complex} object to produce a string.
188      *
189      * @param complex the object to format.
190      * @param toAppendTo where the text is to be appended
191      * @param pos On input: an alignment field, if desired. On output: the
192      *            offsets of the alignment field
193      * @return the value passed in as toAppendTo.
194      */
195     public StringBuffer format(Complex complex, StringBuffer toAppendTo,
196                                FieldPosition pos) {
197         pos.setBeginIndex(0);
198         pos.setEndIndex(0);
199 
200         // format real
201         double re = complex.getReal();
202         CompositeFormat.formatDouble(re, getRealFormat(), toAppendTo, pos);
203 
204         // format sign and imaginary
205         double im = complex.getImaginary();
206         StringBuffer imAppendTo;
207         if (im < 0.0) {
208             toAppendTo.append(" - ");
209             imAppendTo = formatImaginary(-im, new StringBuffer(), pos);
210             toAppendTo.append(imAppendTo);
211             toAppendTo.append(getImaginaryCharacter());
212         } else if (im > 0.0 || Double.isNaN(im)) {
213             toAppendTo.append(" + ");
214             imAppendTo = formatImaginary(im, new StringBuffer(), pos);
215             toAppendTo.append(imAppendTo);
216             toAppendTo.append(getImaginaryCharacter());
217         }
218 
219         return toAppendTo;
220     }
221 
222     /**
223      * Format the absolute value of the imaginary part.
224      *
225      * @param absIm Absolute value of the imaginary part of a complex number.
226      * @param toAppendTo where the text is to be appended.
227      * @param pos On input: an alignment field, if desired. On output: the
228      * offsets of the alignment field.
229      * @return the value passed in as toAppendTo.
230      */
231     private StringBuffer formatImaginary(double absIm,
232                                          StringBuffer toAppendTo,
233                                          FieldPosition pos) {
234         pos.setBeginIndex(0);
235         pos.setEndIndex(0);
236 
237         CompositeFormat.formatDouble(absIm, getImaginaryFormat(), toAppendTo, pos);
238         if ("1".equals(toAppendTo.toString())) {
239             // Remove the character "1" if it is the only one.
240             toAppendTo.setLength(0);
241         }
242 
243         return toAppendTo;
244     }
245 
246     /**
247      * Formats a object to produce a string.  {@code obj} must be either a
248      * {@link Complex} object or a {@link Number} object.  Any other type of
249      * object will result in an {@link IllegalArgumentException} being thrown.
250      *
251      * @param obj the object to format.
252      * @param toAppendTo where the text is to be appended
253      * @param pos On input: an alignment field, if desired. On output: the
254      *            offsets of the alignment field
255      * @return the value passed in as toAppendTo.
256      * @see java.text.Format#format(java.lang.Object, java.lang.StringBuffer, java.text.FieldPosition)
257      * @throws MathIllegalArgumentException is {@code obj} is not a valid type.
258      */
259     public StringBuffer format(Object obj, StringBuffer toAppendTo,
260                                FieldPosition pos)
261         throws MathIllegalArgumentException {
262 
263         if (obj instanceof Complex) {
264             return format( (Complex)obj, toAppendTo, pos);
265         } else if (obj instanceof Number) {
266             return format(new Complex(((Number)obj).doubleValue(), 0.0), toAppendTo, pos);
267         } else {
268             throw new MathIllegalArgumentException(LocalizedCoreFormats.CANNOT_FORMAT_INSTANCE_AS_COMPLEX,
269                                                    obj.getClass().getName());
270         }
271 
272     }
273 
274     /**
275      * Access the imaginaryCharacter.
276      * @return the imaginaryCharacter.
277      */
278     public String getImaginaryCharacter() {
279         return imaginaryCharacter;
280     }
281 
282     /**
283      * Access the imaginaryFormat.
284      * @return the imaginaryFormat.
285      */
286     public NumberFormat getImaginaryFormat() {
287         return imaginaryFormat;
288     }
289 
290     /**
291      * Returns the default complex format for the current locale.
292      * @return the default complex format.
293      * @since 1.4
294      */
295     public static ComplexFormat getComplexFormat() {
296         return getComplexFormat(Locale.getDefault());
297     }
298 
299     /**
300      * Returns the default complex format for the given locale.
301      * @param locale the specific locale used by the format.
302      * @return the complex format specific to the given locale.
303      * @since 1.4
304      */
305     public static ComplexFormat getComplexFormat(Locale locale) {
306         NumberFormat f = CompositeFormat.getDefaultNumberFormat(locale);
307         return new ComplexFormat(f);
308     }
309 
310     /**
311      * Returns the default complex format for the given locale.
312      * @param locale the specific locale used by the format.
313      * @param imaginaryCharacter Imaginary character.
314      * @return the complex format specific to the given locale.
315      * @throws NullArgumentException if {@code imaginaryCharacter} is
316      * {@code null}.
317      * @throws MathIllegalArgumentException if {@code imaginaryCharacter} is an
318      * empty string.
319      * @since 1.4
320      */
321     public static ComplexFormat getComplexFormat(String imaginaryCharacter, Locale locale)
322         throws MathIllegalArgumentException, NullArgumentException {
323         NumberFormat f = CompositeFormat.getDefaultNumberFormat(locale);
324         return new ComplexFormat(imaginaryCharacter, f);
325     }
326 
327     /**
328      * Access the realFormat.
329      * @return the realFormat.
330      */
331     public NumberFormat getRealFormat() {
332         return realFormat;
333     }
334 
335     /**
336      * Parses a string to produce a {@link Complex} object.
337      *
338      * @param source the string to parse.
339      * @return the parsed {@link Complex} object.
340      * @throws MathIllegalStateException if the beginning of the specified string
341      * cannot be parsed.
342      */
343     public Complex parse(String source) throws MathIllegalStateException {
344         ParsePosition parsePosition = new ParsePosition(0);
345         Complex result = parse(source, parsePosition);
346         if (parsePosition.getIndex() == 0) {
347             throw new MathIllegalStateException(LocalizedCoreFormats.CANNOT_PARSE_AS_TYPE,
348                                                 source, parsePosition.getErrorIndex(),
349                                                 Complex.class);
350         }
351         return result;
352     }
353 
354     /**
355      * Parses a string to produce a {@link Complex} object.
356      *
357      * @param source the string to parse
358      * @param pos input/ouput parsing parameter.
359      * @return the parsed {@link Complex} object.
360      */
361     public Complex parse(String source, ParsePosition pos) {
362         int initialIndex = pos.getIndex();
363 
364         // parse whitespace
365         CompositeFormat.parseAndIgnoreWhitespace(source, pos);
366 
367         // parse real
368         Number re = CompositeFormat.parseNumber(source, getRealFormat(), pos);
369         if (re == null) {
370             // invalid real number
371             // set index back to initial, error index should already be set
372             pos.setIndex(initialIndex);
373             return null;
374         }
375 
376         // parse sign
377         int startIndex = pos.getIndex();
378         char c = CompositeFormat.parseNextCharacter(source, pos);
379         int sign = 0;
380         switch (c) {
381         case 0 :
382             // no sign
383             // return real only complex number
384             return new Complex(re.doubleValue(), 0.0);
385         case '-' :
386             sign = -1;
387             break;
388         case '+' :
389             sign = 1;
390             break;
391         default :
392             // invalid sign
393             // set index back to initial, error index should be the last
394             // character examined.
395             pos.setIndex(initialIndex);
396             pos.setErrorIndex(startIndex);
397             return null;
398         }
399 
400         // parse whitespace
401         CompositeFormat.parseAndIgnoreWhitespace(source, pos);
402 
403         // parse imaginary
404         Number im = CompositeFormat.parseNumber(source, getRealFormat(), pos);
405         if (im == null) {
406             // invalid imaginary number
407             // set index back to initial, error index should already be set
408             pos.setIndex(initialIndex);
409             return null;
410         }
411 
412         // parse imaginary character
413         if (!CompositeFormat.parseFixedstring(source, getImaginaryCharacter(), pos)) {
414             return null;
415         }
416 
417         return new Complex(re.doubleValue(), im.doubleValue() * sign);
418 
419     }
420 }