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.  *      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.  * This is not the original file distributed by the Apache Software Foundation
  19.  * It has been modified by the Hipparchus project
  20.  */

  21. package org.hipparchus.linear;

  22. import java.text.FieldPosition;
  23. import java.text.NumberFormat;
  24. import java.text.ParsePosition;
  25. import java.util.ArrayList;
  26. import java.util.List;
  27. import java.util.Locale;

  28. import org.hipparchus.exception.LocalizedCoreFormats;
  29. import org.hipparchus.exception.MathIllegalStateException;
  30. import org.hipparchus.util.CompositeFormat;

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

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

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

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

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

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

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

  146.     /**
  147.      * Get the format prefix.
  148.      * @return format prefix.
  149.      */
  150.     public String getPrefix() {
  151.         return prefix;
  152.     }

  153.     /**
  154.      * Get the format suffix.
  155.      * @return format suffix.
  156.      */
  157.     public String getSuffix() {
  158.         return suffix;
  159.     }

  160.     /**
  161.      * Get the format prefix.
  162.      * @return format prefix.
  163.      */
  164.     public String getRowPrefix() {
  165.         return rowPrefix;
  166.     }

  167.     /**
  168.      * Get the format suffix.
  169.      * @return format suffix.
  170.      */
  171.     public String getRowSuffix() {
  172.         return rowSuffix;
  173.     }

  174.     /**
  175.      * Get the format separator between rows of the matrix.
  176.      * @return format separator for rows.
  177.      */
  178.     public String getRowSeparator() {
  179.         return rowSeparator;
  180.     }

  181.     /**
  182.      * Get the format separator between components.
  183.      * @return format separator between components.
  184.      */
  185.     public String getColumnSeparator() {
  186.         return columnSeparator;
  187.     }

  188.     /**
  189.      * Get the components format.
  190.      * @return components format.
  191.      */
  192.     public NumberFormat getFormat() {
  193.         return format;
  194.     }

  195.     /**
  196.      * Returns the default real vector format for the current locale.
  197.      * @return the default real vector format.
  198.      * @since 1.4
  199.      */
  200.     public static RealMatrixFormat getRealMatrixFormat() {
  201.         return getRealMatrixFormat(Locale.getDefault());
  202.     }

  203.     /**
  204.      * Returns the default real vector format for the given locale.
  205.      * @param locale the specific locale used by the format.
  206.      * @return the real vector format specific to the given locale.
  207.      * @since 1.4
  208.      */
  209.     public static RealMatrixFormat getRealMatrixFormat(final Locale locale) {
  210.         return new RealMatrixFormat(CompositeFormat.getDefaultNumberFormat(locale));
  211.     }

  212.     /**
  213.      * This method calls {@link #format(RealMatrix,StringBuffer,FieldPosition)}.
  214.      *
  215.      * @param m RealMatrix object to format.
  216.      * @return a formatted matrix.
  217.      */
  218.     public String format(RealMatrix m) {
  219.         return format(m, new StringBuffer(), new FieldPosition(0)).toString();
  220.     }

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

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

  233.         // format prefix
  234.         toAppendTo.append(prefix);

  235.         // format rows
  236.         final int rows = matrix.getRowDimension();
  237.         for (int i = 0; i < rows; ++i) {
  238.             toAppendTo.append(rowPrefix);
  239.             for (int j = 0; j < matrix.getColumnDimension(); ++j) {
  240.                 if (j > 0) {
  241.                     toAppendTo.append(columnSeparator);
  242.                 }
  243.                 CompositeFormat.formatDouble(matrix.getEntry(i, j), format, toAppendTo, pos);
  244.             }
  245.             toAppendTo.append(rowSuffix);
  246.             if (i < rows - 1) {
  247.                 toAppendTo.append(rowSeparator);
  248.             }
  249.         }

  250.         // format suffix
  251.         toAppendTo.append(suffix);

  252.         return toAppendTo;
  253.     }

  254.     /**
  255.      * Parse a string to produce a {@link RealMatrix} object.
  256.      *
  257.      * @param source String to parse.
  258.      * @return the parsed {@link RealMatrix} object.
  259.      * @throws MathIllegalStateException if the beginning of the specified string
  260.      * cannot be parsed.
  261.      */
  262.     public RealMatrix parse(String source) {
  263.         final ParsePosition parsePosition = new ParsePosition(0);
  264.         final RealMatrix result = parse(source, parsePosition);
  265.         if (parsePosition.getIndex() == 0) {
  266.             throw new MathIllegalStateException(LocalizedCoreFormats.CANNOT_PARSE_AS_TYPE,
  267.                                                 source, parsePosition.getErrorIndex(),
  268.                                                 Array2DRowRealMatrix.class);
  269.         }
  270.         return result;
  271.     }

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

  281.         final String trimmedPrefix = prefix.trim();
  282.         final String trimmedSuffix = suffix.trim();
  283.         final String trimmedRowPrefix = rowPrefix.trim();
  284.         final String trimmedRowSuffix = rowSuffix.trim();
  285.         final String trimmedColumnSeparator = columnSeparator.trim();
  286.         final String trimmedRowSeparator = rowSeparator.trim();

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

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

  296.             if (!rowComponents.isEmpty()) {
  297.                 CompositeFormat.parseAndIgnoreWhitespace(source, pos);
  298.                 if (!CompositeFormat.parseFixedstring(source, trimmedColumnSeparator, pos)) {
  299.                     if (!trimmedRowSuffix.isEmpty() &&
  300.                         !CompositeFormat.parseFixedstring(source, trimmedRowSuffix, pos)) {
  301.                         return null;
  302.                     } else {
  303.                         CompositeFormat.parseAndIgnoreWhitespace(source, pos);
  304.                         if (CompositeFormat.parseFixedstring(source, trimmedRowSeparator, pos)) {
  305.                             matrix.add(rowComponents);
  306.                             rowComponents = new ArrayList<>();
  307.                             continue;
  308.                         } else {
  309.                             loop = false;
  310.                         }
  311.                     }
  312.                 }
  313.             } else {
  314.                 CompositeFormat.parseAndIgnoreWhitespace(source, pos);
  315.                 if (!trimmedRowPrefix.isEmpty() &&
  316.                     !CompositeFormat.parseFixedstring(source, trimmedRowPrefix, pos)) {
  317.                     return null;
  318.                 }
  319.             }

  320.             if (loop) {
  321.                 CompositeFormat.parseAndIgnoreWhitespace(source, pos);
  322.                 Number component = CompositeFormat.parseNumber(source, format, pos);
  323.                 if (component != null) {
  324.                     rowComponents.add(component);
  325.                 } else {
  326.                     if (rowComponents.isEmpty()) {
  327.                         loop = false;
  328.                     } else {
  329.                         // invalid component
  330.                         // set index back to initial, error index should already be set
  331.                         pos.setIndex(initialIndex);
  332.                         return null;
  333.                     }
  334.                 }
  335.             }

  336.         }

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

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

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

  350.         // build vector
  351.         double[][] data = new double[matrix.size()][];
  352.         int row = 0;
  353.         for (List<Number> rowList : matrix) {
  354.             data[row] = new double[rowList.size()];
  355.             for (int i = 0; i < rowList.size(); i++) {
  356.                 data[row][i] = rowList.get(i).doubleValue();
  357.             }
  358.             row++;
  359.         }
  360.         return MatrixUtils.createRealMatrix(data);
  361.     }
  362. }