View Javadoc
1   package org.djunits.vecmat.table;
2   
3   import java.util.Objects;
4   
5   import org.djunits.formatter.TableFormat;
6   import org.djunits.formatter.TableFormatter;
7   import org.djunits.quantity.SIQuantity;
8   import org.djunits.quantity.def.Quantity;
9   import org.djunits.unit.UnitInterface;
10  import org.djunits.unit.si.SIUnit;
11  import org.djunits.vecmat.def.Table;
12  import org.djunits.vecmat.dn.VectorN;
13  import org.djunits.vecmat.storage.DataGridSi;
14  import org.djunits.vecmat.storage.DenseDoubleDataSi;
15  import org.djutils.exceptions.Throw;
16  
17  /**
18   * QuantityTable is a two-dimensonal table with quantities. The QuantityTable allows for Hadamard (element-wise) operations, but
19   * not for vector/matrix operations. A QuantityTable can be transformed to a MatrixNxM or vice versa.
20   * <p>
21   * Copyright (c) 2025-2026 Delft University of Technology, Jaffalaan 5, 2628 BX Delft, the Netherlands. All rights reserved. See
22   * for project information <a href="https://djunits.org" target="_blank">https://djunits.org</a>. The DJUNITS project is
23   * distributed under a <a href="https://djunits.org/docs/license.html" target="_blank">three-clause BSD-style license</a>.
24   * @author Alexander Verbraeck
25   * @param <Q> the quantity type
26   */
27  public class QuantityTable<Q extends Quantity<Q>>
28          extends Table<Q, QuantityTable<Q>, QuantityTable<SIQuantity>, QuantityTable<?>, QuantityTable<Q>>
29  {
30      /** */
31      private static final long serialVersionUID = 600L;
32  
33      /** The data of the table, in SI unit. */
34      private final DataGridSi<?> dataGridSi;
35  
36      /**
37       * Create a new NxM QuantityTable with a unit, based on a DataGrid storage object. This constructor assumes dataSi stores SI
38       * values. Note: NO safe copy is made.
39       * @param dataGridSi the data of the matrix, in SI unit.
40       * @param displayUnit the display unit to use
41       */
42      public QuantityTable(final DataGridSi<?> dataGridSi, final UnitInterface<Q> displayUnit)
43      {
44          super(displayUnit);
45          Throw.whenNull(dataGridSi, "dataGridSi");
46          this.dataGridSi = dataGridSi;
47      }
48  
49      @Override
50      public QuantityTable<Q> instantiateSi(final double[] siNew, final UnitInterface<Q> displayUnit)
51      {
52          return new QuantityTable<Q>(this.dataGridSi.instantiateNew(siNew), displayUnit);
53      }
54  
55      @Override
56      public QuantityTable<SIQuantity> instantiateSi(final double[] siNew, final SIUnit siUnit)
57      {
58          return new QuantityTable<SIQuantity>(this.dataGridSi.instantiateNew(siNew), siUnit);
59      }
60  
61      /**
62       * Return the internal datagrid object, so we can retrieve data from it.
63       * @return the internal datagrid object
64       */
65      public DataGridSi<?> getDataGrid()
66      {
67          return this.dataGridSi;
68      }
69  
70      @Override
71      public double[] getSiArray()
72      {
73          return this.dataGridSi.getSiArray();
74      }
75  
76      @Override
77      public double[] unsafeSiArray()
78      {
79          return this.dataGridSi.unsafeSiArray();
80      }
81  
82      @Override
83      public double si(final int row, final int col) throws IndexOutOfBoundsException
84      {
85          checkRow(row);
86          checkCol(col);
87          return this.dataGridSi.get(row, col);
88      }
89  
90      @Override
91      public VectorN.Row<Q> getRowVector(final int row)
92      {
93          return VectorN.Row.ofSi(getRowSi(row), getDisplayUnit());
94      }
95  
96      @Override
97      public VectorN.Row<Q> mgetRowVector(final int mRow)
98      {
99          return VectorN.Row.ofSi(mgetRowSi(mRow), getDisplayUnit());
100     }
101 
102     @Override
103     public VectorN.Col<Q> getColumnVector(final int col)
104     {
105         return VectorN.Col.ofSi(getColumnSi(col), getDisplayUnit());
106     }
107 
108     @Override
109     public VectorN.Col<Q> mgetColumnVector(final int mCol)
110     {
111         return VectorN.Col.ofSi(mgetColumnSi(mCol), getDisplayUnit());
112     }
113 
114     @Override
115     public double[] getRowSi(final int row)
116     {
117         checkRow(row);
118         return this.dataGridSi.getRowArray(row);
119     }
120 
121     @Override
122     public double[] getColumnSi(final int col)
123     {
124         checkCol(col);
125         return this.dataGridSi.getColArray(col);
126     }
127 
128     @Override
129     public int rows()
130     {
131         return this.dataGridSi.rows();
132     }
133 
134     @Override
135     public int cols()
136     {
137         return this.dataGridSi.cols();
138     }
139 
140     @Override
141     public int nonZeroCount()
142     {
143         return this.dataGridSi.nonZeroCount();
144     }
145 
146     /**
147      * Return the transposed quantity table. A transposed quantity table has the same unit as the original one.
148      * @return the transposed quantity table
149      */
150     @Override
151     @SuppressWarnings("checkstyle:needbraces")
152     public QuantityTable<Q> transpose()
153     {
154         double[] data = unsafeSiArray();
155         double[] newSi = new double[data.length];
156         int rows = rows();
157         int cols = cols();
158         final UnitInterface<Q> displayUnit = getDisplayUnit();
159         for (int r = 0; r < rows; r++)
160             for (int c = 0; c < cols; c++)
161                 newSi[c * rows + r] = data[r * cols + c];
162         return new QuantityTable<Q>(this.dataGridSi.instantiateNew(newSi, cols, rows), displayUnit);
163     }
164 
165     // --------------------------------------- EQUALS AND HASHCODE ---------------------------------
166 
167     @Override
168     public int hashCode()
169     {
170         return Objects.hash(this.dataGridSi);
171     }
172 
173     @SuppressWarnings("checkstyle:needbraces")
174     @Override
175     public boolean equals(final Object obj)
176     {
177         if (this == obj)
178             return true;
179         if (obj == null)
180             return false;
181         if (getClass() != obj.getClass())
182             return false;
183         QuantityTable<?> other = (QuantityTable<?>) obj;
184         return Objects.equals(this.dataGridSi, other.dataGridSi);
185     }
186 
187     // ------------------------------------------ OF METHODS ------------------------------------------
188 
189     /**
190      * Create a new QuantityTable with a unit, based on a row-major array with values in the given unit.
191      * @param dataInUnit the table values {a11, a12, ..., A1M, ..., aN1, aN2, ..., aNM} expressed in the unit
192      * @param rows the number of rows
193      * @param cols the number of columns
194      * @param unit the unit of the data, also used as the display unit
195      * @param <Q> the quantity type
196      * @return a new QuantityTable with a unit
197      * @throws IllegalArgumentException when dataInUnit does not contain a square number of values
198      */
199     public static <Q extends Quantity<Q>> QuantityTable<Q> of(final double[] dataInUnit, final int rows, final int cols,
200             final UnitInterface<Q> unit)
201     {
202         return new QuantityTable<Q>(DenseDoubleDataSi.of(dataInUnit, rows, cols, unit), unit);
203     }
204 
205     /**
206      * Create a QuantityTable without needing generics, based on a row-major array with SI-values.
207      * @param dataSi the table values {a11, a12, ..., A1M, ..., aN1, aN2, ..., aNM} as an array using SI units
208      * @param rows the number of rows
209      * @param cols the number of columns
210      * @param displayUnit the display unit to use
211      * @return a new QuantityTable with a unit
212      * @param <Q> the quantity type
213      * @throws IllegalArgumentException when dataSi does not contain a square number of values
214      */
215     public static <Q extends Quantity<Q>> QuantityTable<Q> ofSi(final double[] dataSi, final int rows, final int cols,
216             final UnitInterface<Q> displayUnit)
217     {
218         return new QuantityTable<Q>(DenseDoubleDataSi.ofSi(dataSi, rows, cols), displayUnit);
219     }
220 
221     /**
222      * Create a QuantityTable without needing generics, based on a row-major array of quantities. The unit is taken from the
223      * first quantity in the array.
224      * @param data the table values {a11, a12, ..., A1M, ..., aN1, aN2, ..., aNM} expressed as an array of quantities
225      * @param rows the number of rows
226      * @param cols the number of columns
227      * @return a new QuantityTable with a unit
228      * @param <Q> the quantity type
229      * @throws IllegalArgumentException when data does not contain a square number of quantities
230      */
231     public static <Q extends Quantity<Q>> QuantityTable<Q> of(final Q[] data, final int rows, final int cols)
232     {
233         Throw.whenNull(data, "data");
234         Throw.when(data.length == 0, IllegalArgumentException.class, "data.length = 0");
235         return new QuantityTable<Q>(DenseDoubleDataSi.of(data, rows, cols), data[0].getDisplayUnit());
236     }
237 
238     /**
239      * Create a new QuantityTable with a unit, based on a 2-dimensional grid with SI-values.
240      * @param gridSi the table values {{a11, a12, ..., A1M}, ..., {aN1, aN2, ..., aNM}} expressed in the SI or base unit
241      * @param displayUnit the unit of the data, which will also be used as the display unit
242      * @param <Q> the quantity type
243      * @return a new QuantityTable with a unit
244      * @throws IllegalArgumentException when dataInUnit does not contain a square number of values
245      */
246     @SuppressWarnings("checkstyle:needbraces")
247     public static <Q extends Quantity<Q>> QuantityTable<Q> ofSi(final double[][] gridSi, final UnitInterface<Q> displayUnit)
248     {
249         return new QuantityTable<>(DenseDoubleDataSi.ofSi(gridSi), displayUnit);
250     }
251 
252     /**
253      * Create a new QuantityTable with a unit, based on a 2-dimensional grid with values in the given unit.
254      * @param gridInUnit the table values {{a11, a12, ..., A1M}, ..., {aN1, aN2, ..., aNM}} expressed in the unit
255      * @param unit the unit of the values, also used as the display unit
256      * @param <Q> the quantity type
257      * @return a new QuantityTable with a unit
258      * @throws IllegalArgumentException when dataInUnit does not contain a square number of values
259      */
260     @SuppressWarnings("checkstyle:needbraces")
261     public static <Q extends Quantity<Q>> QuantityTable<Q> of(final double[][] gridInUnit, final UnitInterface<Q> unit)
262     {
263         return new QuantityTable<>(DenseDoubleDataSi.of(gridInUnit, unit), unit);
264     }
265 
266     /**
267      * Create a QuantityTable without needing generics, based on a 2-dimensional grid of quantities. The unit is taken from the
268      * first quantity in the grid.
269      * @param grid the table values {{a11, a12, ..., A1M}, ..., {aN1, aN2, ..., aNM}} expressed as a 2-dimensional array of
270      *            quantities
271      * @return a new QuantityTable with a unit
272      * @param <Q> the quantity type
273      * @throws IllegalArgumentException when dataInUnit does not contain a square number of quantities
274      */
275     public static <Q extends Quantity<Q>> QuantityTable<Q> of(final Q[][] grid)
276     {
277         Throw.whenNull(grid, "grid");
278         Throw.when(grid.length == 0, IllegalArgumentException.class, "grid.length = 0");
279         Throw.whenNull(grid[0], "grid[0] = null");
280         Throw.when(grid[0].length == 0, IllegalArgumentException.class, "grid[0].length = 0");
281         Throw.whenNull(grid[0][0], "grid[0][0] = null");
282         return new QuantityTable<>(DenseDoubleDataSi.of(grid), grid[0][0].getDisplayUnit());
283     }
284 
285     // ------------------------------------------------- AS() METHODS -------------------------------------------------
286 
287     /**
288      * Return the QuantityTable 'as' a QuantityTable with a known quantity, using a unit to express the result in. Throw a
289      * Runtime exception when the SI units of this vector and the target vector do not match.
290      * @param targetUnit the unit to convert the quantity table to
291      * @return a quantity table typed in the target quantity table class
292      * @throws IllegalArgumentException when the units do not match
293      * @param <TQ> target quantity type
294      */
295     public <TQ extends Quantity<TQ>> QuantityTable<TQ> as(final UnitInterface<TQ> targetUnit) throws IllegalArgumentException
296     {
297         Throw.when(!getDisplayUnit().siUnit().equals(targetUnit.siUnit()), IllegalArgumentException.class,
298                 "QuantityTable.as(%s) called, but units do not match: %s <> %s", targetUnit,
299                 getDisplayUnit().siUnit().getDisplayAbbreviation(), targetUnit.siUnit().getDisplayAbbreviation());
300         return new QuantityTable<TQ>(this.dataGridSi.instantiateNew(unsafeSiArray()), targetUnit);
301     }
302 
303     // ----------------------------------------- STRING AND FORMATTING METHODS ----------------------------------------
304 
305     /**
306      * Concise description of this quantity table.
307      * @return a String with the quantity table, with the unit attached.
308      */
309     @Override
310     public String format()
311     {
312         return format(TableFormat.instance());
313     }
314 
315     /**
316      * String representation of this quantity table after applying the format.
317      * @param format the format to apply for the quantity table
318      * @return a String representation of this quantity table, formatted according to the given format
319      */
320     public String format(final TableFormat format)
321     {
322         return TableFormatter.format(this, format);
323     }
324 
325     /**
326      * String representation of this quantity table, expressed in the specified unit.
327      * @param targetUnit the unit into which the values of the quantity table are converted for display
328      * @return printable string with the quantity table's values expressed in the specified unit
329      */
330     @Override
331     public String format(final UnitInterface<Q> targetUnit)
332     {
333         return format(TableFormat.instance().setDisplayUnit(targetUnit));
334     }
335 
336 }