summaryrefslogtreecommitdiff
path: root/src/main/java/org/apache/commons/math3/linear/RealMatrixFormat.java
blob: d4eee6b3077ae7a5b7ef1533acb1c84175129138 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package org.apache.commons.math3.linear;

import org.apache.commons.math3.exception.MathParseException;
import org.apache.commons.math3.util.CompositeFormat;

import java.text.FieldPosition;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

/**
 * Formats a {@code nxm} matrix in components list format
 * "{{a<sub>0</sub><sub>0</sub>,a<sub>0</sub><sub>1</sub>, ...,
 * a<sub>0</sub><sub>m-1</sub>},{a<sub>1</sub><sub>0</sub>, a<sub>1</sub><sub>1</sub>, ...,
 * a<sub>1</sub><sub>m-1</sub>},{...},{ a<sub>n-1</sub><sub>0</sub>, a<sub>n-1</sub><sub>1</sub>,
 * ..., a<sub>n-1</sub><sub>m-1</sub>}}".
 *
 * <p>The prefix and suffix "{" and "}", the row prefix and suffix "{" and "}", the row separator
 * "," and the column separator "," can be replaced by any user-defined strings. The number format
 * for components can be configured.
 *
 * <p>White space is ignored at parse time, even if it is in the prefix, suffix or separator
 * specifications. So even if the default separator does include a space character that is used at
 * format time, both input string "{{1,1,1}}" and " { { 1 , 1 , 1 } } " will be parsed without error
 * and the same matrix will be returned. In the second case, however, the parse position after
 * parsing will be just after the closing curly brace, i.e. just before the trailing space.
 *
 * <p><b>Note:</b> the grouping functionality of the used {@link NumberFormat} is disabled to
 * prevent problems when parsing (e.g. 1,345.34 would be a valid number but conflicts with the
 * default column separator).
 *
 * @since 3.1
 */
public class RealMatrixFormat {

    /** The default prefix: "{". */
    private static final String DEFAULT_PREFIX = "{";

    /** The default suffix: "}". */
    private static final String DEFAULT_SUFFIX = "}";

    /** The default row prefix: "{". */
    private static final String DEFAULT_ROW_PREFIX = "{";

    /** The default row suffix: "}". */
    private static final String DEFAULT_ROW_SUFFIX = "}";

    /** The default row separator: ",". */
    private static final String DEFAULT_ROW_SEPARATOR = ",";

    /** The default column separator: ",". */
    private static final String DEFAULT_COLUMN_SEPARATOR = ",";

    /** Prefix. */
    private final String prefix;

    /** Suffix. */
    private final String suffix;

    /** Row prefix. */
    private final String rowPrefix;

    /** Row suffix. */
    private final String rowSuffix;

    /** Row separator. */
    private final String rowSeparator;

    /** Column separator. */
    private final String columnSeparator;

    /** The format used for components. */
    private final NumberFormat format;

    /**
     * Create an instance with default settings.
     *
     * <p>The instance uses the default prefix, suffix and row/column separator: "[", "]", ";" and
     * ", " and the default number format for components.
     */
    public RealMatrixFormat() {
        this(
                DEFAULT_PREFIX,
                DEFAULT_SUFFIX,
                DEFAULT_ROW_PREFIX,
                DEFAULT_ROW_SUFFIX,
                DEFAULT_ROW_SEPARATOR,
                DEFAULT_COLUMN_SEPARATOR,
                CompositeFormat.getDefaultNumberFormat());
    }

    /**
     * Create an instance with a custom number format for components.
     *
     * @param format the custom format for components.
     */
    public RealMatrixFormat(final NumberFormat format) {
        this(
                DEFAULT_PREFIX,
                DEFAULT_SUFFIX,
                DEFAULT_ROW_PREFIX,
                DEFAULT_ROW_SUFFIX,
                DEFAULT_ROW_SEPARATOR,
                DEFAULT_COLUMN_SEPARATOR,
                format);
    }

    /**
     * Create an instance with custom prefix, suffix and separator.
     *
     * @param prefix prefix to use instead of the default "{"
     * @param suffix suffix to use instead of the default "}"
     * @param rowPrefix row prefix to use instead of the default "{"
     * @param rowSuffix row suffix to use instead of the default "}"
     * @param rowSeparator tow separator to use instead of the default ";"
     * @param columnSeparator column separator to use instead of the default ", "
     */
    public RealMatrixFormat(
            final String prefix,
            final String suffix,
            final String rowPrefix,
            final String rowSuffix,
            final String rowSeparator,
            final String columnSeparator) {
        this(
                prefix,
                suffix,
                rowPrefix,
                rowSuffix,
                rowSeparator,
                columnSeparator,
                CompositeFormat.getDefaultNumberFormat());
    }

