SST  14.0.0
StructuralSimulationToolkit
unitAlgebra.h
1 // -*- c++ -*-
2 
3 // Copyright 2009-2024 NTESS. Under the terms
4 // of Contract DE-NA0003525 with NTESS, the U.S.
5 // Government retains certain rights in this software.
6 //
7 // Copyright (c) 2009-2024, NTESS
8 // All rights reserved.
9 //
10 // This file is part of the SST software package. For license
11 // information, see the LICENSE file in the top level directory of the
12 // distribution.
13 
14 #ifndef SST_CORE_UNITALGEBRA_H
15 #define SST_CORE_UNITALGEBRA_H
16 
17 #include "sst/core/decimal_fixedpoint.h"
18 #include "sst/core/serialization/serializable.h"
19 #include "sst/core/serialization/serializer.h"
20 #include "sst/core/sst_types.h"
21 #include "sst/core/warnmacros.h"
22 
23 #include <map>
24 #include <mutex>
25 #include <string>
26 #include <vector>
27 
28 namespace SST {
29 
30 // typedef decimal_fixedpoint<3,3> sst_dec_float;
31 typedef decimal_fixedpoint<3, 3> sst_big_num;
32 
33 /**
34  * Helper class internal to UnitAlgebra.
35  *
36  * Contains information on valid units
37  */
38 class Units
39 {
40 
41  typedef uint8_t unit_id_t;
42 
43 private:
44  friend class UnitAlgebra;
45 
46  // Static data members and functions
47  static std::recursive_mutex unit_lock;
48  static std::map<std::string, unit_id_t> valid_base_units;
49  static std::map<std::string, std::pair<Units, sst_big_num>> valid_compound_units;
50  static std::map<unit_id_t, std::string> unit_strings;
51  static unit_id_t count;
52  static bool initialized;
53 
54  static bool initialize();
55 
56  // Non-static data members and functions
57  std::vector<unit_id_t> numerator;
58  std::vector<unit_id_t> denominator;
59 
60  void reduce();
61  // Used in constructor to incrementally build up unit from string
62  void addUnit(const std::string&, sst_big_num& multiplier, bool invert);
63 
64 public:
65  // Static data members and functions
66  /** Create a new Base Unit type */
67  static void registerBaseUnit(const std::string& u);
68  /** Create a new Compound Unit type */
69  static void registerCompoundUnit(const std::string& u, const std::string& v);
70 
71  // Non-static data members and functions
72  /** Create a new instantiation of a Units with a base unit string, and multiplier
73  * @param units String representing the new unit
74  * @param multiplier Value by which to multiply to get to this unit
75  */
76  Units(const std::string& units, sst_big_num& multiplier);
77  Units() {}
78  virtual ~Units() {}
79 
80  /** Copy constructor */
81  Units(const Units&) = default;
82 
83  /** Assignment operator */
84  Units& operator=(const Units& v);
85  /** Self-multiplication operator */
86  Units& operator*=(const Units& v);
87  /** Self-division operator */
88  Units& operator/=(const Units& v);
89  /** Equality Operator */
90  bool operator==(const Units& lhs) const;
91  /** Inequality Operator */
92  bool operator!=(const Units& lhs) const { return !(*this == lhs); }
93  /** Perform a reciprocal operation. Numerator and Denominator swap. */
94  Units& invert();
95 
96  /** Return a String representation if this Unit */
97  std::string toString() const;
98 };
99 
100 /**
101  * Performs Unit math in full precision
102  *
103  * Allows operations such as multiplying a frequency by 2.
104  *
105  */
106 class UnitAlgebra :
109 {
110 private:
111  Units unit;
112  sst_big_num value;
113 
114  static std::string trim(const std::string& str);
115 
116 public:
117  void init(const std::string& val);
118 
119  UnitAlgebra() {}
120  /**
121  Create a new UnitAlgebra instance, and pre-populate with a parsed value.
122 
123  @param val Value to parse. It is of the following format:
124  @code
125  val := NUMBER( )?UNITS
126  NUMBER := (-)?[0-9]+(.[0-9]+)?
127  UNITS := UNITGROUP(/UNITGROUP)
128  UNITGROUP := UNIT(-UNIT)*
129  UNIT := (SIPREFIX)?(BASEUNIT|COMPUNIT)
130  SIPREFIX := {a,f,p,n,u,m,[kKMGTPE]i?}
131  BASEUNIT := {s,B,b,events}
132  COMPUNIT := {Hz,hz,Bps,bps,event}
133  @endcode
134  */
135  UnitAlgebra(const std::string& val);
136  virtual ~UnitAlgebra();
137 
138  /** Copy constructor */
139  UnitAlgebra(const UnitAlgebra&) = default;
140 
141  /** Print to an ostream the value
142  * @param stream Output stream
143  * @param precision Number of digits to print. Default is 6. <= 0 is full precision.
144  */
145  void print(std::ostream& stream, int32_t precision = 6);
146  /** Print to an ostream the value
147  * Formats the number using SI-prefixes
148  * @param stream Output stream
149  * @param precision Number of digits to print. Default is 6. <= 0 is full precision.
150  */
151  void printWithBestSI(std::ostream& stream, int32_t precision = 6);
152  /** Return a string representation of this value
153  * @param precision Number of digits to print. Default is 6. <= 0 is full precision.
154  */
155  std::string toString(int32_t precision = 6) const;
156  /** Return a string representation of this value
157  * Formats the number using SI-prefixes
158  * @param precision Number of digits to print. Default is 6. <= 0 is full precision.
159  */
160  std::string toStringBestSI(int32_t precision = 6) const;
161 
162  UnitAlgebra& operator=(const std::string& v);
163 
164  /** Multiply by an argument; */
166  /** Multiply by an argument; */
167  template <typename T>
168  UnitAlgebra& operator*=(const T& v)
169  {
170  value *= v;
171  return *this;
172  }
173 
174  /** Divide by an argument; */
176  /** Divide by an argument; */
177  template <typename T>
178  UnitAlgebra& operator/=(const T& v)
179  {
180  value /= v;
181  return *this;
182  }
183 
184  /** Add an argument; */
186  /** Multiply by an argument; */
187  template <typename T>
188  UnitAlgebra& operator+=(const T& v)
189  {
190  value += v;
191  return *this;
192  }
193 
194  /** Subtract an argument; */
196  /** Divide by an argument; */
197  template <typename T>
198  UnitAlgebra& operator-=(const T& v)
199  {
200  value -= v;
201  return *this;
202  }
203 
204  /** Compare if this object is greater than the argument */
205  bool operator>(const UnitAlgebra& v) const;
206  /** Compare if this object is greater than, or equal to, the argument */
207  bool operator>=(const UnitAlgebra& v) const;
208  /** Compare if this object is less than the argument */
209  bool operator<(const UnitAlgebra& v) const;
210  /** Compare if this object is less than, or equal to, the argument */
211  bool operator<=(const UnitAlgebra& v) const;
212  /** Compare if this object is equal to, the argument */
213  bool operator==(const UnitAlgebra& v) const;
214  /** Compare if this object is not equal to, the argument */
215  bool operator!=(const UnitAlgebra& v) const;
216  /** Apply a reciprocal operation to the object */
217  UnitAlgebra& invert();
218 
219  /** Returns true if the units in the parameter string are found
220  * in this object.
221  */
222  bool hasUnits(const std::string& u) const;
223  /** Return the raw value */
224  sst_big_num getValue() const { return value; }
225  /** @return Rounded value as a 64bit integer */
226  int64_t getRoundedValue() const;
227  double getDoubleValue() const;
228  bool isValueZero() const;
229 
230  void serialize_order(SST::Core::Serialization::serializer& ser) override
231  {
232  // Do the unit
233  ser& unit.numerator;
234  ser& unit.denominator;
235 
236  // For value, need to convert cpp_dec_float to string and
237  // reinit from string
238  switch ( ser.mode() ) {
239  case SST::Core::Serialization::serializer::SIZER:
240  case SST::Core::Serialization::serializer::PACK:
241  {
242  // std::string s = value.str(40, std::ios_base::fixed);
243  std::string s = value.toString(0);
244  ser& s;
245  break;
246  }
247  case SST::Core::Serialization::serializer::UNPACK:
248  {
249  std::string s;
250  ser& s;
251  value = sst_big_num(s);
252  break;
253  }
254  }
255  }
256  ImplementSerializable(SST::UnitAlgebra)
257 
258 public:
259  /** Base exception for all exception classes in UnitAlgebra
260  *
261  * This exception inherits from std::logic_error, as all exceptions
262  * thrown in UnitAlgebra are considered configuration errors occurring
263  * prior to simulation start, rather than runtime errors.
264  */
265  class UnitAlgebraException : public std::logic_error
266  {
267  public:
268  /**
269  * @param msg exception message displayed as-is without modification
270  */
271  UnitAlgebraException(const std::string& msg);
272  };
273 
274  /** Exception for when units are not recognized or are invalid
275  */
276  class InvalidUnitType : public UnitAlgebraException
277  {
278  public:
279  /**
280  * @param type string containing invalid type
281  */
282  InvalidUnitType(const std::string& type);
283  };
284 
285  /** Exception for when number couldn't be parsed
286  */
287  class InvalidNumberString : public UnitAlgebraException
288  {
289  public:
290  /**
291  * @param number string containing invalid number
292  */
293  InvalidNumberString(const std::string& number);
294  };
295 
296  /** Exception for when attempting operations between objects that do not have matching base units
297  */
298  class NonMatchingUnits : public UnitAlgebraException
299  {
300  public:
301  /**
302  * @param lhs units for UnitAlgebra on left-hand side of operation
303  * @param rhs units for UnitAlgebra on right-hand side of operation
304  * @param operation representation of operation attempted between units
305  */
306  NonMatchingUnits(const std::string& lhs, const std::string& rhs, const std::string& operation);
307  };
308 };
309 
310 // template <typename T>
311 // UnitAlgebra operator* (UnitAlgebra lhs, const T& rhs);
312 
313 // template <typename T>
314 // UnitAlgebra operator* (const T& lhs, UnitAlgebra rhs);
315 
316 // UnitAlgebra operator* (UnitAlgebra& lhs, const UnitAlgebra rhs);
317 
318 // template <typename T>
319 // UnitAlgebra operator/ (UnitAlgebra lhs, const T& rhs);
320 
321 // std::ostream& operator<< (std::ostream& os, const UnitAlgebra& r);
322 
323 // std::ostream& operator<< (std::ostream& os, const Units& r);
324 
325 template <typename T>
327 operator*(UnitAlgebra lhs, const T& rhs)
328 {
329  lhs *= rhs;
330  return lhs;
331 }
332 
333 // template <typename T>
334 // UnitAlgebra operator* (const T& lhs, UnitAlgebra rhs)
335 // {
336 // rhs *= lhs;
337 // return rhs;
338 // }
339 
340 inline UnitAlgebra
341 operator*(UnitAlgebra lhs, const UnitAlgebra& rhs)
342 {
343  lhs *= rhs;
344  return lhs;
345 }
346 
347 template <typename T>
348 UnitAlgebra
349 operator/(UnitAlgebra lhs, const T& rhs)
350 {
351  lhs /= rhs;
352  return lhs;
353 }
354 
355 inline UnitAlgebra
356 operator/(UnitAlgebra lhs, const UnitAlgebra& rhs)
357 {
358  lhs /= rhs;
359  return lhs;
360 }
361 
362 template <typename T>
363 UnitAlgebra
364 operator+(UnitAlgebra lhs, const T& rhs)
365 {
366  lhs += rhs;
367  return lhs;
368 }
369 
370 inline UnitAlgebra
371 operator+(UnitAlgebra lhs, const UnitAlgebra& rhs)
372 {
373  lhs += rhs;
374  return lhs;
375 }
376 
377 template <typename T>
378 UnitAlgebra
379 operator-(UnitAlgebra lhs, const T& rhs)
380 {
381  lhs -= rhs;
382  return lhs;
383 }
384 
385 inline UnitAlgebra
386 operator-(UnitAlgebra lhs, const UnitAlgebra& rhs)
387 {
388  lhs -= rhs;
389  return lhs;
390 }
391 
392 inline std::ostream&
393 operator<<(std::ostream& os, const UnitAlgebra& r)
394 {
395  os << r.toString();
396  return os;
397 }
398 
399 inline std::ostream&
400 operator<<(std::ostream& os, const Units& r)
401 {
402  os << r.toString();
403  return os;
404 }
405 
406 } // namespace SST
407 
408 #endif // SST_CORE_UNITALGEBRA_H
Units & operator*=(const Units &v)
Self-multiplication operator.
Definition: unitAlgebra.cc:244
UnitAlgebra & operator/=(const UnitAlgebra &v)
Divide by an argument;.
Definition: unitAlgebra.cc:432
This class is basically a wrapper for objects to declare the order in which their members should be s...
Definition: serializer.h:35
bool operator<=(const UnitAlgebra &v) const
Compare if this object is less than, or equal to, the argument.
Definition: unitAlgebra.cc:480
bool operator>=(const UnitAlgebra &v) const
Compare if this object is greater than, or equal to, the argument.
Definition: unitAlgebra.cc:463
std::string toString(int32_t precision=6) const
Create a string representation of this decimal_fixedpoint.
Definition: decimal_fixedpoint.h:440
bool operator>(const UnitAlgebra &v) const
Compare if this object is greater than the argument.
Definition: unitAlgebra.cc:456
Definition: action.cc:18
UnitAlgebra & operator+=(const T &v)
Multiply by an argument;.
Definition: unitAlgebra.h:188
Units & operator=(const Units &v)
Assignment operator.
Definition: unitAlgebra.cc:236
static void registerBaseUnit(const std::string &u)
Create a new Base Unit type.
Definition: unitAlgebra.cc:183
sst_big_num getValue() const
Return the raw value.
Definition: unitAlgebra.h:224
Definition: serializable.h:118
Exception for when number couldn&#39;t be parsed.
Definition: unitAlgebra.h:287
Units & invert()
Perform a reciprocal operation.
Definition: unitAlgebra.cc:278
bool operator<(const UnitAlgebra &v) const
Compare if this object is less than the argument.
Definition: unitAlgebra.cc:473
UnitAlgebra & operator*=(const T &v)
Multiply by an argument;.
Definition: unitAlgebra.h:168
void print(std::ostream &stream, int32_t precision=6)
Print to an ostream the value.
Definition: unitAlgebra.cc:375
bool operator==(const UnitAlgebra &v) const
Compare if this object is equal to, the argument.
Definition: unitAlgebra.cc:487
bool operator!=(const Units &lhs) const
Inequality Operator.
Definition: unitAlgebra.h:92
NonMatchingUnits(const std::string &lhs, const std::string &rhs, const std::string &operation)
Definition: unitAlgebra.cc:554
InvalidUnitType(const std::string &type)
Definition: unitAlgebra.cc:546
Exception for when attempting operations between objects that do not have matching base units...
Definition: unitAlgebra.h:298
UnitAlgebra & operator-=(const T &v)
Divide by an argument;.
Definition: unitAlgebra.h:198
InvalidNumberString(const std::string &number)
Definition: unitAlgebra.cc:550
bool operator==(const Units &lhs) const
Equality Operator.
Definition: unitAlgebra.cc:264
Base exception for all exception classes in UnitAlgebra.
Definition: unitAlgebra.h:276
UnitAlgebra & invert()
Apply a reciprocal operation to the object.
Definition: unitAlgebra.cc:501
bool operator!=(const UnitAlgebra &v) const
Compare if this object is not equal to, the argument.
Definition: unitAlgebra.cc:494
UnitAlgebra & operator/=(const T &v)
Divide by an argument;.
Definition: unitAlgebra.h:178
UnitAlgebra & operator*=(const UnitAlgebra &v)
Multiply by an argument;.
Definition: unitAlgebra.cc:424
UnitAlgebra & operator+=(const UnitAlgebra &v)
Add an argument;.
Definition: unitAlgebra.cc:440
std::string toString() const
Return a String representation if this Unit.
Definition: unitAlgebra.cc:287
static void registerCompoundUnit(const std::string &u, const std::string &v)
Create a new Compound Unit type.
Definition: unitAlgebra.cc:194
UnitAlgebra & operator-=(const UnitAlgebra &v)
Subtract an argument;.
Definition: unitAlgebra.cc:448
std::string toStringBestSI(int32_t precision=6) const
Return a string representation of this value Formats the number using SI-prefixes.
Definition: unitAlgebra.cc:395
bool hasUnits(const std::string &u) const
Returns true if the units in the parameter string are found in this object.
Definition: unitAlgebra.cc:510
Performs Unit math in full precision.
Definition: unitAlgebra.h:106
void printWithBestSI(std::ostream &stream, int32_t precision=6)
Print to an ostream the value Formats the number using SI-prefixes.
Definition: unitAlgebra.cc:381
Units & operator/=(const Units &v)
Self-division operator.
Definition: unitAlgebra.cc:255
int64_t getRoundedValue() const
Definition: unitAlgebra.cc:520
std::string toString(int32_t precision=6) const
Return a string representation of this value.
Definition: unitAlgebra.cc:387
Helper class internal to UnitAlgebra.
Definition: unitAlgebra.h:38
Definition: serializable.h:138