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
9
* http://www.apache.org/licenses/LICENSE-2.0
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.
18
package org.apache.commons.math.linear;
20
import java.text.FieldPosition;
21
import java.text.NumberFormat;
22
import java.text.ParseException;
23
import java.text.ParsePosition;
24
import java.util.ArrayList;
25
import java.util.List;
26
import java.util.Locale;
28
import org.apache.commons.math.MathRuntimeException;
29
import org.apache.commons.math.util.CompositeFormat;
32
* Formats a vector in components list format "{v0; v1; ...; vk-1}".
33
* <p>The prefix and suffix "{" and "}" and the separator "; " can be replaced by
34
* any user-defined strings. The number format for components can be configured.</p>
35
* <p>White space is ignored at parse time, even if it is in the prefix, suffix
36
* or separator specifications. So even if the default separator does include a space
37
* character that is used at format time, both input string "{1;1;1}" and
38
* " { 1 ; 1 ; 1 } " will be parsed without error and the same vector will be
39
* returned. In the second case, however, the parse position after parsing will be
40
* just after the closing curly brace, i.e. just before the trailing space.</p>
42
* @version $Revision: 783702 $ $Date: 2009-06-11 04:54:02 -0400 (Thu, 11 Jun 2009) $
45
public class RealVectorFormat extends CompositeFormat {
47
/** Serializable version identifier */
48
private static final long serialVersionUID = -708767813036157690L;
50
/** The default prefix: "{". */
51
private static final String DEFAULT_PREFIX = "{";
53
/** The default suffix: "}". */
54
private static final String DEFAULT_SUFFIX = "}";
56
/** The default separator: ", ". */
57
private static final String DEFAULT_SEPARATOR = "; ";
60
private final String prefix;
63
private final String suffix;
66
private final String separator;
68
/** Trimmed prefix. */
69
private final String trimmedPrefix;
71
/** Trimmed suffix. */
72
private final String trimmedSuffix;
74
/** Trimmed separator. */
75
private final String trimmedSeparator;
77
/** The format used for components. */
78
private NumberFormat format;
81
* Create an instance with default settings.
82
* <p>The instance uses the default prefix, suffix and separator:
83
* "{", "}", and "; " and the default number format for components.</p>
85
public RealVectorFormat() {
86
this(DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_SEPARATOR, getDefaultNumberFormat());
90
* Create an instance with a custom number format for components.
91
* @param format the custom format for components.
93
public RealVectorFormat(final NumberFormat format) {
94
this(DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_SEPARATOR, format);
98
* Create an instance with custom prefix, suffix and separator.
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 "; "
103
public RealVectorFormat(final String prefix, final String suffix,
104
final String separator) {
105
this(prefix, suffix, separator, getDefaultNumberFormat());
109
* Create an instance with custom prefix, suffix, separator and format
111
* @param prefix prefix to use instead of the default "{"
112
* @param suffix suffix to use instead of the default "}"
113
* @param separator separator to use instead of the default "; "
114
* @param format the custom format for components.
116
public RealVectorFormat(final String prefix, final String suffix,
117
final String separator, final NumberFormat format) {
118
this.prefix = prefix;
119
this.suffix = suffix;
120
this.separator = separator;
121
trimmedPrefix = prefix.trim();
122
trimmedSuffix = suffix.trim();
123
trimmedSeparator = separator.trim();
124
this.format = format;
128
* Get the set of locales for which real vectors formats are available.
129
* <p>This is the same set as the {@link NumberFormat} set.</p>
130
* @return available real vector format locales.
132
public static Locale[] getAvailableLocales() {
133
return NumberFormat.getAvailableLocales();
137
* Get the format prefix.
138
* @return format prefix.
140
public String getPrefix() {
145
* Get the format suffix.
146
* @return format suffix.
148
public String getSuffix() {
153
* Get the format separator between components.
154
* @return format separator.
156
public String getSeparator() {
161
* Get the components format.
162
* @return components format.
164
public NumberFormat getFormat() {
169
* Returns the default real vector format for the current locale.
170
* @return the default real vector format.
172
public static RealVectorFormat getInstance() {
173
return getInstance(Locale.getDefault());
177
* Returns the default real vector format for the given locale.
178
* @param locale the specific locale used by the format.
179
* @return the real vector format specific to the given locale.
181
public static RealVectorFormat getInstance(final Locale locale) {
182
return new RealVectorFormat(getDefaultNumberFormat(locale));
186
* This static method calls {@link #format(Object)} on a default instance of
189
* @param v RealVector object to format
190
* @return A formatted vector
192
public static String formatRealVector(RealVector v) {
193
return getInstance().format(v);
197
* Formats a {@link RealVector} object to produce a string.
198
* @param vector the object to format.
199
* @param toAppendTo where the text is to be appended
200
* @param pos On input: an alignment field, if desired. On output: the
201
* offsets of the alignment field
202
* @return the value passed in as toAppendTo.
204
public StringBuffer format(RealVector vector, StringBuffer toAppendTo,
207
pos.setBeginIndex(0);
211
toAppendTo.append(prefix);
214
for (int i = 0; i < vector.getDimension(); ++i) {
216
toAppendTo.append(separator);
218
formatDouble(vector.getEntry(i), format, toAppendTo, pos);
222
toAppendTo.append(suffix);
229
* Formats a object to produce a string.
230
* <p><code>obj</code> must be a {@link RealVector} object. Any other type of
231
* object will result in an {@link IllegalArgumentException} being thrown.</p>
232
* @param obj the object to format.
233
* @param toAppendTo where the text is to be appended
234
* @param pos On input: an alignment field, if desired. On output: the
235
* offsets of the alignment field
236
* @return the value passed in as toAppendTo.
237
* @see java.text.Format#format(java.lang.Object, java.lang.StringBuffer, java.text.FieldPosition)
238
* @throws IllegalArgumentException is <code>obj</code> is not a valid type.
241
public StringBuffer format(Object obj, StringBuffer toAppendTo,
244
if (obj instanceof RealVector) {
245
return format( (RealVector)obj, toAppendTo, pos);
248
throw MathRuntimeException.createIllegalArgumentException(
249
"cannot format a {0} instance as a real vector",
250
obj.getClass().getName());
255
* Parses a string to produce a {@link RealVector} object.
256
* @param source the string to parse
257
* @return the parsed {@link RealVector} object.
258
* @exception ParseException if the beginning of the specified string
261
public ArrayRealVector parse(String source) throws ParseException {
262
ParsePosition parsePosition = new ParsePosition(0);
263
ArrayRealVector result = parse(source, parsePosition);
264
if (parsePosition.getIndex() == 0) {
265
throw MathRuntimeException.createParseException(
266
parsePosition.getErrorIndex(),
267
"unparseable real vector: \"{0}\"", source);
273
* Parses a string to produce a {@link RealVector} object.
274
* @param source the string to parse
275
* @param pos input/ouput parsing parameter.
276
* @return the parsed {@link RealVector} object.
278
public ArrayRealVector parse(String source, ParsePosition pos) {
279
int initialIndex = pos.getIndex();
282
parseAndIgnoreWhitespace(source, pos);
283
if (!parseFixedstring(source, trimmedPrefix, pos)) {
288
List<Number> components = new ArrayList<Number>();
289
for (boolean loop = true; loop;){
291
if (!components.isEmpty()) {
292
parseAndIgnoreWhitespace(source, pos);
293
if (!parseFixedstring(source, trimmedSeparator, pos)) {
299
parseAndIgnoreWhitespace(source, pos);
300
Number component = parseNumber(source, format, pos);
301
if (component != null) {
302
components.add(component);
305
// set index back to initial, error index should already be set
306
pos.setIndex(initialIndex);
314
parseAndIgnoreWhitespace(source, pos);
315
if (!parseFixedstring(source, trimmedSuffix, pos)) {
320
double[] data = new double[components.size()];
321
for (int i = 0; i < data.length; ++i) {
322
data[i] = components.get(i).doubleValue();
324
return new ArrayRealVector(data, false);
329
* Parses a string to produce a object.
330
* @param source the string to parse
331
* @param pos input/ouput parsing parameter.
332
* @return the parsed object.
333
* @see java.text.Format#parseObject(java.lang.String, java.text.ParsePosition)
336
public Object parseObject(String source, ParsePosition pos) {
337
return parse(source, pos);