    /**
     * Create an instance with custom prefix, suffix, separator and format for components.
     *
     * @param prefix prefix to use instead of the default "{"
     * @param suffix suffix to use instead of the default "}"
     * @param rowPrefix row prefix to use instead of the default "{"
     * @param rowSuffix row suffix to use instead of the default "}"
     * @param rowSeparator tow separator to use instead of the default ";"
     * @param columnSeparator column separator to use instead of the default ", "
     * @param format the custom format for components.
     */
    public RealMatrixFormat(
            final String prefix,
            final String suffix,
            final String rowPrefix,
            final String rowSuffix,
            final String rowSeparator,
            final String columnSeparator,
            final NumberFormat format) {
        this.prefix = prefix;
        this.suffix = suffix;
        this.rowPrefix = rowPrefix;
        this.rowSuffix = rowSuffix;
        this.rowSeparator = rowSeparator;
        this.columnSeparator = columnSeparator;
        this.format = format;
        // disable grouping to prevent parsing problems
        this.format.setGroupingUsed(false);
    }

    /**
     * Get the set of locales for which real vectors formats are available.
     *
     * <p>This is the same set as the {@link NumberFormat} set.
     *
     * @return available real vector format locales.
     */
    public static Locale[] getAvailableLocales() {
        return NumberFormat.getAvailableLocales();
    }

    /**
     * Get the format prefix.
     *
     * @return format prefix.
     */
    public String getPrefix() {
        return prefix;
    }

    /**
     * Get the format suffix.
     *
     * @return format suffix.
     */
    public String getSuffix() {
        return suffix;
    }

    /**
     * Get the format prefix.
     *
     * @return format prefix.
     */
    public String getRowPrefix() {
        return rowPrefix;
    }

    /**
     * Get the format suffix.
     *
     * @return format suffix.
     */
    public String getRowSuffix() {
        return rowSuffix;
    }

    /**
     * Get the format separator between rows of the matrix.
     *
     * @return format separator for rows.
     */
    public String getRowSeparator() {
        return rowSeparator;
    }

    /**
     * Get the format separator between components.
     *
     * @return format separator between components.
     */
    public String getColumnSeparator() {
        return columnSeparator;
    }

    /**
     * Get the components format.
     *
     * @return components format.
     */
    public NumberFormat getFormat() {
        return format;
    }

    /**
     * Returns the default real vector format for the current locale.
     *
     * @return the default real vector format.
     */
    public static RealMatrixFormat getInstance() {
        return getInstance(Locale.getDefault());
    }

    /**
     * Returns the default real vector format for the given locale.
     *
     * @param locale the specific locale used by the format.
     * @return the real vector format specific to the given locale.
     */
    public static RealMatrixFormat getInstance(final Locale locale) {
        return new RealMatrixFormat(CompositeFormat.getDefaultNumberFormat(locale));
    }

    /**
     * This method calls {@link #format(RealMatrix,StringBuffer,FieldPosition)}.
     *
     * @param m RealMatrix object to format.
     * @return a formatted matrix.
     */
    public String format(RealMatrix m) {
        return format(m, new StringBuffer(), new FieldPosition(0)).toString();
    }

    /**
     * Formats a {@link RealMatrix} object to produce a string.
     *
     * @param matrix the object to format.
     * @param toAppendTo where the text is to be appended
     * @param pos On input: an alignment field, if desired. On output: the offsets of the alignment
     *     field
     * @return the value passed in as toAppendTo.
     */
    public StringBuffer format(RealMatrix matrix, StringBuffer toAppendTo, FieldPosition pos) {

        pos.setBeginIndex(0);
        pos.setEndIndex(0);

        // format prefix
        toAppendTo.append(prefix);

        // format rows
        final int rows = matrix.getRowDimension();
        for (int i = 0; i < rows; ++i) {
            toAppendTo.append(rowPrefix);
            for (int j = 0; j < matrix.getColumnDimension(); ++j) {
                if (j > 0) {
                    toAppendTo.append(columnSeparator);
                }
                CompositeFormat.formatDouble(matrix.getEntry(i, j), format, toAppendTo, pos);
            }
            toAppendTo.append(rowSuffix);
            if (i < rows - 1) {
                toAppendTo.append(rowSeparator);
            }
        }

        // format suffix
        toAppendTo.append(suffix);

        return toAppendTo;
    }

