RealMatrixFormat.java

  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. package org.apache.commons.math4.legacy.linear;

  18. import java.text.FieldPosition;
  19. import java.text.NumberFormat;
  20. import java.text.ParsePosition;
  21. import java.util.ArrayList;
  22. import java.util.List;
  23. import java.util.Locale;

  24. import org.apache.commons.math4.legacy.exception.MathParseException;
  25. import org.apache.commons.math4.legacy.util.CompositeFormat;

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

  51.     /** The default prefix: "{". */
  52.     private static final String DEFAULT_PREFIX = "{";
  53.     /** The default suffix: "}". */
  54.     private static final String DEFAULT_SUFFIX = "}";
  55.     /** The default row prefix: "{". */
  56.     private static final String DEFAULT_ROW_PREFIX = "{";
  57.     /** The default row suffix: "}". */
  58.     private static final String DEFAULT_ROW_SUFFIX = "}";
  59.     /** The default row separator: ",". */
  60.     private static final String DEFAULT_ROW_SEPARATOR = ",";
  61.     /** The default column separator: ",". */
  62.     private static final String DEFAULT_COLUMN_SEPARATOR = ",";
  63.     /** Prefix. */
  64.     private final String prefix;
  65.     /** Suffix. */
  66.     private final String suffix;
  67.     /** Row prefix. */
  68.     private final String rowPrefix;
  69.     /** Row suffix. */
  70.     private final String rowSuffix;
  71.     /** Row separator. */
  72.     private final String rowSeparator;
  73.     /** Column separator. */
  74.     private final String columnSeparator;
  75.     /** The format used for components. */
  76.     private final NumberFormat format;

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

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

  94.     /**
  95.      * Create an instance with custom prefix, suffix and separator.
  96.      * @param prefix prefix to use instead of the default "{"
  97.      * @param suffix suffix to use instead of the default "}"
  98.      * @param rowPrefix row prefix to use instead of the default "{"
  99.      * @param rowSuffix row suffix to use instead of the default "}"
  100.      * @param rowSeparator tow separator to use instead of the default ";"
  101.      * @param columnSeparator column separator to use instead of the default ", "
  102.      */
  103.     public RealMatrixFormat(final String prefix, final String suffix,
  104.                             final String rowPrefix, final String rowSuffix,
  105.                             final String rowSeparator, final String columnSeparator) {
  106.         this(prefix, suffix, rowPrefix, rowSuffix, rowSeparator, columnSeparator,
  107.                 CompositeFormat.getDefaultNumberFormat());
  108.     }

  109.     /**
  110.      * Create an instance with custom prefix, suffix, separator and format
  111.      * for components.
  112.      * @param prefix prefix to use instead of the default "{"
  113.      * @param suffix suffix to use instead of the default "}"
  114.      * @param rowPrefix row prefix to use instead of the default "{"
  115.      * @param rowSuffix row suffix to use instead of the default "}"
  116.      * @param rowSeparator tow separator to use instead of the default ";"
  117.      * @param columnSeparator column separator to use instead of the default ", "
  118.      * @param format the custom format for components.
  119.      */
  120.     public RealMatrixFormat(final String prefix, final String suffix,
  121.                             final String rowPrefix, final String rowSuffix,
  122.                             final String rowSeparator, final String columnSeparator,
  123.                             final NumberFormat format) {
  124.         this.prefix            = prefix;
  125.         this.suffix            = suffix;
  126.         this.rowPrefix         = rowPrefix;
  127.         this.rowSuffix         = rowSuffix;
  128.         this.rowSeparator      = rowSeparator;
  129.         this.columnSeparator   = columnSeparator;
  130.         this.format            = format;
  131.         // disable grouping to prevent parsing problems
  132.         this.format.setGroupingUsed(false);
  133.     }

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

  142.     /**
  143.      * Get the format prefix.
  144.      * @return format prefix.
  145.      */
  146.     public String getPrefix() {
  147.         return prefix;
  148.     }

  149.     /**
  150.      * Get the format suffix.
  151.      * @return format suffix.
  152.      */
  153.     public String getSuffix() {
  154.         return suffix;
  155.     }

  156.     /**
  157.      * Get the format prefix.
  158.      * @return format prefix.
  159.      */
  160.     public String getRowPrefix() {
  161.         return rowPrefix;
  162.     }

  163.     /**
  164.      * Get the format suffix.
  165.      * @return format suffix.
  166.      */
  167.     public String getRowSuffix() {
  168.         return rowSuffix;
  169.     }

  170.     /**
  171.      * Get the format separator between rows of the matrix.
  172.      * @return format separator for rows.
  173.      */
  174.     public String getRowSeparator() {
  175.         return rowSeparator;
  176.     }

  177.     /**
  178.      * Get the format separator between components.
  179.      * @return format separator between components.
  180.      */
  181.     public String getColumnSeparator() {
  182.         return columnSeparator;
  183.     }

  184.     /**
  185.      * Get the components format.
  186.      * @return components format.
  187.      */
  188.     public NumberFormat getFormat() {
  189.         return format;
  190.     }

  191.     /**
  192.      * Returns the default real vector format for the current locale.
  193.      * @return the default real vector format.
  194.      */
  195.     public static RealMatrixFormat getInstance() {
  196.         return getInstance(Locale.getDefault());
  197.     }

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

  206.     /**
  207.      * This method calls {@link #format(RealMatrix,StringBuffer,FieldPosition)}.
  208.      *
  209.      * @param m RealMatrix object to format.
  210.      * @return a formatted matrix.
  211.      */
  212.     public String format(RealMatrix m) {
  213.         return format(m, new StringBuffer(), new FieldPosition(0)).toString();
  214.     }

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

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

  227.         // format prefix
  228.         toAppendTo.append(prefix);

  229.         // format rows
  230.         final int rows = matrix.getRowDimension();
  231.         for (int i = 0; i < rows; ++i) {
  232.             toAppendTo.append(rowPrefix);
  233.             for (int j = 0; j < matrix.getColumnDimension(); ++j) {
  234.                 if (j > 0) {
  235.                     toAppendTo.append(columnSeparator);
  236.                 }
  237.                 CompositeFormat.formatDouble(matrix.getEntry(i, j), format, toAppendTo, pos);
  238.             }
  239.             toAppendTo.append(rowSuffix);
  240.             if (i < rows - 1) {
  241.                 toAppendTo.append(rowSeparator);
  242.             }
  243.         }

  244.         // format suffix
  245.         toAppendTo.append(suffix);

  246.         return toAppendTo;
  247.     }

  248.     /**
  249.      * Parse a string to produce a {@link RealMatrix} object.
  250.      *
  251.      * @param source String to parse.
  252.      * @return the parsed {@link RealMatrix} object.
  253.      * @throws MathParseException if the beginning of the specified string
  254.      * cannot be parsed.
  255.      */
  256.     public RealMatrix parse(String source) {
  257.         final ParsePosition parsePosition = new ParsePosition(0);
  258.         final RealMatrix result = parse(source, parsePosition);
  259.         if (parsePosition.getIndex() == 0) {
  260.             throw new MathParseException(source,
  261.                                          parsePosition.getErrorIndex(),
  262.                                          Array2DRowRealMatrix.class);
  263.         }
  264.         return result;
  265.     }

  266.     /**
  267.      * Parse a string to produce a {@link RealMatrix} object.
  268.      *
  269.      * @param source String to parse.
  270.      * @param pos input/output parsing parameter.
  271.      * @return the parsed {@link RealMatrix} object.
  272.      */
  273.     public RealMatrix parse(String source, ParsePosition pos) {
  274.         int initialIndex = pos.getIndex();

  275.         final String trimmedPrefix = prefix.trim();
  276.         final String trimmedSuffix = suffix.trim();
  277.         final String trimmedRowPrefix = rowPrefix.trim();
  278.         final String trimmedRowSuffix = rowSuffix.trim();
  279.         final String trimmedColumnSeparator = columnSeparator.trim();
  280.         final String trimmedRowSeparator = rowSeparator.trim();

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

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

  290.             if (!rowComponents.isEmpty()) {
  291.                 CompositeFormat.parseAndIgnoreWhitespace(source, pos);
  292.                 if (!CompositeFormat.parseFixedstring(source, trimmedColumnSeparator, pos)) {
  293.                     if (!trimmedRowSuffix.isEmpty() &&
  294.                         !CompositeFormat.parseFixedstring(source, trimmedRowSuffix, pos)) {
  295.                         return null;
  296.                     }
  297.                     CompositeFormat.parseAndIgnoreWhitespace(source, pos);
  298.                     if (CompositeFormat.parseFixedstring(source, trimmedRowSeparator, pos)) {
  299.                         matrix.add(rowComponents);
  300.                         rowComponents = new ArrayList<>();
  301.                         continue;
  302.                     }
  303.                     loop = false;
  304.                 }
  305.             } else {
  306.                 CompositeFormat.parseAndIgnoreWhitespace(source, pos);
  307.                 if (!trimmedRowPrefix.isEmpty() &&
  308.                     !CompositeFormat.parseFixedstring(source, trimmedRowPrefix, pos)) {
  309.                     return null;
  310.                 }
  311.             }

  312.             if (loop) {
  313.                 CompositeFormat.parseAndIgnoreWhitespace(source, pos);
  314.                 Number component = CompositeFormat.parseNumber(source, format, pos);
  315.                 if (component != null) {
  316.                     rowComponents.add(component);
  317.                 } else {
  318.                     if (rowComponents.isEmpty()) {
  319.                         loop = false;
  320.                     } else {
  321.                         // invalid component
  322.                         // set index back to initial, error index should already be set
  323.                         pos.setIndex(initialIndex);
  324.                         return null;
  325.                     }
  326.                 }
  327.             }
  328.         }

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

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

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

  342.         // build vector
  343.         double[][] data = new double[matrix.size()][];
  344.         int row = 0;
  345.         for (List<Number> rowList : matrix) {
  346.             data[row] = new double[rowList.size()];
  347.             for (int i = 0; i < rowList.size(); i++) {
  348.                 data[row][i] = rowList.get(i).doubleValue();
  349.             }
  350.             row++;
  351.         }
  352.         return MatrixUtils.createRealMatrix(data);
  353.     }
  354. }