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