    /**
     * Parse a string to produce a {@link RealMatrix} object.
     *
     * @param source String to parse.
     * @return the parsed {@link RealMatrix} object.
     * @throws MathParseException if the beginning of the specified string cannot be parsed.
     */
    public RealMatrix parse(String source) {
        final ParsePosition parsePosition = new ParsePosition(0);
        final RealMatrix result = parse(source, parsePosition);
        if (parsePosition.getIndex() == 0) {
            throw new MathParseException(
                    source, parsePosition.getErrorIndex(), Array2DRowRealMatrix.class);
        }
        return result;
    }

    /**
     * Parse a string to produce a {@link RealMatrix} object.
     *
     * @param source String to parse.
     * @param pos input/ouput parsing parameter.
     * @return the parsed {@link RealMatrix} object.
     */
    public RealMatrix parse(String source, ParsePosition pos) {
        int initialIndex = pos.getIndex();

        final String trimmedPrefix = prefix.trim();
        final String trimmedSuffix = suffix.trim();
        final String trimmedRowPrefix = rowPrefix.trim();
        final String trimmedRowSuffix = rowSuffix.trim();
        final String trimmedColumnSeparator = columnSeparator.trim();
        final String trimmedRowSeparator = rowSeparator.trim();

        // parse prefix
        CompositeFormat.parseAndIgnoreWhitespace(source, pos);
        if (!CompositeFormat.parseFixedstring(source, trimmedPrefix, pos)) {
            return null;
        }

        // parse components
        List<List<Number>> matrix = new ArrayList<List<Number>>();
        List<Number> rowComponents = new ArrayList<Number>();
        for (boolean loop = true; loop; ) {

            if (!rowComponents.isEmpty()) {
                CompositeFormat.parseAndIgnoreWhitespace(source, pos);
                if (!CompositeFormat.parseFixedstring(source, trimmedColumnSeparator, pos)) {
                    if (trimmedRowSuffix.length() != 0
                            && !CompositeFormat.parseFixedstring(source, trimmedRowSuffix, pos)) {
                        return null;
                    } else {
                        CompositeFormat.parseAndIgnoreWhitespace(source, pos);
                        if (CompositeFormat.parseFixedstring(source, trimmedRowSeparator, pos)) {
                            matrix.add(rowComponents);
                            rowComponents = new ArrayList<Number>();
                            continue;
                        } else {
                            loop = false;
                        }
                    }
                }
            } else {
                CompositeFormat.parseAndIgnoreWhitespace(source, pos);
                if (trimmedRowPrefix.length() != 0
                        && !CompositeFormat.parseFixedstring(source, trimmedRowPrefix, pos)) {
                    return null;
                }
            }

            if (loop) {
                CompositeFormat.parseAndIgnoreWhitespace(source, pos);
                Number component = CompositeFormat.parseNumber(source, format, pos);
                if (component != null) {
                    rowComponents.add(component);
                } else {
                    if (rowComponents.isEmpty()) {
                        loop = false;
                    } else {
                        // invalid component
                        // set index back to initial, error index should already be set
                        pos.setIndex(initialIndex);
                        return null;
                    }
                }
            }
        }

        if (!rowComponents.isEmpty()) {
            matrix.add(rowComponents);
        }

        // parse suffix
        CompositeFormat.parseAndIgnoreWhitespace(source, pos);
        if (!CompositeFormat.parseFixedstring(source, trimmedSuffix, pos)) {
            return null;
        }

        // do not allow an empty matrix
        if (matrix.isEmpty()) {
            pos.setIndex(initialIndex);
            return null;
        }

        // build vector
        double[][] data = new double[matrix.size()][];
        int row = 0;
        for (List<Number> rowList : matrix) {
            data[row] = new double[rowList.size()];
            for (int i = 0; i < rowList.size(); i++) {
                data[row][i] = rowList.get(i).doubleValue();
            }
            row++;
        }
        return MatrixUtils.createRealMatrix(data);
    }
}