001/*
002 * Licensed to the Apache Software Foundation (ASF) under one or more
003 * contributor license agreements.  See the NOTICE file distributed with
004 * this work for additional information regarding copyright ownership.
005 * The ASF licenses this file to You under the Apache License, Version 2.0
006 * (the "License"); you may not use this file except in compliance with
007 * the License.  You may obtain a copy of the License at
008 *
009 *      http://www.apache.org/licenses/LICENSE-2.0
010 *
011 * Unless required by applicable law or agreed to in writing, software
012 * distributed under the License is distributed on an "AS IS" BASIS,
013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
014 * See the License for the specific language governing permissions and
015 * limitations under the License.
016 */
017
018package org.apache.commons.math3.linear;
019
020import java.text.FieldPosition;
021import java.text.NumberFormat;
022import java.text.ParsePosition;
023import java.util.ArrayList;
024import java.util.List;
025import java.util.Locale;
026
027import org.apache.commons.math3.exception.MathParseException;
028import org.apache.commons.math3.util.CompositeFormat;
029
030/**
031 * Formats a vector in components list format "{v0; v1; ...; vk-1}".
032 * <p>The prefix and suffix "{" and "}" and the separator "; " can be replaced by
033 * any user-defined strings. The number format for components can be configured.</p>
034 * <p>White space is ignored at parse time, even if it is in the prefix, suffix
035 * or separator specifications. So even if the default separator does include a space
036 * character that is used at format time, both input string "{1;1;1}" and
037 * " { 1 ; 1 ; 1 } " will be parsed without error and the same vector will be
038 * returned. In the second case, however, the parse position after parsing will be
039 * just after the closing curly brace, i.e. just before the trailing space.</p>
040 *
041 * @since 2.0
042 */
043public class RealVectorFormat {
044
045    /** The default prefix: "{". */
046    private static final String DEFAULT_PREFIX = "{";
047    /** The default suffix: "}". */
048    private static final String DEFAULT_SUFFIX = "}";
049    /** The default separator: ", ". */
050    private static final String DEFAULT_SEPARATOR = "; ";
051    /** Prefix. */
052    private final String prefix;
053    /** Suffix. */
054    private final String suffix;
055    /** Separator. */
056    private final String separator;
057    /** Trimmed prefix. */
058    private final String trimmedPrefix;
059    /** Trimmed suffix. */
060    private final String trimmedSuffix;
061    /** Trimmed separator. */
062    private final String trimmedSeparator;
063    /** The format used for components. */
064    private final NumberFormat format;
065
066    /**
067     * Create an instance with default settings.
068     * <p>The instance uses the default prefix, suffix and separator:
069     * "{", "}", and "; " and the default number format for components.</p>
070     */
071    public RealVectorFormat() {
072        this(DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_SEPARATOR,
073             CompositeFormat.getDefaultNumberFormat());
074    }
075
076    /**
077     * Create an instance with a custom number format for components.
078     * @param format the custom format for components.
079     */
080    public RealVectorFormat(final NumberFormat format) {
081        this(DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_SEPARATOR, format);
082    }
083
084    /**
085     * Create an instance with custom prefix, suffix and separator.
086     * @param prefix prefix to use instead of the default "{"
087     * @param suffix suffix to use instead of the default "}"
088     * @param separator separator to use instead of the default "; "
089     */
090    public RealVectorFormat(final String prefix, final String suffix,
091                            final String separator) {
092        this(prefix, suffix, separator,
093             CompositeFormat.getDefaultNumberFormat());
094    }
095
096    /**
097     * Create an instance with custom prefix, suffix, separator and format
098     * for components.
099     * @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/ouput 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<Number>();
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
275        // parse suffix
276        CompositeFormat.parseAndIgnoreWhitespace(source, pos);
277        if (!CompositeFormat.parseFixedstring(source, trimmedSuffix, pos)) {
278            return null;
279        }
280
281        // build vector
282        double[] data = new double[components.size()];
283        for (int i = 0; i < data.length; ++i) {
284            data[i] = components.get(i).doubleValue();
285        }
286        return new ArrayRealVector(data, false);
287    }
288}