swift
Loading...
Searching...
No Matches
physicalquantity.cpp
1// SPDX-FileCopyrightText: Copyright (C) 2013 swift Project Community / Contributors
2// SPDX-License-Identifier: GPL-3.0-or-later OR LicenseRef-swift-pilot-client-1
3
5
6#include <cmath>
7#include <limits>
8
9#include <QDBusArgument>
10#include <QJsonObject>
11#include <QJsonValue>
12#include <QString>
13#include <QtGlobal>
14
16#include "misc/dictionary.h"
18#include "misc/pq/angle.h"
19#include "misc/pq/frequency.h"
20#include "misc/pq/length.h"
21#include "misc/pq/mass.h"
23#include "misc/pq/pqstring.h"
24#include "misc/pq/pressure.h"
25#include "misc/pq/speed.h"
26#include "misc/pq/temperature.h"
27#include "misc/pq/time.h"
30#include "misc/stringutils.h"
31#include "misc/verify.h"
32
34SWIFT_DEFINE_PQ_MIXINS(CLengthUnit, CLength)
35SWIFT_DEFINE_PQ_MIXINS(CPressureUnit, CPressure)
37SWIFT_DEFINE_PQ_MIXINS(CMassUnit, CMass)
38SWIFT_DEFINE_PQ_MIXINS(CTemperatureUnit, CTemperature)
39SWIFT_DEFINE_PQ_MIXINS(CSpeedUnit, CSpeed)
40SWIFT_DEFINE_PQ_MIXINS(CTimeUnit, CTime)
41SWIFT_DEFINE_PQ_MIXINS(CAccelerationUnit, CAcceleration)
42
43namespace swift::misc::physical_quantities
44{
45 template <class MU, class PQ>
47 {
48 return m_unit;
49 }
50
51 template <class MU, class PQ>
53 {
54 m_unit = unit;
55 }
56
57 template <class MU, class PQ>
59 {
60 m_unit = CMeasurementUnit::unitFromSymbol<MU>(unitName);
61 }
62
63 template <class MU, class PQ>
65 {
66 return m_unit.getSymbol(true);
67 }
68
69 template <class MU, class PQ>
71 : m_value(unit.isNull() ? 0.0 : value), m_unit(unit)
72 {
73 Q_ASSERT_X(!std::isnan(value), Q_FUNC_INFO, "nan value");
74 Q_ASSERT_X(!std::isinf(value), Q_FUNC_INFO, "infinity");
75 }
76
77 template <class MU, class PQ>
78 CPhysicalQuantity<MU, PQ>::CPhysicalQuantity(const QString &unitString) : m_value(0.0), m_unit(MU::nullUnit())
79 {
80 this->parseFromString(unitString);
81 }
82
83 template <class MU, class PQ>
84 bool CPhysicalQuantity<MU, PQ>::equals(const CPhysicalQuantity<MU, PQ> &other) const
85 {
86 if (this == &other) return true;
87
88 if (this->isNull()) return other.isNull();
89 if (other.isNull()) return false;
90
91 double diff = std::abs(m_value - other.value(m_unit));
92 return diff <= m_unit.getEpsilon();
93 }
94
95 template <class MU, class PQ>
97 {
98 m_value += other.value(m_unit);
99 return *this;
100 }
101
102 template <class MU, class PQ>
104 {
105 m_value += value;
106 }
107
108 template <class MU, class PQ>
110 {
111 m_value -= value;
112 }
113
114 template <class MU, class PQ>
116 {
117 m_value -= other.value(m_unit);
118 return *this;
119 }
120
121 template <class MU, class PQ>
123 {
124 return m_unit.isEpsilon(m_value);
125 }
126
127 template <class MU, class PQ>
129 {
130 return !this->isZeroEpsilonConsidered() && m_value > 0;
131 }
133 template <class MU, class PQ>
135 {
136 return !this->isZeroEpsilonConsidered() && m_value < 0;
137 }
138
139 template <class MU, class PQ>
141 {
142 if (this->isNull() || qFuzzyIsNull(m_value))
143 {
144 return *this->derived();
146 if (m_value < 0)
147 {
148 m_value *= -1.0;
149 }
150 return *this->derived();
152
153 template <class MU, class PQ>
155 {
156 if (this->isNull() || qFuzzyIsNull(m_value))
158 return *this->derived();
159 }
160 if (m_value > 0)
161 {
162 m_value *= -1.0;
164 return *this->derived();
165 }
167 template <class MU, class PQ>
169 {
170 if (this->isNull() || qFuzzyIsNull(m_value))
171 {
172 return *this->derived();
173 }
174 if (m_value >= 0)
175 {
176 return *this->derived();
177 }
178 PQ copy(*this->derived());
179 return copy.makePositive();
180 }
181
182 template <class MU, class PQ>
184 {
185 constexpr double NaN = std::numeric_limits<double>::quiet_NaN();
186 argument << (this->isNull() ? NaN : this->value(UnitClass::defaultUnit()));
187 }
188
189 template <class MU, class PQ>
191 {
192 argument >> m_value;
193 m_unit = UnitClass::defaultUnit();
194 if (std::isnan(m_value))
195 {
196 this->setNull();
197 }
198 }
199
200 template <class MU, class PQ>
202 {
203 argument << m_value;
204 argument << m_unit;
205 }
207 template <class MU, class PQ>
210 argument >> m_value;
211 argument >> m_unit;
213
214 template <class MU, class PQ>
216 {
217 constexpr double NaN = std::numeric_limits<double>::quiet_NaN();
218 stream << (this->isNull() ? NaN : this->value(UnitClass::defaultUnit()));
219 }
220
221 template <class MU, class PQ>
223 {
224 stream >> m_value;
225 m_unit = UnitClass::defaultUnit();
226 if (std::isnan(m_value))
228 this->setNull();
229 }
231
232 template <class MU, class PQ>
234 {
235 m_value *= factor;
236 return *this;
237 }
238
239 template <class MU, class PQ>
241 {
242 PQ copy = *derived();
243 copy *= factor;
244 return copy;
245 }
246
247 template <class MU, class PQ>
249 {
250 m_value /= divisor;
251 return *this;
252 }
253
254 template <class MU, class PQ>
256 {
257 PQ copy = *derived();
258 copy /= divisor;
259 return copy;
260 }
261
262 template <class MU, class PQ>
264 {
265 PQ copy = *derived();
266 copy *= -1;
267 return copy;
268 }
269
270 template <class MU, class PQ>
271 bool CPhysicalQuantity<MU, PQ>::lessThan(const CPhysicalQuantity<MU, PQ> &other) const
272 {
273 if (*this == other) return false;
274
275 if (isNull() < other.isNull())
277 return true;
278 }
279 if (isNull() > other.isNull())
280 {
281 return false;
283 if (isNull() && other.isNull())
284 {
285 return false;
286 }
287
288 return (m_value < other.value(m_unit));
289 }
290
291 template <class MU, class PQ>
293 {
294 // NULL check: https://discordapp.com/channels/539048679160676382/539925070550794240/593151683698229258
295 if (m_unit == newUnit || this->isNull())
296 {
297 return *derived();
298 }
299 if (newUnit.isNull())
300 {
301 this->setNull();
302 }
303 else
304 {
305 m_value = newUnit.convertFrom(m_value, m_unit);
306 m_unit = newUnit;
307 }
308 return *derived();
310
311 template <class MU, class PQ>
312 PQ CPhysicalQuantity<MU, PQ>::switchedUnit(const MU &newUnit) const
313 {
314 if (m_unit == newUnit || this->isNull())
316 return *derived();
317 }
318 PQ copy(*derived());
319 copy.switchUnit(newUnit);
320 return copy;
322
323 template <class MU, class PQ>
325 {
326 return m_unit.isNull();
328
329 template <class MU, class PQ>
331 {
332 m_value = 0;
333 m_unit = MU::nullUnit();
334 }
335
336 template <class MU, class PQ>
338 {
339 if (this->isNull())
340 {
341 return 0.0;
342 }
343 return m_value;
344 }
346 template <class MU, class PQ>
349 if (!this->isNull())
350 {
351 m_value = value;
352 }
353 }
355 template <class MU, class PQ>
358 m_value = baseValue;
359 }
360
361 template <class MU, class PQ>
362 QString CPhysicalQuantity<MU, PQ>::valueRoundedWithUnit(const MU &unit, int digits, bool withGroupSeparator,
363 bool i18n) const
365 Q_ASSERT_X(!unit.isNull(), Q_FUNC_INFO, "Cannot convert to null");
366 if (this->isNull())
367 {
368 return this->convertToQString(i18n);
369 }
370 return unit.makeRoundedQStringWithUnit(this->value(unit), digits, withGroupSeparator, i18n);
371 }
372
373 template <class MU, class PQ>
374 QString CPhysicalQuantity<MU, PQ>::valueRoundedWithUnit(int digits, bool withGroupSeparator, bool i18n) const
375 {
376 if (this->isNull())
377 {
378 return QStringLiteral("null");
379 }
380 return this->valueRoundedWithUnit(m_unit, digits, withGroupSeparator, i18n);
381 }
382
383 template <class MU, class PQ>
385 {
386 if (this->isNull())
387 {
388 return;
389 }
390 m_value = m_unit.roundToEpsilon(m_value);
391 }
392
393 template <class MU, class PQ>
394 double CPhysicalQuantity<MU, PQ>::valueRounded(MU unit, int digits) const
395 {
396 Q_ASSERT_X(!unit.isNull(), Q_FUNC_INFO, "Cannot convert to null");
397 return unit.roundValue(this->value(unit), digits);
398 }
399
400 template <class MU, class PQ>
402 {
403 Q_ASSERT_X(!unit.isNull(), Q_FUNC_INFO, "Cannot convert to null");
404 const double v = this->value(unit);
405 return qRound(v);
406 }
407
408 template <class MU, class PQ>
410 {
411 return this->valueInteger(m_unit);
412 }
413
414 template <class MU, class PQ>
416 {
417 if (this->isNull())
418 {
419 return false;
420 }
421
422 const double diff = std::abs(this->value() - this->valueInteger());
423 return diff <= m_unit.getEpsilon();
424 }
425
426 template <class MU, class PQ>
428 {
429 return this->valueRounded(m_unit, digits);
430 }
431
432 template <class MU, class PQ>
434 {
435 if (this->isNull())
436 {
437 return QStringLiteral("null");
438 }
439 const double v = this->valueRounded(unit, digits);
440 return QString::number(v, 'f', digits);
441 }
442
443 template <class MU, class PQ>
445 {
446 Q_ASSERT_X(!unit.isNull(), Q_FUNC_INFO, "Cannot convert to null");
447 return unit.convertFrom(m_value, m_unit);
448 }
449
450 template <class MU, class PQ>
452 {
453 if (this->isNull())
454 {
455 return QStringLiteral("null");
456 }
457 return this->valueRoundedWithUnit(this->getUnit(), -1, i18n);
458 }
459
460 template <class MU, class PQ>
461 const PQ &CPhysicalQuantity<MU, PQ>::maxValue(const PQ &pq1, const PQ &pq2)
462 {
463 if (pq1.isNull())
464 {
465 return pq2;
466 }
467 if (pq2.isNull())
468 {
469 return pq1;
470 }
471 return pq1 > pq2 ? pq1 : pq2;
472 }
473
474 template <class MU, class PQ>
475 const PQ &CPhysicalQuantity<MU, PQ>::minValue(const PQ &pq1, const PQ &pq2)
476 {
477 if (pq1.isNull())
478 {
479 return pq2;
480 }
481 if (pq2.isNull())
482 {
483 return pq1;
484 }
485 return pq1 < pq2 ? pq1 : pq2;
486 }
487
488 template <class MU, class PQ>
490 {
491 static const PQ n(0, MU::nullUnit());
492 return n;
493 }
494
495 template <class MU, class PQ>
497 {
498 // there is no double qHash
499 // also unit and rounding has to be considered
500 return qHash(this->valueRoundedWithUnit(MU::defaultUnit()));
501 }
502
503 template <class MU, class PQ>
505 {
506 QJsonObject json;
507 json.insert("value", QJsonValue(m_value));
508 json.insert("unit", QJsonValue(m_unit.getSymbol()));
509 return json;
510 }
511
512 template <class MU, class PQ>
514 {
515 const QJsonValue unit = json.value("unit");
516 const QJsonValue value = json.value("value");
517 if (unit.isUndefined())
518 {
519 throw CJsonException("Missing 'unit'");
520 }
521 if (value.isUndefined())
522 {
523 throw CJsonException("Missing 'value'");
524 }
525
526 this->setUnitBySymbol(unit.toString());
527 m_value = value.toDouble();
528 }
529
530 template <class MU, class PQ>
535
536 template <class MU, class PQ>
538 const MU &defaultUnitIfMissing)
539 {
541 {
542 const QString v = value + defaultUnitIfMissing.getSymbol();
543 this->parseFromString(v, mode);
544 }
545 else
546 {
547 this->parseFromString(value, mode);
548 }
549 }
550
551 template <class MU, class PQ>
556
557 template <class MU, class PQ>
559 const MU &defaultUnitIfMissing)
560 {
561 QString v = value;
563 {
564 v = value + defaultUnitIfMissing.getSymbol();
565 }
566
567 // no idea why I cannot call pq.parseFromString(v, mode, defaultUnitIfMissing);
568 PQ pq;
569 pq.parseFromString(v, mode);
570 return pq;
571 }
572
573 template <class MU, class PQ>
575 {
576 PQ pq;
577 pq.parseFromString(value, mode);
578 return pq;
579 }
580
581 template <class MU, class PQ>
583 {
584 if (index.isMyself())
585 {
586 return QVariant::fromValue(*derived());
587 }
588 const auto i = index.frontCasted<ColumnIndex>();
589 switch (i)
590 {
591 case IndexValue: return QVariant::fromValue(m_value);
592 case IndexUnit: return QVariant::fromValue(m_unit);
593 case IndexValueRounded0DigitsWithUnit: return QVariant::fromValue(this->valueRoundedWithUnit(0));
594 case IndexValueRounded1DigitsWithUnit: return QVariant::fromValue(this->valueRoundedWithUnit(1));
595 case IndexValueRounded2DigitsWithUnit: return QVariant::fromValue(this->valueRoundedWithUnit(2));
596 case IndexValueRounded3DigitsWithUnit: return QVariant::fromValue(this->valueRoundedWithUnit(3));
597 case IndexValueRounded6DigitsWithUnit: return QVariant::fromValue(this->valueRoundedWithUnit(6));
598 default: return mixin::Index<PQ>::propertyByIndex(index);
599 }
600 }
601
602 template <class MU, class PQ>
604 {
605 if (index.isMyself())
606 {
607 (*this) = variant.value<PQ>();
608 return;
609 }
610 const auto i = index.frontCasted<ColumnIndex>();
611 switch (i)
612 {
613 case IndexValue: m_value = variant.toDouble(); break;
614 case IndexUnit: m_unit = variant.value<MU>(); break;
615 case IndexValueRounded0DigitsWithUnit:
616 case IndexValueRounded1DigitsWithUnit:
617 case IndexValueRounded2DigitsWithUnit:
618 case IndexValueRounded3DigitsWithUnit:
619 case IndexValueRounded6DigitsWithUnit: this->parseFromString(variant.toString()); break;
620 default: mixin::Index<PQ>::setPropertyByIndex(index, variant); break;
621 }
622 }
623
624 template <class MU, class PQ>
626 {
627 if (index.isMyself())
628 {
629 return compareImpl(*derived(), pq);
630 }
631 const auto i = index.frontCasted<ColumnIndex>();
632 switch (i)
633 {
634 case IndexValue: return Compare::compare(m_value, pq.m_value);
635 default: break;
636 }
637 SWIFT_VERIFY_X(false, Q_FUNC_INFO, qUtf8Printable("No comparison for index " + index.toQString()));
638 return 0;
639 }
640
641 template <class MU, class PQ>
642 int CPhysicalQuantity<MU, PQ>::compareImpl(const PQ &a, const PQ &b)
643 {
644 if (a < b)
645 {
646 return -1;
647 }
648 else if (a > b)
649 {
650 return 1;
651 }
652 else
653 {
654 return 0;
655 }
656 }
657
658 template <class MU, class PQ>
659 PQ const *CPhysicalQuantity<MU, PQ>::derived() const
660 {
661 return static_cast<PQ const *>(this);
662 }
663
664 template <class MU, class PQ>
665 PQ *CPhysicalQuantity<MU, PQ>::derived()
666 {
667 return static_cast<PQ *>(this);
668 }
669
670 // see here for the reason of thess forward instantiations
671 // https://isocpp.org/wiki/faq/templates#separate-template-fn-defn-from-decl
683
684} // namespace swift::misc::physical_quantities
Physical unit angle (radians, degrees).
Definition angle.h:23
Specialized class for angles (degrees, radian).
Definition units.h:231
Physical unit frequency.
Definition frequency.h:18
Specialized class for frequency (hertz, mega hertz, kilo hertz).
Definition units.h:334
Thrown when a convertFromJson method encounters an unrecoverable error in JSON data.
Non-owning reference to a CPropertyIndex with a subset of its features.
QString toQString(bool i18n=false) const
Cast as QString.
CastType frontCasted() const
First element casted to given type, usually the PropertIndex enum.
bool isMyself() const
Myself index, used with nesting.
Tag type signifying overloaded marshalling methods that preserve data at the expense of size.
Definition mixindbus.h:26
void setPropertyByIndex(CPropertyIndexRef index, const QVariant &variant)
Set property by index.
Definition mixinindex.h:167
QVariant propertyByIndex(CPropertyIndexRef index) const
Property by index.
Definition mixinindex.h:180
static CAccelerationUnit defaultUnit()
Default unit.
Definition units.h:1061
static U unitFromSymbol(const QString &symbol, bool strict=true)
Unit from symbol.
A physical quantity such as "5m", "20s", "1500ft/s".
CPhysicalQuantity & operator+=(const CPhysicalQuantity &other)
Plus operator +=.
bool isNegativeWithEpsilonConsidered() const
Value <= 0 epsilon considered.
void setValueSameUnit(double value)
Change value without changing unit.
void parseFromString(const QString &value)
Parse value from string.
void unmarshallFromDbus(const QDBusArgument &argument)
Unmarshall without begin/endStructure, for when composed within another object.
static PQ parsedFromString(const QString &value, CPqString::SeparatorMode mode=CPqString::SeparatorBestGuess)
Parsed from given string.
PQ switchedUnit(const MU &newUnit) const
Return copy with switched unit.
PQ & switchUnit(const MU &newUnit)
Change unit, and convert value to maintain the same quantity.
void setUnitBySymbol(const QString &unitName)
Set unit by string.
size_t getValueHash() const
qHash overload, needed for storing value in a QSet.
QJsonObject toJson() const
Cast to JSON object.
void setPropertyByIndex(CPropertyIndexRef index, const QVariant &variant)
Set property by index.
static const PQ & minValue(const PQ &pq1, const PQ &pq2)
Minimum of 2 quantities.
int comparePropertyByIndex(CPropertyIndexRef index, const PQ &pq) const
Compare for index.
CPhysicalQuantity & operator-=(const CPhysicalQuantity &other)
Minus operator-=.
double value(MU unit) const
Value in given unit.
void unmarshalFromDataStream(QDataStream &stream)
Unmarshal a value from a QDataStream.
CPhysicalQuantity(double value, MU unit)
Constructor with double.
QString valueRoundedAsString(MU unit, int digits=-1) const
Rounded value in given unit.
void roundToEpsilon()
Round current value in current unit to epsilon.
void addValueSameUnit(double value)
Add to the value in the current unit.
QVariant propertyByIndex(CPropertyIndexRef index) const
Property by index.
void setUnit(const MU &unit)
Simply set unit, do no calclulate conversion.
void substractValueSameUnit(double value)
Substract from the value in the current unit.
CPhysicalQuantity & operator/=(double divide)
Divide operator /=.
void marshalToDataStream(QDataStream &stream) const
Marshal a value to a QDataStream.
int valueInteger() const
As integer value in current unit.
void convertFromJson(const QJsonObject &json)
Assign from JSON object.
void setCurrentUnitValue(double value)
Set value in current unit.
const PQ & makePositive()
Make value always positive.
static const PQ & maxValue(const PQ &pq1, const PQ &pq2)
Maximum of 2 quantities.
void marshallToDbus(QDBusArgument &argument) const
Marshall without begin/endStructure, for when composed within another object.
CPhysicalQuantity & operator*=(double multiply)
Multiply operator *=.
QString valueRoundedWithUnit(const MU &unit, int digits=-1, bool withGroupSeparator=false, bool i18n=false) const
Value to QString with the given unit, e.g. "5.00m".
bool isPositiveWithEpsilonConsidered() const
Value >= 0 epsilon considered.
double valueRounded(MU unit, int digits=-1) const
Rounded value in given unit.
const PQ & makeNegative()
Make value always negative.
bool isZeroEpsilonConsidered() const
Quantity value <= epsilon.
static PQ parse(const QString &value, SeparatorMode mode=SeparatorQtDefault)
Parse into concrete type.
Definition pqstring.h:58
SeparatorMode
Number separators / group separators.
Definition pqstring.h:34
@ SeparatorQtDefault
100000.00 no group separator
Definition pqstring.h:35
int compare(T a, T b)
Compare arithmetic values.
bool is09OrSeparatorOnlyString(const QString &testString)
String with 0-9/separator only.
size_t qHash(const std::string &key, uint seed)
std::string qHash
Definition metaclass.h:84
#define SWIFT_DEFINE_PQ_MIXINS(MU, PQ)
Explicit template definition of mixins for a CPhysicalQuantity subclass.
QJsonObject::iterator insert(QLatin1StringView key, const QJsonValue &value)
bool isUndefined() const const
QString toString() const const
QString number(double n, char format, int precision)
QVariant fromValue(T &&value)
double toDouble(bool *ok) const const
QString toString() const const
T value() const &const
#define SWIFT_VERIFY_X(COND, WHERE, WHAT)
A weaker kind of assert.
Definition verify.h:26