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.isEmpty()) {
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).append(getImaginaryCharacter());
211         } else if (im > 0.0 || Double.isNaN(im)) {
212             toAppendTo.append(" + ");
213             imAppendTo = formatImaginary(im, new StringBuffer(), pos);
214             toAppendTo.append(imAppendTo).append(getImaginaryCharacter());
215         }
216 
217         return toAppendTo;
218     }
219 
220     /**
221      * Format the absolute value of the imaginary part.
222      *
223      * @param absIm Absolute value of the imaginary part of a complex number.
224      * @param toAppendTo where the text is to be appended.
225      * @param pos On input: an alignment field, if desired. On output: the
226      * offsets of the alignment field.
227      * @return the value passed in as toAppendTo.
228      */
229     private StringBuffer formatImaginary(double absIm,
230                                          StringBuffer toAppendTo,
231                                          FieldPosition pos) {
232         pos.setBeginIndex(0);
233         pos.setEndIndex(0);
234 
235         CompositeFormat.formatDouble(absIm, getImaginaryFormat(), toAppendTo, pos);
236         if ("1".equals(toAppendTo.toString())) {
237             // Remove the character "1" if it is the only one.
238             toAppendTo.setLength(0);
239         }
240 
241         return toAppendTo;
242     }
243 
244     /**
245      * Formats a object to produce a string.  {@code obj} must be either a
246      * {@link Complex} object or a {@link Number} object.  Any other type of
247      * object will result in an {@link IllegalArgumentException} being thrown.
248      *
249      * @param obj the object to format.
250      * @param toAppendTo where the text is to be appended
251      * @param pos On input: an alignment field, if desired. On output: the
252      *            offsets of the alignment field
253      * @return the value passed in as toAppendTo.
254      * @see java.text.Format#format(java.lang.Object, java.lang.StringBuffer, java.text.FieldPosition)
255      * @throws MathIllegalArgumentException is {@code obj} is not a valid type.
256      */
257     public StringBuffer format(Object obj, StringBuffer toAppendTo,
258                                FieldPosition pos)
259         throws MathIllegalArgumentException {
260 
261         if (obj instanceof Complex) {
262             return format( (Complex)obj, toAppendTo, pos);
263         } else if (obj instanceof Number) {
264             return format(new Complex(((Number)obj).doubleValue(), 0.0), toAppendTo, pos);
265         } else {
266             throw new MathIllegalArgumentException(LocalizedCoreFormats.CANNOT_FORMAT_INSTANCE_AS_COMPLEX,
267                                                    obj.getClass().getName());
268         }
269 
270     }
271 
272     /**
273      * Access the imaginaryCharacter.
274      * @return the imaginaryCharacter.
275      */
276     public String getImaginaryCharacter() {
277         return imaginaryCharacter;
278     }
279 
280     /**
281      * Access the imaginaryFormat.
282      * @return the imaginaryFormat.
283      */
284     public NumberFormat getImaginaryFormat() {
285         return imaginaryFormat;
286     }
287 
288     /**
289      * Returns the default complex format for the current locale.
290      * @return the default complex format.
291      * @since 1.4
292      */
293     public static ComplexFormat getComplexFormat() {
294         return getComplexFormat(Locale.getDefault());
295     }
296 
297     /**
298      * Returns the default complex format for the given locale.
299      * @param locale the specific locale used by the format.
300      * @return the complex format specific to the given locale.
301      * @since 1.4
302      */
303     public static ComplexFormat getComplexFormat(Locale locale) {
304         NumberFormat f = CompositeFormat.getDefaultNumberFormat(locale);
305         return new ComplexFormat(f);
306     }
307 
308     /**
309      * Returns the default complex format for the given locale.
310      * @param locale the specific locale used by the format.
311      * @param imaginaryCharacter Imaginary character.
312      * @return the complex format specific to the given locale.
313      * @throws NullArgumentException if {@code imaginaryCharacter} is
314      * {@code null}.
315      * @throws MathIllegalArgumentException if {@code imaginaryCharacter} is an
316      * empty string.
317      * @since 1.4
318      */
319     public static ComplexFormat getComplexFormat(String imaginaryCharacter, Locale locale)
320         throws MathIllegalArgumentException, NullArgumentException {
321         NumberFormat f = CompositeFormat.getDefaultNumberFormat(locale);
322         return new ComplexFormat(imaginaryCharacter, f);
323     }
324 
325     /**
326      * Access the realFormat.
327      * @return the realFormat.
328      */
329     public NumberFormat getRealFormat() {
330         return realFormat;
331     }
332 
333     /**
334      * Parses a string to produce a {@link Complex} object.
335      *
336      * @param source the string to parse.
337      * @return the parsed {@link Complex} object.
338      * @throws MathIllegalStateException if the beginning of the specified string
339      * cannot be parsed.
340      */
341     public Complex parse(String source) throws MathIllegalStateException {
342         ParsePosition parsePosition = new ParsePosition(0);
343         Complex result = parse(source, parsePosition);
344         if (parsePosition.getIndex() == 0) {
345             throw new MathIllegalStateException(LocalizedCoreFormats.CANNOT_PARSE_AS_TYPE,
346                                                 source, parsePosition.getErrorIndex(),
347                                                 Complex.class);
348         }
349         return result;
350     }
351 
352     /**
353      * Parses a string to produce a {@link Complex} object.
354      *
355      * @param source the string to parse
356      * @param pos input/ouput parsing parameter.
357      * @return the parsed {@link Complex} object.
358      */
359     public Complex parse(String source, ParsePosition pos) {
360         int initialIndex = pos.getIndex();
361 
362         // parse whitespace
363         CompositeFormat.parseAndIgnoreWhitespace(source, pos);
364 
365         // parse real
366         Number re = CompositeFormat.parseNumber(source, getRealFormat(), pos);
367         if (re == null) {
368             // invalid real number
369             // set index back to initial, error index should already be set
370             pos.setIndex(initialIndex);
371             return null;
372         }
373 
374         // parse sign
375         int startIndex = pos.getIndex();
376         char c = CompositeFormat.parseNextCharacter(source, pos);
377         int sign;
378         switch (c) {
379         case 0 :
380             // no sign
381             // return real only complex number
382             return new Complex(re.doubleValue(), 0.0);
383         case '-' :
384             sign = -1;
385             break;
386         case '+' :
387             sign = 1;
388             break;
389         default :
390             // invalid sign
391             // set index back to initial, error index should be the last
392             // character examined.
393             pos.setIndex(initialIndex);
394             pos.setErrorIndex(startIndex);
395             return null;
396         }
397 
398         // parse whitespace
399         CompositeFormat.parseAndIgnoreWhitespace(source, pos);
400 
401         // parse imaginary
402         Number im = CompositeFormat.parseNumber(source, getRealFormat(), pos);
403         if (im == null) {
404             // invalid imaginary number
405             // set index back to initial, error index should already be set
406             pos.setIndex(initialIndex);
407             return null;
408         }
409 
410         // parse imaginary character
411         if (!CompositeFormat.parseFixedstring(source, getImaginaryCharacter(), pos)) {
412             return null;
413         }
414 
415         return new Complex(re.doubleValue(), im.doubleValue() * sign);
416 
417     }
418 }