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.linear;
24  
25  import java.text.FieldPosition;
26  import java.text.NumberFormat;
27  import java.text.ParsePosition;
28  import java.util.ArrayList;
29  import java.util.List;
30  import java.util.Locale;
31  
32  import org.hipparchus.exception.LocalizedCoreFormats;
33  import org.hipparchus.exception.MathIllegalStateException;
34  import org.hipparchus.util.CompositeFormat;
35  
36  /**
37   * Formats a vector in components list format "{v0; v1; ...; vk-1}".
38   * <p>The prefix and suffix "{" and "}" and the separator "; " can be replaced by
39   * any user-defined strings. The number format for components can be configured.</p>
40   * <p>White space is ignored at parse time, even if it is in the prefix, suffix
41   * or separator specifications. So even if the default separator does include a space
42   * character that is used at format time, both input string "{1;1;1}" and
43   * " { 1 ; 1 ; 1 } " will be parsed without error and the same vector will be
44   * returned. In the second case, however, the parse position after parsing will be
45   * just after the closing curly brace, i.e. just before the trailing space.</p>
46   *
47   */
48  public class RealVectorFormat {
49  
50      /** The default prefix: "{". */
51      private static final String DEFAULT_PREFIX = "{";
52      /** The default suffix: "}". */
53      private static final String DEFAULT_SUFFIX = "}";
54      /** The default separator: ", ". */
55      private static final String DEFAULT_SEPARATOR = "; ";
56      /** Prefix. */
57      private final String prefix;
58      /** Suffix. */
59      private final String suffix;
60      /** Separator. */
61      private final String separator;
62      /** Trimmed prefix. */
63      private final String trimmedPrefix;
64      /** Trimmed suffix. */
65      private final String trimmedSuffix;
66      /** Trimmed separator. */
67      private final String trimmedSeparator;
68      /** The format used for components. */
69      private final NumberFormat format;
70  
71      /**
72       * Create an instance with default settings.
73       * <p>The instance uses the default prefix, suffix and separator:
74       * "{", "}", and "; " and the default number format for components.</p>
75       */
76      public RealVectorFormat() {
77          this(DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_SEPARATOR,
78               CompositeFormat.getDefaultNumberFormat());
79      }
80  
81      /**
82       * Create an instance with a custom number format for components.
83       * @param format the custom format for components.
84       */
85      public RealVectorFormat(final NumberFormat format) {
86          this(DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_SEPARATOR, format);
87      }
88  
89      /**
90       * Create an instance with custom prefix, suffix and separator.
91       * @param prefix prefix to use instead of the default "{"
92       * @param suffix suffix to use instead of the default "}"
93       * @param separator separator to use instead of the default "; "
94       */
95      public RealVectorFormat(final String prefix, final String suffix,
96                              final String separator) {
97          this(prefix, suffix, separator,
98               CompositeFormat.getDefaultNumberFormat());
99      }
100 
101     /**
102      * Create an instance with custom prefix, suffix, separator and format
103      * for components.
104      * @param prefix prefix to use instead of the default "{"
105      * @param suffix suffix to use instead of the default "}"
106      * @param separator separator to use instead of the default "; "
107      * @param format the custom format for components.
108      */
109     public RealVectorFormat(final String prefix, final String suffix,
110                             final String separator, final NumberFormat format) {
111         this.prefix      = prefix;
112         this.suffix      = suffix;
113         this.separator   = separator;
114         trimmedPrefix    = prefix.trim();
115         trimmedSuffix    = suffix.trim();
116         trimmedSeparator = separator.trim();
117         this.format      = format;
118     }
119 
120     /**
121      * Get the set of locales for which real vectors formats are available.
122      * <p>This is the same set as the {@link NumberFormat} set.</p>
123      * @return available real vector format locales.
124      */
125     public static Locale[] getAvailableLocales() {
126         return NumberFormat.getAvailableLocales();
127     }
128 
129     /**
130      * Get the format prefix.
131      * @return format prefix.
132      */
133     public String getPrefix() {
134         return prefix;
135     }
136 
137     /**
138      * Get the format suffix.
139      * @return format suffix.
140      */
141     public String getSuffix() {
142         return suffix;
143     }
144 
145     /**
146      * Get the format separator between components.
147      * @return format separator.
148      */
149     public String getSeparator() {
150         return separator;
151     }
152 
153     /**
154      * Get the components format.
155      * @return components format.
156      */
157     public NumberFormat getFormat() {
158         return format;
159     }
160 
161     /**
162      * Returns the default real vector format for the current locale.
163      * @return the default real vector format.
164      * @since 1.4
165      */
166     public static RealVectorFormat getRealVectorFormat() {
167         return getRealVectorFormat(Locale.getDefault());
168     }
169 
170     /**
171      * Returns the default real vector format for the given locale.
172      * @param locale the specific locale used by the format.
173      * @return the real vector format specific to the given locale.
174      * @since 1.4
175      */
176     public static RealVectorFormat getRealVectorFormat(final Locale locale) {
177         return new RealVectorFormat(CompositeFormat.getDefaultNumberFormat(locale));
178     }
179 
180     /**
181      * This method calls {@link #format(RealVector,StringBuffer,FieldPosition)}.
182      *
183      * @param v RealVector object to format.
184      * @return a formatted vector.
185      */
186     public String format(RealVector v) {
187         return format(v, new StringBuffer(), new FieldPosition(0)).toString();
188     }
189 
190     /**
191      * Formats a {@link RealVector} object to produce a string.
192      * @param vector the object to format.
193      * @param toAppendTo where the text is to be appended
194      * @param pos On input: an alignment field, if desired. On output: the
195      *            offsets of the alignment field
196      * @return the value passed in as toAppendTo.
197      */
198     public StringBuffer format(RealVector vector, StringBuffer toAppendTo,
199                                FieldPosition pos) {
200 
201         pos.setBeginIndex(0);
202         pos.setEndIndex(0);
203 
204         // format prefix
205         toAppendTo.append(prefix);
206 
207         // format components
208         for (int i = 0; i < vector.getDimension(); ++i) {
209             if (i > 0) {
210                 toAppendTo.append(separator);
211             }
212             CompositeFormat.formatDouble(vector.getEntry(i), format, toAppendTo, pos);
213         }
214 
215         // format suffix
216         toAppendTo.append(suffix);
217 
218         return toAppendTo;
219     }
220 
221     /**
222      * Parse a string to produce a {@link RealVector} object.
223      *
224      * @param source String to parse.
225      * @return the parsed {@link RealVector} object.
226      * @throws MathIllegalStateException if the beginning of the specified string
227      * cannot be parsed.
228      */
229     public ArrayRealVector parse(String source) {
230         final ParsePosition parsePosition = new ParsePosition(0);
231         final ArrayRealVector result = parse(source, parsePosition);
232         if (parsePosition.getIndex() == 0) {
233             throw new MathIllegalStateException(LocalizedCoreFormats.CANNOT_PARSE_AS_TYPE,
234                                                 source,
235                                                 parsePosition.getErrorIndex(),
236                                                 ArrayRealVector.class);
237         }
238         return result;
239     }
240 
241     /**
242      * Parse a string to produce a {@link RealVector} object.
243      *
244      * @param source String to parse.
245      * @param pos input/ouput parsing parameter.
246      * @return the parsed {@link RealVector} object.
247      */
248     public ArrayRealVector parse(String source, ParsePosition pos) {
249         int initialIndex = pos.getIndex();
250 
251         // parse prefix
252         CompositeFormat.parseAndIgnoreWhitespace(source, pos);
253         if (!CompositeFormat.parseFixedstring(source, trimmedPrefix, pos)) {
254             return null;
255         }
256 
257         // parse components
258         List<Number> components = new ArrayList<>();
259         for (boolean loop = true; loop;){
260 
261             if (!components.isEmpty()) {
262                 CompositeFormat.parseAndIgnoreWhitespace(source, pos);
263                 if (!CompositeFormat.parseFixedstring(source, trimmedSeparator, pos)) {
264                     loop = false;
265                 }
266             }
267 
268             if (loop) {
269                 CompositeFormat.parseAndIgnoreWhitespace(source, pos);
270                 Number component = CompositeFormat.parseNumber(source, format, pos);
271                 if (component != null) {
272                     components.add(component);
273                 } else {
274                     // invalid component
275                     // set index back to initial, error index should already be set
276                     pos.setIndex(initialIndex);
277                     return null;
278                 }
279             }
280 
281         }
282 
283         // parse suffix
284         CompositeFormat.parseAndIgnoreWhitespace(source, pos);
285         if (!CompositeFormat.parseFixedstring(source, trimmedSuffix, pos)) {
286             return null;
287         }
288 
289         // build vector
290         double[] data = new double[components.size()];
291         for (int i = 0; i < data.length; ++i) {
292             data[i] = components.get(i).doubleValue();
293         }
294         return new ArrayRealVector(data, false);
295     }
296 }