View Javadoc
1   package org.djutils.serialization.serializers;
2   
3   import java.lang.reflect.Constructor;
4   import java.lang.reflect.InvocationTargetException;
5   import java.util.HashMap;
6   import java.util.Map;
7   
8   import org.djunits.unit.SIUnit;
9   import org.djunits.unit.Unit;
10  import org.djunits.unit.scale.IdentityScale;
11  import org.djunits.unit.util.UnitRuntimeException;
12  import org.djunits.value.ValueRuntimeException;
13  import org.djunits.value.storage.StorageType;
14  import org.djunits.value.vfloat.matrix.FloatSIMatrix;
15  import org.djunits.value.vfloat.matrix.base.FloatMatrix;
16  import org.djunits.value.vfloat.matrix.data.FloatMatrixData;
17  import org.djunits.value.vfloat.scalar.base.FloatScalar;
18  import org.djunits.value.vfloat.vector.base.FloatVector;
19  import org.djutils.serialization.EndianUtil;
20  import org.djutils.serialization.FieldTypes;
21  import org.djutils.serialization.SerializationException;
22  
23  /**
24   * (De)serializes a DJUNITS FloatMatrix.
25   * <p>
26   * Copyright (c) 2019-2024 Delft University of Technology, PO Box 5, 2600 AA, Delft, the Netherlands. All rights reserved. <br>
27   * BSD-style license. See <a href="https://djunits.org/docs/license.html">DJUNITS License</a>.
28   * <p>
29   * @author <a href="https://www.tudelft.nl/averbraeck" target="_blank">Alexander Verbraeck</a>
30   * @param <U> the unit type
31   * @param <S> the scalar type
32   * @param <V> the vector type
33   * @param <M> the matrix type
34   */
35  public class FloatMatrixSerializer<U extends Unit<U>, S extends FloatScalar<U, S>, V extends FloatVector<U, S, V>,
36          M extends FloatMatrix<U, S, V, M>> extends ArrayOrMatrixWithUnitSerializer<U, M>
37  {
38      /** The cache to make the lookup of the constructor for a Vevtor belonging to a unit faster. */
39      private static final Map<Unit<?>, Constructor<? extends FloatMatrix<?, ?, ?, ?>>> CACHE = new HashMap<>();
40  
41      /** */
42      public FloatMatrixSerializer()
43      {
44          super(FieldTypes.FLOAT_32_UNIT_MATRIX, "Djunits_FloatMatrix", 2);
45      }
46  
47      /** {@inheritDoc} */
48      @Override
49      public int size(final M afm) throws SerializationException
50      {
51          try
52          {
53              return 4 + 4 + 2 + 4 * afm.rows() * afm.cols();
54          }
55          catch (ValueRuntimeException e)
56          {
57              throw new SerializationException(e);
58          }
59      }
60  
61      /** {@inheritDoc} */
62      @Override
63      public void serialize(final M afm, final byte[] buffer, final Pointer pointer, final EndianUtil endianUtil)
64              throws SerializationException
65      {
66          try
67          {
68              endianUtil.encodeInt(afm.rows(), buffer, pointer.getAndIncrement(4));
69              endianUtil.encodeInt(afm.cols(), buffer, pointer.getAndIncrement(4));
70              encodeUnit(afm.getDisplayUnit(), buffer, pointer, endianUtil);
71              for (int i = 0; i < afm.rows(); i++)
72              {
73                  for (int j = 0; j < afm.cols(); j++)
74                  {
75                      endianUtil.encodeFloat(afm.get(i, j).getSI(), buffer, pointer.getAndIncrement(4));
76                  }
77              }
78          }
79          catch (ValueRuntimeException e)
80          {
81              throw new SerializationException(e);
82          }
83      }
84  
85      /** {@inheritDoc} */
86      @Override
87      public M deSerialize(final byte[] buffer, final Pointer pointer, final EndianUtil endianUtil) throws SerializationException
88      {
89          int height = endianUtil.decodeInt(buffer, pointer.getAndIncrement(4));
90          int width = endianUtil.decodeInt(buffer, pointer.getAndIncrement(4));
91          Unit<? extends Unit<?>> unit = getUnit(buffer, pointer, endianUtil);
92          float[][] array = new float[height][width];
93          for (int i = 0; i < height; i++)
94          {
95              for (int j = 0; j < width; j++)
96              {
97                  array[i][j] = endianUtil.decodeFloat(buffer, pointer.getAndIncrement(4));
98              }
99          }
100         try
101         {
102             FloatMatrixData fvd = FloatMatrixData.instantiate(array, IdentityScale.SCALE, StorageType.DENSE);
103             return instantiateAnonymous(fvd, unit);
104         }
105         catch (ValueRuntimeException exception)
106         {
107             throw new SerializationException(exception);
108         }
109     }
110 
111     /**
112      * Instantiate the FloatMatrix based on its unit. Loose check for types on the compiler. This allows the unit to be
113      * specified as a Unit&lt;?&gt; type.<br>
114      * <b>Note</b> that it is possible to make mistakes with anonymous units.
115      * @param data FloatMatrixData; the values
116      * @param unit Unit&lt;?&gt;; the unit in which the value is expressed
117      * @return M; an instantiated FloatMatrix with the provided displayUunit
118      * @param <U> the unit type
119      * @param <S> the scalar type
120      * @param <V> the vector type
121      * @param <M> the matrix type
122      */
123     @SuppressWarnings("unchecked")
124     public static <U extends Unit<U>, S extends FloatScalar<U, S>, V extends FloatVector<U, S, V>,
125             M extends FloatMatrix<U, S, V, M>> M instantiateAnonymous(final FloatMatrixData data, final Unit<?> unit)
126     {
127         try
128         {
129             Constructor<? extends FloatMatrix<?, ?, ?, ?>> matrixConstructor = CACHE.get(unit);
130             if (matrixConstructor == null)
131             {
132                 if (!unit.getClass().getSimpleName().endsWith("Unit"))
133                 {
134                     throw new ClassNotFoundException("Unit " + unit.getClass().getSimpleName()
135                             + " name does noet end with 'Unit'. Cannot find corresponding scalar");
136                 }
137                 Class<? extends FloatMatrix<?, ?, ?, ?>> matrixClass;
138                 if (unit instanceof SIUnit)
139                 {
140                     matrixClass = FloatSIMatrix.class;
141                 }
142                 else
143                 {
144                     matrixClass = (Class<FloatMatrix<?, ?, ?, ?>>) Class.forName("org.djunits.value.vfloat.matrix.Float"
145                             + unit.getClass().getSimpleName().replace("Unit", "") + "Matrix");
146                 }
147                 matrixConstructor = matrixClass.getDeclaredConstructor(FloatMatrixData.class, unit.getClass());
148                 CACHE.put(unit, matrixConstructor);
149             }
150             return (M) matrixConstructor.newInstance(data, unit);
151         }
152         catch (ClassNotFoundException | NoSuchMethodException | SecurityException | InstantiationException
153                 | IllegalAccessException | IllegalArgumentException | InvocationTargetException exception)
154         {
155             throw new UnitRuntimeException(
156                     "Cannot instantiate FloatMatrix of unit " + unit.toString() + ". Reason: " + exception.getMessage());
157         }
158     }
159 
160 }