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 {@code nxm} matrix in components list format
38   * "{{a<sub>0</sub><sub>0</sub>,a<sub>0</sub><sub>1</sub>, ...,
39   * a<sub>0</sub><sub>m-1</sub>},{a<sub>1</sub><sub>0</sub>,
40   * a<sub>1</sub><sub>1</sub>, ..., a<sub>1</sub><sub>m-1</sub>},{...},{
41   * a<sub>n-1</sub><sub>0</sub>, a<sub>n-1</sub><sub>1</sub>, ...,
42   * a<sub>n-1</sub><sub>m-1</sub>}}".
43   * <p>The prefix and suffix "{" and "}", the row prefix and suffix "{" and "}",
44   * the row separator "," and the column separator "," can be replaced by any
45   * user-defined strings. The number format for components can be configured.</p>
46   *
47   * <p>White space is ignored at parse time, even if it is in the prefix, suffix
48   * or separator specifications. So even if the default separator does include a space
49   * character that is used at format time, both input string "{{1,1,1}}" and
50   * " { { 1 , 1 , 1 } } " will be parsed without error and the same matrix will be
51   * returned. In the second case, however, the parse position after parsing will be
52   * just after the closing curly brace, i.e. just before the trailing space.</p>
53   *
54   * <p><b>Note:</b> the grouping functionality of the used {@link NumberFormat} is
55   * disabled to prevent problems when parsing (e.g. 1,345.34 would be a valid number
56   * but conflicts with the default column separator).</p>
57   *
58   */
59  public class RealMatrixFormat {
60  
61      /** The default prefix: "{". */
62      private static final String DEFAULT_PREFIX = "{";
63      /** The default suffix: "}". */
64      private static final String DEFAULT_SUFFIX = "}";
65      /** The default row prefix: "{". */
66      private static final String DEFAULT_ROW_PREFIX = "{";
67      /** The default row suffix: "}". */
68      private static final String DEFAULT_ROW_SUFFIX = "}";
69      /** The default row separator: ",". */
70      private static final String DEFAULT_ROW_SEPARATOR = ",";
71      /** The default column separator: ",". */
72      private static final String DEFAULT_COLUMN_SEPARATOR = ",";
73      /** Prefix. */
74      private final String prefix;
75      /** Suffix. */
76      private final String suffix;
77      /** Row prefix. */
78      private final String rowPrefix;
79      /** Row suffix. */
80      private final String rowSuffix;
81      /** Row separator. */
82      private final String rowSeparator;
83      /** Column separator. */
84      private final String columnSeparator;
85      /** The format used for components. */
86      private final NumberFormat format;
87  
88      /**
89       * Create an instance with default settings.
90       * <p>The instance uses the default prefix, suffix and row/column separator:
91       * "[", "]", ";" and ", " and the default number format for components.</p>
92       */
93      public RealMatrixFormat() {
94          this(DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ROW_PREFIX, DEFAULT_ROW_SUFFIX,
95                  DEFAULT_ROW_SEPARATOR, DEFAULT_COLUMN_SEPARATOR, CompositeFormat.getDefaultNumberFormat());
96      }
97  
98      /**
99       * Create an instance with a custom number format for components.
100      * @param format the custom format for components.
101      */
102     public RealMatrixFormat(final NumberFormat format) {
103         this(DEFAULT_PREFIX, DEFAULT_SUFFIX, DEFAULT_ROW_PREFIX, DEFAULT_ROW_SUFFIX,
104                 DEFAULT_ROW_SEPARATOR, DEFAULT_COLUMN_SEPARATOR, format);
105     }
106 
107     /**
108      * Create an instance with custom prefix, suffix and separator.
109      * @param prefix prefix to use instead of the default "{"
110      * @param suffix suffix to use instead of the default "}"
111      * @param rowPrefix row prefix to use instead of the default "{"
112      * @param rowSuffix row suffix to use instead of the default "}"
113      * @param rowSeparator tow separator to use instead of the default ";"
114      * @param columnSeparator column separator to use instead of the default ", "
115      */
116     public RealMatrixFormat(final String prefix, final String suffix,
117                             final String rowPrefix, final String rowSuffix,
118                             final String rowSeparator, final String columnSeparator) {
119         this(prefix, suffix, rowPrefix, rowSuffix, rowSeparator, columnSeparator,
120                 CompositeFormat.getDefaultNumberFormat());
121     }
122 
123     /**
124      * Create an instance with custom prefix, suffix, separator and format
125      * for components.
126      * @param prefix prefix to use instead of the default "{"
127      * @param suffix suffix to use instead of the default "}"
128      * @param rowPrefix row prefix to use instead of the default "{"
129      * @param rowSuffix row suffix to use instead of the default "}"
130      * @param rowSeparator tow separator to use instead of the default ";"
131      * @param columnSeparator column separator to use instead of the default ", "
132      * @param format the custom format for components.
133      */
134     public RealMatrixFormat(final String prefix, final String suffix,
135                             final String rowPrefix, final String rowSuffix,
136                             final String rowSeparator, final String columnSeparator,
137                             final NumberFormat format) {
138         this.prefix            = prefix;
139         this.suffix            = suffix;
140         this.rowPrefix         = rowPrefix;
141         this.rowSuffix         = rowSuffix;
142         this.rowSeparator      = rowSeparator;
143         this.columnSeparator   = columnSeparator;
144         this.format            = format;
145         // disable grouping to prevent parsing problems
146         this.format.setGroupingUsed(false);
147     }
148 
149     /**
150      * Get the set of locales for which real vectors formats are available.
151      * <p>This is the same set as the {@link NumberFormat} set.</p>
152      * @return available real vector format locales.
153      */
154     public static Locale[] getAvailableLocales() {
155         return NumberFormat.getAvailableLocales();
156     }
157 
158     /**
159      * Get the format prefix.
160      * @return format prefix.
161      */
162     public String getPrefix() {
163         return prefix;
164     }
165 
166     /**
167      * Get the format suffix.
168      * @return format suffix.
169      */
170     public String getSuffix() {
171         return suffix;
172     }
173 
174     /**
175      * Get the format prefix.
176      * @return format prefix.
177      */
178     public String getRowPrefix() {
179         return rowPrefix;
180     }
181 
182     /**
183      * Get the format suffix.
184      * @return format suffix.
185      */
186     public String getRowSuffix() {
187         return rowSuffix;
188     }
189 
190     /**
191      * Get the format separator between rows of the matrix.
192      * @return format separator for rows.
193      */
194     public String getRowSeparator() {
195         return rowSeparator;
196     }
197 
198     /**
199      * Get the format separator between components.
200      * @return format separator between components.
201      */
202     public String getColumnSeparator() {
203         return columnSeparator;
204     }
205 
206     /**
207      * Get the components format.
208      * @return components format.
209      */
210     public NumberFormat getFormat() {
211         return format;
212     }
213 
214     /**
215      * Returns the default real vector format for the current locale.
216      * @return the default real vector format.
217      * @since 1.4
218      */
219     public static RealMatrixFormat getRealMatrixFormat() {
220         return getRealMatrixFormat(Locale.getDefault());
221     }
222 
223     /**
224      * Returns the default real vector format for the given locale.
225      * @param locale the specific locale used by the format.
226      * @return the real vector format specific to the given locale.
227      * @since 1.4
228      */
229     public static RealMatrixFormat getRealMatrixFormat(final Locale locale) {
230         return new RealMatrixFormat(CompositeFormat.getDefaultNumberFormat(locale));
231     }
232 
233     /**
234      * This method calls {@link #format(RealMatrix,StringBuffer,FieldPosition)}.
235      *
236      * @param m RealMatrix object to format.
237      * @return a formatted matrix.
238      */
239     public String format(RealMatrix m) {
240         return format(m, new StringBuffer(), new FieldPosition(0)).toString();
241     }
242 
243     /**
244      * Formats a {@link RealMatrix} object to produce a string.
245      * @param matrix the object to format.
246      * @param toAppendTo where the text is to be appended
247      * @param pos On input: an alignment field, if desired. On output: the
248      *            offsets of the alignment field
249      * @return the value passed in as toAppendTo.
250      */
251     public StringBuffer format(RealMatrix matrix, StringBuffer toAppendTo,
252                                FieldPosition pos) {
253 
254         pos.setBeginIndex(0);
255         pos.setEndIndex(0);
256 
257         // format prefix
258         toAppendTo.append(prefix);
259 
260         // format rows
261         final int rows = matrix.getRowDimension();
262         for (int i = 0; i < rows; ++i) {
263             toAppendTo.append(rowPrefix);
264             for (int j = 0; j < matrix.getColumnDimension(); ++j) {
265                 if (j > 0) {
266                     toAppendTo.append(columnSeparator);
267                 }
268                 CompositeFormat.formatDouble(matrix.getEntry(i, j), format, toAppendTo, pos);
269             }
270             toAppendTo.append(rowSuffix);
271             if (i < rows - 1) {
272                 toAppendTo.append(rowSeparator);
273             }
274         }
275 
276         // format suffix
277         toAppendTo.append(suffix);
278 
279         return toAppendTo;
280     }
281 
282     /**
283      * Parse a string to produce a {@link RealMatrix} object.
284      *
285      * @param source String to parse.
286      * @return the parsed {@link RealMatrix} object.
287      * @throws MathIllegalStateException if the beginning of the specified string
288      * cannot be parsed.
289      */
290     public RealMatrix parse(String source) {
291         final ParsePosition parsePosition = new ParsePosition(0);
292         final RealMatrix result = parse(source, parsePosition);
293         if (parsePosition.getIndex() == 0) {
294             throw new MathIllegalStateException(LocalizedCoreFormats.CANNOT_PARSE_AS_TYPE,
295                                                 source, parsePosition.getErrorIndex(),
296                                                 Array2DRowRealMatrix.class);
297         }
298         return result;
299     }
300 
301     /**
302      * Parse a string to produce a {@link RealMatrix} object.
303      *
304      * @param source String to parse.
305      * @param pos input/ouput parsing parameter.
306      * @return the parsed {@link RealMatrix} object.
307      */
308     public RealMatrix parse(String source, ParsePosition pos) {
309         int initialIndex = pos.getIndex();
310 
311         final String trimmedPrefix = prefix.trim();
312         final String trimmedSuffix = suffix.trim();
313         final String trimmedRowPrefix = rowPrefix.trim();
314         final String trimmedRowSuffix = rowSuffix.trim();
315         final String trimmedColumnSeparator = columnSeparator.trim();
316         final String trimmedRowSeparator = rowSeparator.trim();
317 
318         // parse prefix
319         CompositeFormat.parseAndIgnoreWhitespace(source, pos);
320         if (!CompositeFormat.parseFixedstring(source, trimmedPrefix, pos)) {
321             return null;
322         }
323 
324         // parse components
325         List<List<Number>> matrix = new ArrayList<>();
326         List<Number> rowComponents = new ArrayList<>();
327         for (boolean loop = true; loop;){
328 
329             if (!rowComponents.isEmpty()) {
330                 CompositeFormat.parseAndIgnoreWhitespace(source, pos);
331                 if (!CompositeFormat.parseFixedstring(source, trimmedColumnSeparator, pos)) {
332                     if (trimmedRowSuffix.length() != 0 &&
333                         !CompositeFormat.parseFixedstring(source, trimmedRowSuffix, pos)) {
334                         return null;
335                     } else {
336                         CompositeFormat.parseAndIgnoreWhitespace(source, pos);
337                         if (CompositeFormat.parseFixedstring(source, trimmedRowSeparator, pos)) {
338                             matrix.add(rowComponents);
339                             rowComponents = new ArrayList<>();
340                             continue;
341                         } else {
342                             loop = false;
343                         }
344                     }
345                 }
346             } else {
347                 CompositeFormat.parseAndIgnoreWhitespace(source, pos);
348                 if (trimmedRowPrefix.length() != 0 &&
349                     !CompositeFormat.parseFixedstring(source, trimmedRowPrefix, pos)) {
350                     return null;
351                 }
352             }
353 
354             if (loop) {
355                 CompositeFormat.parseAndIgnoreWhitespace(source, pos);
356                 Number component = CompositeFormat.parseNumber(source, format, pos);
357                 if (component != null) {
358                     rowComponents.add(component);
359                 } else {
360                     if (rowComponents.isEmpty()) {
361                         loop = false;
362                     } else {
363                         // invalid component
364                         // set index back to initial, error index should already be set
365                         pos.setIndex(initialIndex);
366                         return null;
367                     }
368                 }
369             }
370 
371         }
372 
373         if (!rowComponents.isEmpty()) {
374             matrix.add(rowComponents);
375         }
376 
377         // parse suffix
378         CompositeFormat.parseAndIgnoreWhitespace(source, pos);
379         if (!CompositeFormat.parseFixedstring(source, trimmedSuffix, pos)) {
380             return null;
381         }
382 
383         // do not allow an empty matrix
384         if (matrix.isEmpty()) {
385             pos.setIndex(initialIndex);
386             return null;
387         }
388 
389         // build vector
390         double[][] data = new double[matrix.size()][];
391         int row = 0;
392         for (List<Number> rowList : matrix) {
393             data[row] = new double[rowList.size()];
394             for (int i = 0; i < rowList.size(); i++) {
395                 data[row][i] = rowList.get(i).doubleValue();
396             }
397             row++;
398         }
399         return MatrixUtils.createRealMatrix(data);
400     }
401 }