merged AI doc, some new pages
This commit is contained in:
@@ -1,9 +1,8 @@
|
||||
/*! \file picrc.h
|
||||
* \ingroup Math
|
||||
* \~\brief
|
||||
* \~english CRC checksum calculation
|
||||
* \~russian Вычисление CRC контрольной суммы
|
||||
*/
|
||||
//! \~\file picrc.h
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english CRC checksum calculation
|
||||
//! \~russian Вычисление CRC контрольной суммы
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
CRC checksum calculator
|
||||
@@ -28,13 +27,21 @@
|
||||
|
||||
#include "pistring.h"
|
||||
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english Fixed-width unsigned helper used by generic CRC implementations.
|
||||
//! \~russian Вспомогательный беззнаковый тип фиксированной ширины для обобщенных реализаций CRC.
|
||||
template<int L>
|
||||
class PIP_EXPORT uint_cl {
|
||||
public:
|
||||
//! \~english Constructs a zero-filled value.
|
||||
//! \~russian Создает значение, заполненное нулями.
|
||||
uint_cl() {
|
||||
for (int i = 0; i < L / 8; ++i)
|
||||
data_[i] = 0;
|
||||
}
|
||||
//! \~english Constructs a copy.
|
||||
//! \~russian Создает копию.
|
||||
uint_cl(const uint_cl<L> & v) {
|
||||
for (int i = 0; i < L / 8; ++i)
|
||||
data_[i] = v.data_[i];
|
||||
@@ -96,6 +103,8 @@ public:
|
||||
data_[i] = 0;
|
||||
}
|
||||
|
||||
//! \~english Returns \c true when at least one bit is set.
|
||||
//! \~russian Возвращает \c true, если установлен хотя бы один бит.
|
||||
operator bool() {
|
||||
for (int i = 0; i < L / 8; ++i)
|
||||
if (data_[i] > 0) return true;
|
||||
@@ -152,6 +161,8 @@ public:
|
||||
return t;
|
||||
}
|
||||
|
||||
//! \~english Adds two fixed-width values with carry propagation.
|
||||
//! \~russian Складывает два значения фиксированной ширины с переносом.
|
||||
uint_cl<L> operator+(const uint_cl<L> & v) {
|
||||
uint_cl<L> t;
|
||||
uint cv;
|
||||
@@ -165,6 +176,8 @@ public:
|
||||
return t;
|
||||
}
|
||||
|
||||
//! \~english Returns bitwise AND with another value.
|
||||
//! \~russian Возвращает побитовое И с другим значением.
|
||||
uint_cl<L> operator&(const uint_cl<L> & v) const {
|
||||
uint_cl<L> t;
|
||||
for (int i = 0; i < L / 8; ++i)
|
||||
@@ -182,6 +195,8 @@ public:
|
||||
uint_cl<L> operator&(const long & v) const { return *this & uint_cl<L>(v); }
|
||||
uint_cl<L> operator&(const llong & v) const { return *this & uint_cl<L>(v); }
|
||||
|
||||
//! \~english Returns bitwise OR with another value.
|
||||
//! \~russian Возвращает побитовое ИЛИ с другим значением.
|
||||
uint_cl<L> operator|(const uint_cl<L> & v) const {
|
||||
uint_cl<L> t;
|
||||
for (int i = 0; i < L / 8; ++i)
|
||||
@@ -199,6 +214,8 @@ public:
|
||||
uint_cl<L> operator|(const long & v) const { return *this | uint_cl<L>(v); }
|
||||
uint_cl<L> operator|(const llong & v) const { return *this | uint_cl<L>(v); }
|
||||
|
||||
//! \~english Returns bitwise XOR with another value.
|
||||
//! \~russian Возвращает побитовое исключающее ИЛИ с другим значением.
|
||||
uint_cl<L> operator^(const uint_cl<L> & v) const {
|
||||
uint_cl<L> t;
|
||||
for (int i = 0; i < L / 8; ++i)
|
||||
@@ -216,6 +233,8 @@ public:
|
||||
uint_cl<L> operator^(const long & v) const { return *this ^ uint_cl<L>(v); }
|
||||
uint_cl<L> operator^(const llong & v) const { return *this ^ uint_cl<L>(v); }
|
||||
|
||||
//! \~english Less than operator
|
||||
//! \~russian Оператор меньше
|
||||
bool operator<(const uint_cl<L> & v) const {
|
||||
for (int i = 0; i < L / 8; ++i) {
|
||||
if (v.data_[i] > data_[i]) return true;
|
||||
@@ -223,6 +242,9 @@ public:
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
//! \~english Less than or equal operator
|
||||
//! \~russian Оператор меньше или равно
|
||||
bool operator<=(const uint_cl<L> & v) const {
|
||||
for (int i = 0; i < L / 8; ++i) {
|
||||
if (v.data_[i] > data_[i]) return true;
|
||||
@@ -230,6 +252,9 @@ public:
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
//! \~english Greater than operator
|
||||
//! \~russian Оператор больше
|
||||
bool operator>(const uint_cl<L> & v) const {
|
||||
for (int i = 0; i < L / 8; ++i) {
|
||||
if (v.data_[i] < data_[i]) return true;
|
||||
@@ -237,6 +262,9 @@ public:
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
//! \~english Greater than or equal operator
|
||||
//! \~russian Оператор больше или равно
|
||||
bool operator>=(const uint_cl<L> & v) const {
|
||||
for (int i = 0; i < L / 8; ++i) {
|
||||
if (v.data_[i] < data_[i]) return true;
|
||||
@@ -244,18 +272,29 @@ public:
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
//! \~english Equality operator
|
||||
//! \~russian Оператор равенства
|
||||
bool operator==(const uint_cl<L> & v) const {
|
||||
for (int i = 0; i < L / 8; ++i)
|
||||
if (v.data_[i] != data_[i]) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
//! \~english Inequality operator
|
||||
//! \~russian Оператор неравенства
|
||||
bool operator!=(const uint_cl<L> & v) const {
|
||||
for (int i = 0; i < L / 8; ++i)
|
||||
if (v.data_[i] != data_[i]) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
//! \~english Less than or equal operator (specialized for 8-bit)
|
||||
//! \~russian Оператор меньше или равно (специализация для 8 бит)
|
||||
bool operator<=(const uint_cl<8> & v1) { return (*(uchar *)data()) <= (*(uchar *)v1.data()); }
|
||||
|
||||
//! \~english Returns a value shifted right by the specified bit count.
|
||||
//! \~russian Возвращает значение, сдвинутое вправо на указанное число битов.
|
||||
uint_cl<L> operator>>(const int & c) const {
|
||||
uint_cl<L> t;
|
||||
int l = L - c;
|
||||
@@ -271,6 +310,8 @@ public:
|
||||
return t;
|
||||
}
|
||||
uint_cl<L> operator>>(const uint & c) const { return (*this << (int)c); }
|
||||
//! \~english Returns a value shifted left by the specified bit count.
|
||||
//! \~russian Возвращает значение, сдвинутое влево на указанное число битов.
|
||||
uint_cl<L> operator<<(const int & c) const {
|
||||
uint_cl<L> t;
|
||||
int l = L - c;
|
||||
@@ -287,17 +328,23 @@ public:
|
||||
}
|
||||
uint_cl<L> operator<<(const uint & c) const { return (*this >> (int)c); }
|
||||
|
||||
//! \~english Inverts all bits in place.
|
||||
//! \~russian Инвертирует все биты на месте.
|
||||
uint_cl<L> & inverse() const {
|
||||
for (int i = 0; i < L / 8; ++i)
|
||||
data_[i] = ~data_[i];
|
||||
return *this;
|
||||
}
|
||||
//! \~english Returns a copy with all bits inverted.
|
||||
//! \~russian Возвращает копию с инвертированными битами.
|
||||
uint_cl<L> inversed() const {
|
||||
uint_cl<L> t(*this);
|
||||
for (int i = 0; i < L / 8; ++i)
|
||||
t.data_[i] = ~t.data_[i];
|
||||
return t;
|
||||
}
|
||||
//! \~english Returns a copy with bit order reversed.
|
||||
//! \~russian Возвращает копию с обратным порядком битов.
|
||||
uint_cl<L> reversed() const {
|
||||
uint_cl<L> t;
|
||||
bool bit;
|
||||
@@ -311,8 +358,14 @@ public:
|
||||
return t;
|
||||
}
|
||||
|
||||
//! \~english Returns raw byte storage.
|
||||
//! \~russian Возвращает сырое байтовое представление.
|
||||
const uchar * data() const { return data_; }
|
||||
//! \~english Returns raw byte storage.
|
||||
//! \~russian Возвращает сырое байтовое представление.
|
||||
uchar * data() { return data_; }
|
||||
//! \~english Returns storage length in bytes.
|
||||
//! \~russian Возвращает длину хранения в байтах.
|
||||
uint length() const { return L / 8; }
|
||||
|
||||
private:
|
||||
@@ -320,6 +373,8 @@ private:
|
||||
};
|
||||
|
||||
|
||||
//! \~english Returns a byte with reversed bit order.
|
||||
//! \~russian Возвращает байт с обратным порядком битов.
|
||||
inline uchar reverseByte(uchar b) {
|
||||
uchar ret = 0;
|
||||
bool bit;
|
||||
@@ -330,9 +385,15 @@ inline uchar reverseByte(uchar b) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english Generic table-driven CRC calculator for a polynomial width \a L.
|
||||
//! \~russian Универсальный табличный калькулятор CRC для полинома ширины \a L.
|
||||
template<uint L, typename N = uint_cl<L>>
|
||||
class PIP_EXPORT PICRC {
|
||||
public:
|
||||
//! \~english Constructs a calculator with the specified polynomial and default CRC conventions.
|
||||
//! \~russian Создает калькулятор с указанным полиномом и стандартными настройками CRC.
|
||||
PICRC(const N & poly = N()) {
|
||||
poly_ = poly;
|
||||
reverse_poly = true;
|
||||
@@ -341,6 +402,9 @@ public:
|
||||
reverse_before_xor = reverse_data = false;
|
||||
initTable();
|
||||
}
|
||||
|
||||
//! \~english Constructs a calculator with fully specified initialization parameters.
|
||||
//! \~russian Создает калькулятор с полностью заданными параметрами инициализации.
|
||||
PICRC(const N & poly, bool reverse_poly_, const N & initial, const N & out_xor) {
|
||||
poly_ = poly;
|
||||
reverse_poly = reverse_poly_;
|
||||
@@ -350,15 +414,33 @@ public:
|
||||
initTable();
|
||||
}
|
||||
|
||||
|
||||
//! \~english Sets the initial CRC value.
|
||||
//! \~russian Устанавливает начальное значение CRC.
|
||||
void setInitial(const N & v) { init_ = v; }
|
||||
|
||||
//! \~english Sets the final XOR value.
|
||||
//! \~russian Устанавливает финальное значение XOR.
|
||||
void setOutXor(const N & v) { out_ = v; }
|
||||
|
||||
//! \~english Enables or disables polynomial bit reversal and rebuilds the lookup table.
|
||||
//! \~russian Включает или отключает реверс полинома и перестраивает таблицу поиска.
|
||||
void setReversePolynome(bool yes) {
|
||||
reverse_poly = yes;
|
||||
initTable();
|
||||
}
|
||||
|
||||
//! \~english Reverses the resulting CRC before applying the output XOR.
|
||||
//! \~russian Разворачивает итоговый CRC перед применением выходного XOR.
|
||||
void setReverseOutBeforeXOR(bool yes) { reverse_before_xor = yes; }
|
||||
|
||||
//! \~english Reverses bits in each input byte before processing.
|
||||
//! \~russian Разворачивает биты в каждом входном байте перед обработкой.
|
||||
void setReverseDataBytes(bool yes) { reverse_data = yes; }
|
||||
|
||||
|
||||
//! \~english Rebuilds the 256-entry lookup table for the current polynomial settings.
|
||||
//! \~russian Перестраивает таблицу из 256 элементов для текущих настроек полинома.
|
||||
void initTable() {
|
||||
N tmp, pol = reverse_poly ? reversed(poly_) : poly_;
|
||||
// cout << std::hex << "poly " << (uint)N(poly_) << " -> " << (uint)N(pol) << endl;
|
||||
@@ -370,6 +452,9 @@ public:
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
//! \~english Calculates CRC for a raw memory block.
|
||||
//! \~russian Вычисляет CRC для блока памяти.
|
||||
N calculate(const void * data, int size) {
|
||||
N crc = init_;
|
||||
uchar *data_ = (uchar *)data, cb;
|
||||
@@ -385,7 +470,13 @@ public:
|
||||
if (reverse_before_xor) crc = reversed(crc);
|
||||
return crc ^ out_;
|
||||
}
|
||||
|
||||
//! \~english Calculates CRC for a byte array.
|
||||
//! \~russian Вычисляет CRC для массива байтов.
|
||||
N calculate(const PIByteArray & d) { return calculate(d.data(), d.size()); }
|
||||
|
||||
//! \~english Calculates CRC for a null-terminated string.
|
||||
//! \~russian Вычисляет CRC для нуль-терминированной строки.
|
||||
N calculate(const char * str) {
|
||||
PIByteArray s(PIString(str).toByteArray());
|
||||
return calculate(s.data(), s.size_s());
|
||||
@@ -425,20 +516,43 @@ inline uint PICRC<32, uint>::inversed(const uint & v) {
|
||||
return ~v;
|
||||
}
|
||||
|
||||
//! \~english CRC-32 calculator type.
|
||||
//! \~russian Тип калькулятора CRC-32.
|
||||
typedef PICRC<32, uint> CRC_32;
|
||||
|
||||
//! \~english CRC-24 calculator type.
|
||||
//! \~russian Тип калькулятора CRC-24.
|
||||
typedef PICRC<24> CRC_24;
|
||||
|
||||
//! \~english CRC-16 calculator type.
|
||||
//! \~russian Тип калькулятора CRC-16.
|
||||
typedef PICRC<16, ushort> CRC_16;
|
||||
|
||||
//! \~english CRC-8 calculator type.
|
||||
//! \~russian Тип калькулятора CRC-8.
|
||||
typedef PICRC<8, uchar> CRC_8;
|
||||
|
||||
|
||||
//! \~english Create standard CRC-32 calculator
|
||||
//! \~russian Создать стандартный калькулятор CRC-32
|
||||
inline CRC_32 standardCRC_32() {
|
||||
return CRC_32(0x04C11DB7, true, 0xFFFFFFFF, 0xFFFFFFFF);
|
||||
}
|
||||
|
||||
//! \~english Create standard CRC-16 calculator
|
||||
//! \~russian Создать стандартный калькулятор CRC-16
|
||||
inline CRC_16 standardCRC_16() {
|
||||
return CRC_16(0x8005, true, 0x0, 0x0);
|
||||
}
|
||||
|
||||
//! \~english Create standard CRC-16 Modbus calculator
|
||||
//! \~russian Создать стандартный калькулятор CRC-16 Modbus
|
||||
inline CRC_16 standardCRC_16_Modbus() {
|
||||
return CRC_16(0x8005, 0xFFFF, 0xFFFF, false);
|
||||
}
|
||||
|
||||
//! \~english Create standard CRC-8 calculator
|
||||
//! \~russian Создать стандартный калькулятор CRC-8
|
||||
inline CRC_8 standardCRC_8() {
|
||||
return CRC_8(0xD5, true, 0x0, 0x0);
|
||||
}
|
||||
|
||||
@@ -1,9 +1,16 @@
|
||||
/*! \file pievaluator.h
|
||||
* \ingroup Math
|
||||
* \~\brief
|
||||
* \~english Mathematic expressions calculator
|
||||
* \~russian Вычислитель математических выражений
|
||||
*/
|
||||
//! \~\file pievaluator.h
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english Mathematical expression evaluator
|
||||
//! \~russian Вычислитель математических выражений
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! Declares evaluator types, expression storage, and the evaluator that
|
||||
//! prepares an expression once and then reuses compiled instructions.
|
||||
//! \~russian
|
||||
//! Объявляет типы вычислителя, контейнер выражения и вычислитель,
|
||||
//! который один раз подготавливает выражение и затем повторно использует
|
||||
//! скомпилированные инструкции.
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Evaluator designed for stream calculations
|
||||
@@ -40,6 +47,7 @@ enum eType {
|
||||
etVariable,
|
||||
etFunction
|
||||
};
|
||||
|
||||
enum Operation {
|
||||
oNone,
|
||||
oAdd,
|
||||
@@ -58,6 +66,7 @@ enum Operation {
|
||||
oOr,
|
||||
oFunction
|
||||
};
|
||||
|
||||
enum BaseFunctions {
|
||||
bfUnknown,
|
||||
bfSin,
|
||||
@@ -112,66 +121,84 @@ struct PIP_EXPORT Instruction {
|
||||
function = -1;
|
||||
operation = oNone;
|
||||
}
|
||||
|
||||
Instruction(Operation oper, PIVector<short> opers, short out_ind, short func = -1) {
|
||||
operation = oper;
|
||||
operators = opers;
|
||||
out = out_ind;
|
||||
function = func;
|
||||
}
|
||||
|
||||
Operation operation;
|
||||
short out;
|
||||
short function;
|
||||
PIVector<short> operators;
|
||||
};
|
||||
|
||||
|
||||
struct PIP_EXPORT Element {
|
||||
Element() {
|
||||
num = 0;
|
||||
var_num = -1;
|
||||
type = etNumber;
|
||||
}
|
||||
|
||||
Element(eType new_type, short new_num, short new_var_num = -1) { set(new_type, new_num, new_var_num); }
|
||||
|
||||
void set(eType new_type, short new_num, short new_var_num = -1) {
|
||||
type = new_type;
|
||||
num = new_num;
|
||||
var_num = new_var_num;
|
||||
}
|
||||
|
||||
eType type;
|
||||
short num;
|
||||
short var_num;
|
||||
};
|
||||
|
||||
|
||||
struct PIP_EXPORT Function {
|
||||
Function() {
|
||||
arguments = 0;
|
||||
type = bfUnknown;
|
||||
handler = nullptr;
|
||||
}
|
||||
|
||||
Function(const PIString & name, short args, BaseFunctions ftype) {
|
||||
identifier = name;
|
||||
arguments = args;
|
||||
type = ftype;
|
||||
handler = nullptr;
|
||||
}
|
||||
|
||||
Function(const PIString & name, short args, FuncHanlder h) {
|
||||
identifier = name;
|
||||
arguments = args;
|
||||
type = bfCustom;
|
||||
handler = h;
|
||||
}
|
||||
|
||||
PIString identifier;
|
||||
BaseFunctions type;
|
||||
FuncHanlder handler;
|
||||
short arguments;
|
||||
};
|
||||
|
||||
|
||||
struct PIP_EXPORT Variable {
|
||||
Variable() { value = 0.; }
|
||||
|
||||
Variable(const PIString & var_name, complexd val) {
|
||||
name = var_name;
|
||||
value = val;
|
||||
}
|
||||
|
||||
PIString name;
|
||||
complexd value;
|
||||
};
|
||||
|
||||
} // namespace PIEvaluatorTypes
|
||||
|
||||
/*
|
||||
≠ :
|
||||
≥ }
|
||||
@@ -179,7 +206,6 @@ struct PIP_EXPORT Variable {
|
||||
⋀ &
|
||||
⋁ |
|
||||
*/
|
||||
|
||||
class PIP_EXPORT PIEvaluatorContent {
|
||||
friend class PIEvaluator;
|
||||
BINARY_STREAM_FRIEND(PIEvaluatorContent);
|
||||
@@ -209,7 +235,6 @@ public:
|
||||
bool setVariableName(const PIString & var_name, const PIString & new_name) { return setVariableName(findVariable(var_name), new_name); }
|
||||
void clearCustomVariables();
|
||||
PIEvaluatorTypes::BaseFunctions getBaseFunction(const PIString & name);
|
||||
|
||||
void dump();
|
||||
|
||||
private:
|
||||
@@ -219,64 +244,97 @@ private:
|
||||
};
|
||||
|
||||
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english Expression evaluator with reusable compiled instructions.
|
||||
//! \~russian Вычислитель выражений с повторно используемыми скомпилированными инструкциями.
|
||||
//!
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! The evaluator prepares an expression with \a check(), keeps the processed
|
||||
//! form and instruction list, and then reevaluates it after variable updates.
|
||||
//! Built-in constants include \c i, \c pi, and \c e.
|
||||
//! \~russian
|
||||
//! Вычислитель подготавливает выражение через \a check(), сохраняет
|
||||
//! обработанную форму и список инструкций, а затем повторно вычисляет его
|
||||
//! после обновления переменных. Встроенные константы: \c i, \c pi и \c e.
|
||||
class PIP_EXPORT PIEvaluator {
|
||||
public:
|
||||
//! Constructs an empty evaluator
|
||||
//! \~english Constructs an empty evaluator.
|
||||
//! \~russian Создает пустой вычислитель.
|
||||
PIEvaluator() {
|
||||
correct = false;
|
||||
data_ = 0;
|
||||
}
|
||||
|
||||
//! \~english Destroys the evaluator.
|
||||
//! \~russian Уничтожает вычислитель.
|
||||
~PIEvaluator() { ; }
|
||||
|
||||
|
||||
//! Returns custom data
|
||||
//! \~english Returns custom user data passed to callback functions.
|
||||
//! \~russian Возвращает пользовательские данные, передаваемые в callback-функции.
|
||||
void * data() { return data_; }
|
||||
|
||||
//! Set custom data to "_data"
|
||||
//! \~english Sets custom user data for callback functions.
|
||||
//! \~russian Устанавливает пользовательские данные для callback-функций.
|
||||
void setData(void * _data) { data_ = _data; }
|
||||
|
||||
|
||||
//! Check mathematical expression and parse it to list of instructions
|
||||
//! \~english Checks and compiles an expression.
|
||||
//! \~russian Проверяет и компилирует выражение.
|
||||
bool check(const PIString & string);
|
||||
|
||||
//! Returns true if expression was checked succesfully
|
||||
//! \~english Returns true if the last \a check() succeeded.
|
||||
//! \~russian Возвращает true, если последний вызов \a check() завершился успешно.
|
||||
bool isCorrect() const { return correct; }
|
||||
|
||||
//! Set variable value with name "name" to value "value". Add variable if it doesn`t exists
|
||||
//! \~english Sets a named variable and creates it if needed.
|
||||
//! \~russian Устанавливает именованную переменную и создает ее при необходимости.
|
||||
int setVariable(const PIString & name, complexd value = complexd(0.));
|
||||
|
||||
//! Set variable value with index "index" to value "value". Don`t add variable if it doesn`t exists
|
||||
//! \~english Sets a variable by index.
|
||||
//! \~russian Устанавливает переменную по индексу.
|
||||
void setVariable(int index, complexd value = 0.);
|
||||
|
||||
//! Evaluate last successfully checked with function \a check() expression and returns result
|
||||
//! \~english Evaluates the last successfully compiled expression.
|
||||
//! \~russian Вычисляет последнее успешно скомпилированное выражение.
|
||||
complexd evaluate();
|
||||
|
||||
//! Remove all manually added variables
|
||||
//! \~english Removes user-added variables and keeps built-in constants.
|
||||
//! \~russian Удаляет добавленные пользователем переменные и сохраняет встроенные константы.
|
||||
void clearCustomVariables() { content.clearCustomVariables(); }
|
||||
|
||||
//! Returns index of variable with name "name"
|
||||
//! \~english Returns variable index by name, or -1.
|
||||
//! \~russian Возвращает индекс переменной по имени или -1.
|
||||
int variableIndex(const PIString & name) const { return content.findVariable(name); }
|
||||
|
||||
//! Returns all unknown variables founded in last expression passed to \a check() function
|
||||
//! \~english Returns unknown variables found during the last \a check().
|
||||
//! \~russian Возвращает неизвестные переменные, найденные при последнем \a check().
|
||||
const PIStringList & unknownVariables() const { return unknownVars; }
|
||||
|
||||
//! Returns all used variables founded in last expression passed to \a check() function
|
||||
//! \~english Returns variables used in the last checked expression.
|
||||
//! \~russian Возвращает переменные, использованные в последнем проверенном выражении.
|
||||
const PIStringList & usedVariables() const { return usedVars; }
|
||||
|
||||
//! Returns processed last expression passed to \a check() function
|
||||
//! \~english Returns the normalized form of the last checked expression.
|
||||
//! \~russian Возвращает нормализованную форму последнего проверенного выражения.
|
||||
const PIString & expression() const { return currentString; }
|
||||
|
||||
//! Returns last error description occured in \a check() function
|
||||
//! \~english Returns the last status or error text from \a check().
|
||||
//! \~russian Возвращает последний статус или текст ошибки из \a check().
|
||||
const PIString & error() const { return lastError; }
|
||||
|
||||
//! Returns last result of \a evaluate()
|
||||
//! \~english Returns the last evaluation result.
|
||||
//! \~russian Возвращает последний результат вычисления.
|
||||
const complexd & lastResult() const { return out; }
|
||||
|
||||
//! Save to %PIByteArray evaluator state (expression, variables, errors, compiled instructions)
|
||||
//! \~english Serializes evaluator state.
|
||||
//! \~russian Сериализует состояние вычислителя.
|
||||
PIByteArray save() const;
|
||||
|
||||
//! Restore from %PIByteArray evaluator state (expression, variables, errors, compiled instructions)
|
||||
//! \~english Restores evaluator state from serialized data.
|
||||
//! \~russian Восстанавливает состояние вычислителя из сериализованных данных.
|
||||
void load(PIByteArray ba);
|
||||
|
||||
private:
|
||||
|
||||
@@ -1,10 +1,9 @@
|
||||
/*! \file pifft.h
|
||||
* \ingroup Math
|
||||
* \ingroup FFTW
|
||||
* \~\brief
|
||||
* \~english FFT, IFFT and Hilbert transformations
|
||||
* \~russian БПФ, ОБПФ и преобразования Гильберта
|
||||
*/
|
||||
//! \~\file pifft.h
|
||||
//! \~\ingroup Math
|
||||
//! \~\ingroup FFTW
|
||||
//! \~\brief
|
||||
//! \~english FFT, IFFT and Hilbert transformations
|
||||
//! \~russian БПФ, ОБПФ и преобразования Гильберта
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Class for FFT, IFFT and Hilbert transformations
|
||||
@@ -64,16 +63,37 @@
|
||||
|
||||
# include "pip_fftw_export.h"
|
||||
|
||||
//! \~\ingroup Math
|
||||
//! \~\ingroup FFTW
|
||||
//! \~\brief
|
||||
//! \~english Double-precision FFT helper that stores the last transform result.
|
||||
//! \~russian Вспомогательный класс БПФ двойной точности, сохраняющий результат последнего преобразования.
|
||||
class PIP_EXPORT PIFFT_double {
|
||||
public:
|
||||
//! \~english Constructs an empty transformer.
|
||||
//! \~russian Создает пустой объект преобразования.
|
||||
PIFFT_double();
|
||||
|
||||
//! \~english Calculates complex FFT for the input signal.
|
||||
//! \~russian Вычисляет комплексное БПФ для входного сигнала.
|
||||
PIVector<complexd> * calcFFT(const PIVector<complexd> & val);
|
||||
//! \~english Calculates FFT for a real-valued input signal.
|
||||
//! \~russian Вычисляет БПФ для вещественного входного сигнала.
|
||||
PIVector<complexd> * calcFFT(const PIVector<double> & val);
|
||||
//! \~english Calculates inverse FFT for a complex spectrum.
|
||||
//! \~russian Вычисляет обратное БПФ для комплексного спектра.
|
||||
PIVector<complexd> * calcFFTinverse(const PIVector<complexd> & val);
|
||||
//! \~english Calculates the analytic signal using a Hilbert transform.
|
||||
//! \~russian Вычисляет аналитический сигнал с помощью преобразования Гильберта.
|
||||
PIVector<complexd> * calcHilbert(const PIVector<double> & val);
|
||||
//! \~english Returns magnitudes of the last calculated result.
|
||||
//! \~russian Возвращает модули последнего вычисленного результата.
|
||||
PIVector<double> getAmplitude() const;
|
||||
//! \~english Returns real parts of the last calculated result.
|
||||
//! \~russian Возвращает действительные части последнего вычисленного результата.
|
||||
PIVector<double> getReal() const;
|
||||
//! \~english Returns imaginary parts of the last calculated result.
|
||||
//! \~russian Возвращает мнимые части последнего вычисленного результата.
|
||||
PIVector<double> getImag() const;
|
||||
|
||||
private:
|
||||
@@ -118,16 +138,37 @@ private:
|
||||
void ftbase_ffttwcalc(PIVector<double> * a, int aoffset, int n1, int n2);
|
||||
};
|
||||
|
||||
//! \~\ingroup Math
|
||||
//! \~\ingroup FFTW
|
||||
//! \~\brief
|
||||
//! \~english Single-precision FFT helper that stores the last transform result.
|
||||
//! \~russian Вспомогательный класс БПФ одинарной точности, сохраняющий результат последнего преобразования.
|
||||
class PIP_EXPORT PIFFT_float {
|
||||
public:
|
||||
//! \~english Constructs an empty transformer.
|
||||
//! \~russian Создает пустой объект преобразования.
|
||||
PIFFT_float();
|
||||
|
||||
//! \~english Calculates complex FFT for the input signal.
|
||||
//! \~russian Вычисляет комплексное БПФ для входного сигнала.
|
||||
PIVector<complexf> * calcFFT(const PIVector<complexf> & val);
|
||||
//! \~english Calculates FFT for a real-valued input signal.
|
||||
//! \~russian Вычисляет БПФ для вещественного входного сигнала.
|
||||
PIVector<complexf> * calcFFT(const PIVector<float> & val);
|
||||
//! \~english Calculates inverse FFT for a complex spectrum.
|
||||
//! \~russian Вычисляет обратное БПФ для комплексного спектра.
|
||||
PIVector<complexf> * calcFFTinverse(const PIVector<complexf> & val);
|
||||
//! \~english Calculates the analytic signal using a Hilbert transform.
|
||||
//! \~russian Вычисляет аналитический сигнал с помощью преобразования Гильберта.
|
||||
PIVector<complexf> * calcHilbert(const PIVector<float> & val);
|
||||
//! \~english Returns magnitudes of the last calculated result.
|
||||
//! \~russian Возвращает модули последнего вычисленного результата.
|
||||
PIVector<float> getAmplitude() const;
|
||||
//! \~english Returns real parts of the last calculated result.
|
||||
//! \~russian Возвращает действительные части последнего вычисленного результата.
|
||||
PIVector<float> getReal() const;
|
||||
//! \~english Returns imaginary parts of the last calculated result.
|
||||
//! \~russian Возвращает мнимые части последнего вычисленного результата.
|
||||
PIVector<float> getImag() const;
|
||||
|
||||
private:
|
||||
@@ -172,8 +213,14 @@ private:
|
||||
void ftbase_ffttwcalc(PIVector<float> * a, int aoffset, int n1, int n2);
|
||||
};
|
||||
|
||||
//! \~english Default FFT helper alias based on double precision.
|
||||
//! \~russian Псевдоним стандартного FFT-помощника на базе двойной точности.
|
||||
typedef PIFFT_double PIFFT;
|
||||
//! \~english Double-precision FFT helper alias.
|
||||
//! \~russian Псевдоним FFT-помощника двойной точности.
|
||||
typedef PIFFT_double PIFFTd;
|
||||
//! \~english Single-precision FFT helper alias.
|
||||
//! \~russian Псевдоним FFT-помощника одинарной точности.
|
||||
typedef PIFFT_float PIFFTf;
|
||||
|
||||
# ifndef CC_VC
|
||||
@@ -193,25 +240,44 @@ _PIFFTW_H(float)
|
||||
_PIFFTW_H(double)
|
||||
_PIFFTW_H(ldouble)
|
||||
|
||||
//! \~\ingroup Math
|
||||
//! \~\ingroup FFTW
|
||||
//! \~\brief
|
||||
//! \~english Thin wrapper over libfftw3 plans for a selected scalar type.
|
||||
//! \~russian Тонкая обертка над планами libfftw3 для выбранного скалярного типа.
|
||||
template<typename T>
|
||||
class PIFFTW {
|
||||
public:
|
||||
//! \~english Constructs the backend object for the selected precision.
|
||||
//! \~russian Создает внутренний объект для выбранной точности.
|
||||
explicit PIFFTW() {
|
||||
p = 0;
|
||||
newP(p);
|
||||
}
|
||||
//! \~english Destroys the backend object and its cached plans.
|
||||
//! \~russian Уничтожает внутренний объект и его кэшированные планы.
|
||||
~PIFFTW() { deleteP(p); }
|
||||
|
||||
//! \~english Calculates complex FFT for the input signal.
|
||||
//! \~russian Вычисляет комплексное БПФ для входного сигнала.
|
||||
inline const PIVector<complex<T>> & calcFFT(const PIVector<complex<T>> & in) { return PIVector<complex<T>>().resize(in.size()); }
|
||||
//! \~english Calculates FFT for a real-valued input signal.
|
||||
//! \~russian Вычисляет БПФ для вещественного входного сигнала.
|
||||
inline const PIVector<complex<T>> & calcFFT(const PIVector<T> & in) { return PIVector<complex<T>>().resize(in.size()); }
|
||||
//! \~english Calculates inverse FFT for a complex spectrum.
|
||||
//! \~russian Вычисляет обратное БПФ для комплексного спектра.
|
||||
inline const PIVector<complex<T>> & calcFFTinverse(const PIVector<complex<T>> & in) { return PIVector<complex<T>>().resize(in.size()); }
|
||||
|
||||
//! \~english Operation kind for precomputed FFTW plans.
|
||||
//! \~russian Тип операции для заранее подготовленных планов FFTW.
|
||||
enum FFT_Operation {
|
||||
foReal,
|
||||
foComplex,
|
||||
foInverse
|
||||
foReal /** \~english Forward transform for real input \~russian Прямое преобразование для вещественного входа */,
|
||||
foComplex /** \~english Forward transform for complex input \~russian Прямое преобразование для комплексного входа */,
|
||||
foInverse /** \~english Inverse complex transform \~russian Обратное комплексное преобразование */
|
||||
};
|
||||
|
||||
//! \~english Prepares and caches a plan for the specified signal size and operation.
|
||||
//! \~russian Подготавливает и кэширует план для указанного размера сигнала и операции.
|
||||
inline void preparePlan(int size, FFT_Operation op) {}
|
||||
|
||||
private:
|
||||
@@ -250,6 +316,8 @@ inline void PIFFTW<float>::deleteP(void *& _p) {
|
||||
_p = 0;
|
||||
}
|
||||
|
||||
//! \~english Single-precision FFTW wrapper.
|
||||
//! \~russian Обертка FFTW одинарной точности.
|
||||
typedef PIFFTW<float> PIFFTWf;
|
||||
|
||||
|
||||
@@ -279,6 +347,8 @@ inline void PIFFTW<double>::deleteP(void *& _p) {
|
||||
_p = 0;
|
||||
}
|
||||
|
||||
//! \~english Double-precision FFTW wrapper.
|
||||
//! \~russian Обертка FFTW двойной точности.
|
||||
typedef PIFFTW<double> PIFFTWd;
|
||||
|
||||
|
||||
@@ -308,6 +378,8 @@ inline void PIFFTW<ldouble>::deleteP(void *& _p) {
|
||||
_p = 0;
|
||||
}
|
||||
|
||||
//! \~english Extended-precision FFTW wrapper.
|
||||
//! \~russian Обертка FFTW расширенной точности.
|
||||
typedef PIFFTW<ldouble> PIFFTWld;
|
||||
|
||||
# endif
|
||||
|
||||
@@ -1,21 +1,12 @@
|
||||
/*! \file pigeometry.h
|
||||
* \ingroup Math
|
||||
* \brief
|
||||
* \~english Geometry base classes
|
||||
* \~russian Базовые геометрические классы
|
||||
* \~\details
|
||||
* \~english
|
||||
* Add \a PIPoint, \a PILine and \a PIRect classes.
|
||||
* \~russian
|
||||
* Содержит классы: \a PIPoint, \a PILine и \a PIRect.
|
||||
* * \~\authors
|
||||
* \~english
|
||||
* Ivan Pelipenko peri4ko@yandex.ru;
|
||||
* Andrey Bychkov work.a.b@yandex.ru;
|
||||
* \~russian
|
||||
* Иван Пелипенко peri4ko@yandex.ru;
|
||||
* Андрей Бычков work.a.b@yandex.ru;
|
||||
*/
|
||||
//! \~\file pigeometry.h
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english Convenience header for basic geometry types
|
||||
//! \~russian Заголовок-агрегатор для базовых геометрических типов
|
||||
//!
|
||||
//! \~\details
|
||||
//! \~english Includes \a PIPoint, \a PILine and \a PIRect.
|
||||
//! \~russian Подключает \a PIPoint, \a PILine и \a PIRect.
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Geometry base classes
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file piline.h
|
||||
* \ingroup Math
|
||||
* \brief
|
||||
* \~english Two-dimensional line class
|
||||
* \~russian Класс отрезка двумерной линии
|
||||
*/
|
||||
//! \~\file piline.h
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english Two-dimensional line segment type
|
||||
//! \~russian Тип двумерного отрезка
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Two-dimensional line class
|
||||
@@ -28,155 +27,164 @@
|
||||
#include "pipoint.h"
|
||||
|
||||
|
||||
/*! \brief
|
||||
* \~english Two-dimensional line class
|
||||
* \~russian Класс отрезка двумерной линии
|
||||
* \~\details
|
||||
* \~russian
|
||||
* Этот класс описывает линию на плоскости в прямоугольной системе координат
|
||||
*/
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english Two-dimensional line segment.
|
||||
//! \~russian Двумерный отрезок.
|
||||
//! \~\details
|
||||
//! \~english Stores start and end points of a segment on a plane.
|
||||
//! \~russian Хранит начальную и конечную точки отрезка на плоскости.
|
||||
template<typename Type>
|
||||
class PIP_EXPORT PILine {
|
||||
static_assert(std::is_arithmetic<Type>::value, "Type must be arithmetic");
|
||||
|
||||
public:
|
||||
//! \~english Segment start point.
|
||||
//! \~russian Начальная точка отрезка.
|
||||
PIPoint<Type> p0;
|
||||
|
||||
//! \~english Segment end point.
|
||||
//! \~russian Конечная точка отрезка.
|
||||
PIPoint<Type> p1;
|
||||
|
||||
//! \~russian
|
||||
//! Пустой конструктор.
|
||||
//! \details
|
||||
//! При выполнении пустого конструктора координаты не изменяются.
|
||||
//! Начало и конец совпадают.
|
||||
//! \~english Constructs empty segment.
|
||||
//! \~russian Создает пустой отрезок.
|
||||
PILine() {}
|
||||
|
||||
//! \~russian
|
||||
//! Создает линию по двум принятым точкам \a PIPoint начала и конца.
|
||||
//! \~english Constructs segment from two points.
|
||||
//! \~russian Создает отрезок по двум точкам.
|
||||
PILine(const PIPoint<Type> & p0_, const PIPoint<Type> & p1_) {
|
||||
p0 = p0_;
|
||||
p1 = p1_;
|
||||
}
|
||||
|
||||
//! \~russian
|
||||
//! Создает линию по принятым координатам начала и конца.
|
||||
//! \~english Constructs segment from endpoint coordinates.
|
||||
//! \~russian Создает отрезок по координатам концов.
|
||||
PILine(Type x0, Type y0, Type x1, Type y1) {
|
||||
p0.set(x0, y0);
|
||||
p1.set(x1, y1);
|
||||
}
|
||||
|
||||
//! \~russian
|
||||
//! Задать новые координаты начала и конца по двум принятым точкам \a PIPoint.
|
||||
//! \~english Sets segment endpoints from two points.
|
||||
//! \~russian Задает концы отрезка по двум точкам.
|
||||
PILine<Type> & set(const PIPoint<Type> & p0_, const PIPoint<Type> & p1_) {
|
||||
p0 = p0_;
|
||||
p1 = p1_;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~russian
|
||||
//! Задать новые координаты начала и конца.
|
||||
//! \~english Sets segment endpoints from coordinates.
|
||||
//! \~russian Задает концы отрезка по координатам.
|
||||
PILine<Type> & set(Type x0, Type y0, Type x1, Type y1) {
|
||||
p0.set(x0, y0);
|
||||
p1.set(x1, y1);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~russian
|
||||
//! Проверить на совпадение координат начала и конца.
|
||||
//! \~english Returns `true` if segment endpoints are equal.
|
||||
//! \~russian Возвращает `true`, если концы отрезка совпадают.
|
||||
bool isEmpty() const { return (p0 == p1); }
|
||||
|
||||
//! \~russian
|
||||
//! Вычислить ширину прямоугольника, диагональю которого является данный отрезок.
|
||||
//! \~english Returns horizontal span between endpoints.
|
||||
//! \~russian Возвращает горизонтальный размах между концами.
|
||||
Type width() const { return piAbs<Type>(p1.x - p0.x); }
|
||||
|
||||
//! \~russian
|
||||
//! Вычислить высоту прямоугольника, диагональю которого является данный отрезок.
|
||||
//! \~english Returns vertical span between endpoints.
|
||||
//! \~russian Возвращает вертикальный размах между концами.
|
||||
Type height() const { return piAbs<Type>(p1.y - p0.y); }
|
||||
|
||||
//! \~russian
|
||||
//! Сдвинуть линию на \a x, \a y.
|
||||
//! \~english Shifts the segment by `x` and `y`.
|
||||
//! \~russian Сдвигает отрезок на `x` и `y`.
|
||||
PILine<Type> & translate(Type x, Type y) {
|
||||
p0.translate(x, y);
|
||||
p1.translate(x, y);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~russian
|
||||
//! Сдвинуть линию на значение координат точки \a PIPoint.
|
||||
//! \~english Shifts the segment by a point offset.
|
||||
//! \~russian Сдвигает отрезок на смещение, заданное точкой.
|
||||
PILine<Type> & translate(const PIPoint<Type> & p) {
|
||||
p0.translate(p);
|
||||
p1.translate(p);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! Создать копию отрезка и сдвинуть её на `x` и `y`.
|
||||
//! \~english Returns translated copy of the segment.
|
||||
//! \~russian Возвращает смещенную копию отрезка.
|
||||
PILine<Type> translated(Type x, Type y) const {
|
||||
PILine<Type> l(*this);
|
||||
l.translate(x, y);
|
||||
return l;
|
||||
}
|
||||
|
||||
//! \~russian
|
||||
//! Создать копию отрезка и сдвинуть её на значение координат точки \a PIPoint.
|
||||
//! \~english Returns copy shifted by a point offset.
|
||||
//! \~russian Возвращает копию, смещенную на точку.
|
||||
PILine<Type> translated(const PIPoint<Type> & p) const {
|
||||
PILine<Type> l(*this);
|
||||
l.translate(p);
|
||||
return l;
|
||||
}
|
||||
|
||||
//! \~russian
|
||||
//! Сдвинуть линию на \a x, \a y.
|
||||
//! \details Является копией метода \a translate().
|
||||
//! \~english Same as \a translate().
|
||||
//! \~russian Синоним \a translate().
|
||||
PILine<Type> & move(Type x, Type y) { return translate(x, y); }
|
||||
|
||||
//! \~russian
|
||||
//! Сдвинуть линию на значение координат точки \a PIPoint.
|
||||
//! \details Является копией метода \a translate().
|
||||
//! \~english Same as \a translate().
|
||||
//! \~russian Синоним \a translate().
|
||||
PILine<Type> & move(const PIPoint<Type> & p) { return translate(p); }
|
||||
|
||||
//! \~russian
|
||||
//! Создать копию отрезка и сдвинуть её на \a x, \a y.
|
||||
//! \details Является копией метода \a translated().
|
||||
//! \~english Same as \a translated().
|
||||
//! \~russian Синоним \a translated().
|
||||
PILine<Type> moved(Type x, Type y) const {
|
||||
PILine<Type> l(*this);
|
||||
l.translate(x, y);
|
||||
return l;
|
||||
}
|
||||
|
||||
//! \~russian
|
||||
//! Создать копию отрезка и сдвинуть её на значение координат точки \a PIPoint.
|
||||
//! \details Является копией метода \a translated().
|
||||
//! \~english Same as \a translated().
|
||||
//! \~russian Синоним \a translated().
|
||||
PILine<Type> moved(const PIPoint<Type> & p) const {
|
||||
PILine<Type> l(*this);
|
||||
l.translate(p);
|
||||
return l;
|
||||
}
|
||||
|
||||
//! \~russian Сдвинуть линию по двум координатам на значение \a x.
|
||||
//! \~english Shifts both coordinates by `x`.
|
||||
//! \~russian Сдвигает обе координаты на `x`.
|
||||
void operator+=(Type x) { translate(x, x); }
|
||||
|
||||
//! \~russian Сдвинуть линию по двум координатам на величину координат точки \a PIPoint.
|
||||
//! \~english Shifts the segment by a point offset.
|
||||
//! \~russian Сдвигает отрезок на смещение, заданное точкой.
|
||||
void operator+=(const PIPoint<Type> & p) { translate(p); }
|
||||
|
||||
//! \~russian Сдвинуть линию по двум координатам на значение \a x.
|
||||
//! \~english Shifts both coordinates by `-x`.
|
||||
//! \~russian Сдвигает обе координаты на `-x`.
|
||||
void operator-=(Type x) { translate(-x, -x); }
|
||||
|
||||
//! \~russian Сдвинуть линию по двум координатам на величину координат точки \a PIPoint.
|
||||
//! \~english Shifts the segment by the negated point offset.
|
||||
//! \~russian Сдвигает отрезок на отрицательное смещение точки.
|
||||
void operator-=(const PIPoint<Type> & p) { translate(-p); }
|
||||
|
||||
//! \~russian Сдвинуть линию по двум координатам на величину координат точки \a PIPoint.
|
||||
//! \~english Returns segment shifted by a point offset.
|
||||
//! \~russian Возвращает отрезок, смещенный на точку.
|
||||
PILine<Type> operator+(const PIPoint<Type> & p) { return translated(p); }
|
||||
|
||||
//! \~russian Сдвинуть линию по двум координатам на величину координат точки \a PIPoint.
|
||||
//! \~english Returns segment shifted by the negated point offset.
|
||||
//! \~russian Возвращает отрезок, смещенный на отрицательное смещение точки.
|
||||
PILine<Type> operator-(const PIPoint<Type> & p) { return translated(-p); }
|
||||
|
||||
//! \~russian Проверить равенство координат двух отрезков.
|
||||
//! \~english Checks whether segment endpoints are equal.
|
||||
//! \~russian Проверяет равенство концов отрезков.
|
||||
bool operator==(const PILine<Type> & r) const { return (p0 == r.p0 && p1 == r.p1); }
|
||||
|
||||
//! \~russian Проверить неравенство координат двух отрезков.
|
||||
//! \~english Checks whether segments differ.
|
||||
//! \~russian Проверяет различие отрезков.
|
||||
bool operator!=(const PILine<Type> & r) const { return (p1 != r.p1 || p1 != r.p1); }
|
||||
};
|
||||
|
||||
//! \~russian Перегруженный оператор для вывода координат в \a PICout.
|
||||
//! \relatesalso PICout
|
||||
//! \~english Writes segment coordinates to \a PICout.
|
||||
//! \~russian Выводит координаты отрезка в \a PICout.
|
||||
template<typename Type>
|
||||
PICout operator<<(PICout & s, const PILine<Type> & v) {
|
||||
s.space();
|
||||
@@ -186,9 +194,20 @@ PICout operator<<(PICout & s, const PILine<Type> & v) {
|
||||
return s;
|
||||
}
|
||||
|
||||
//! \~english Alias for segment with `int` coordinates.
|
||||
//! \~russian Псевдоним отрезка с координатами типа `int`.
|
||||
typedef PILine<int> PILinei;
|
||||
|
||||
//! \~english Alias for segment with `uint` coordinates.
|
||||
//! \~russian Псевдоним отрезка с координатами типа `uint`.
|
||||
typedef PILine<uint> PILineu;
|
||||
|
||||
//! \~english Alias for segment with `float` coordinates.
|
||||
//! \~russian Псевдоним отрезка с координатами типа `float`.
|
||||
typedef PILine<float> PILinef;
|
||||
|
||||
//! \~english Alias for segment with `double` coordinates.
|
||||
//! \~russian Псевдоним отрезка с координатами типа `double`.
|
||||
typedef PILine<double> PILined;
|
||||
|
||||
#endif // PILINE_H
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file pimathbase.h
|
||||
* \ingroup Math
|
||||
* \~\brief
|
||||
* \~english Basic mathematical functions and defines
|
||||
* \~russian Базовые математические функции и дефайны
|
||||
*/
|
||||
//! \~\file pimathbase.h
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english Basic mathematical constants and helper algorithms
|
||||
//! \~russian Базовые математические константы и вспомогательные алгоритмы
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Basic mathematical functions and defines
|
||||
@@ -41,112 +40,260 @@
|
||||
# include <cmath>
|
||||
#endif
|
||||
|
||||
//! \name Mathematical constants
|
||||
//! \{
|
||||
//! \~english Natural logarithm of 2
|
||||
//! \~russian Натуральный логарифм 2
|
||||
#ifndef M_LN2
|
||||
# define M_LN2 0.69314718055994530942
|
||||
#endif
|
||||
//! \~english Natural logarithm of 10
|
||||
//! \~russian Натуральный логарифм 10
|
||||
#ifndef M_LN10
|
||||
# define M_LN10 2.30258509299404568402
|
||||
#endif
|
||||
//! \~english Square root of 2
|
||||
//! \~russian Квадратный корень из 2
|
||||
#ifndef M_SQRT2
|
||||
# define M_SQRT2 1.41421356237309514547
|
||||
#endif
|
||||
//! \~english Square root of 3
|
||||
//! \~russian Квадратный корень из 3
|
||||
#ifndef M_SQRT3
|
||||
# define M_SQRT3 1.73205080756887719318
|
||||
#endif
|
||||
//! \~english 1 divided by square root of 2
|
||||
//! \~russian 1 делить на квадратный корень из 2
|
||||
#ifndef M_1_SQRT2
|
||||
# define M_1_SQRT2 0.70710678118654746172
|
||||
#endif
|
||||
//! \~english 1 divided by square root of 3
|
||||
//! \~russian 1 делить на квадратный корень из 3
|
||||
#ifndef M_1_SQRT3
|
||||
# define M_1_SQRT3 0.57735026918962584208
|
||||
#endif
|
||||
//! \~english Pi constant
|
||||
//! \~russian Число Пи
|
||||
#ifndef M_PI
|
||||
# define M_PI 3.141592653589793238462643383280
|
||||
#endif
|
||||
//! \~english 2 times Pi
|
||||
//! \~russian 2 times Пи
|
||||
#ifndef M_2PI
|
||||
# define M_2PI 6.283185307179586476925286766559
|
||||
#endif
|
||||
//! \~english Pi divided by 3
|
||||
//! \~russian Пи делить на 3
|
||||
#ifndef M_PI_3
|
||||
# define M_PI_3 1.04719755119659774615
|
||||
#endif
|
||||
//! \~english 2 times Pi divided by 3
|
||||
//! \~russian 2 times Пи делить на 3
|
||||
#ifndef M_2PI_3
|
||||
# define M_2PI_3 2.0943951023931954923
|
||||
#endif
|
||||
//! \~english 180 divided by Pi (degrees to radians conversion factor)
|
||||
//! \~russian 180 делить на Пи (коэффициент преобразования градусов в радианы)
|
||||
#ifndef M_180_PI
|
||||
# define M_180_PI 57.2957795130823208768
|
||||
#endif
|
||||
//! \~english Pi divided by 180 (radians to degrees conversion factor)
|
||||
//! \~russian Пи делить на 180 (коэффициент преобразования радианов в градусы)
|
||||
#ifndef M_PI_180
|
||||
# define M_PI_180 1.74532925199432957692e-2
|
||||
#endif
|
||||
//! \~english Square root of Pi
|
||||
//! \~russian Квадратный корень из Пи
|
||||
#ifndef M_SQRT_PI
|
||||
# define M_SQRT_PI 1.772453850905516027298167483341
|
||||
#endif
|
||||
//! \~english Euler's number
|
||||
//! \~russian Число Эйлера
|
||||
#ifndef M_E
|
||||
# define M_E 2.7182818284590452353602874713527
|
||||
#endif
|
||||
//! \~english Speed of light in vacuum
|
||||
//! \~russian Скорость света в вакууме
|
||||
#ifndef M_LIGHT_SPEED
|
||||
# define M_LIGHT_SPEED 2.99792458e+8
|
||||
#endif
|
||||
//! \~english Relative gas constant
|
||||
//! \~russian Газовая постоянная
|
||||
#ifndef M_RELATIVE_CONST
|
||||
# define M_RELATIVE_CONST -4.442807633e-10;
|
||||
#endif
|
||||
//! \~english Gravitational constant
|
||||
//! \~russian Гравитационная постоянная
|
||||
#ifndef M_GRAVITY_CONST
|
||||
# define M_GRAVITY_CONST 398600.4418e9;
|
||||
#endif
|
||||
//! \}
|
||||
|
||||
|
||||
//! \~english Multiplicative factor for converting degrees to radians.
|
||||
//! \~russian Множитель для перевода градусов в радианы.
|
||||
const double deg2rad = M_PI_180;
|
||||
|
||||
//! \~english Multiplicative factor for converting radians to degrees.
|
||||
//! \~russian Множитель для перевода радиан в градусы.
|
||||
const double rad2deg = M_180_PI;
|
||||
|
||||
|
||||
// clang-format off
|
||||
//! \~english Returns the sign of a floating-point value.
|
||||
//! \~russian Возвращает знак вещественного значения.
|
||||
inline int sign(const float & x) {return (x < 0.f) ? -1 : (x > 0.f ? 1 : 0);}
|
||||
|
||||
//! \~english Returns the sign of a floating-point value.
|
||||
//! \~russian Возвращает знак вещественного значения.
|
||||
inline int sign(const double & x) {return (x < 0. ) ? -1 : (x > 0. ? 1 : 0);}
|
||||
|
||||
//! \~english Returns the sign of a floating-point value.
|
||||
//! \~russian Возвращает знак вещественного значения.
|
||||
inline int sign(const ldouble & x) {return (x < 0.L) ? -1 : (x > 0.L ? 1 : 0);}
|
||||
|
||||
//! \~english Returns `2` raised to integer power \a p.
|
||||
//! \~russian Возвращает `2` в целой степени \a p.
|
||||
inline int pow2 (const int p ) {return 1 << p;}
|
||||
|
||||
//! \~english Returns `10` raised to the specified power.
|
||||
//! \~russian Возвращает `10` в указанной степени.
|
||||
inline float pow10(const float & e) {return powf(10.f, e);}
|
||||
|
||||
//! \~english Returns `10` raised to the specified power.
|
||||
//! \~russian Возвращает `10` в указанной степени.
|
||||
inline double pow10(const double & e) {return pow (10. , e);}
|
||||
|
||||
//! \~english Returns `10` raised to the specified power.
|
||||
//! \~russian Возвращает `10` в указанной степени.
|
||||
inline ldouble pow10(const ldouble & e) {return powl(10.L, e);}
|
||||
// clang-format on
|
||||
|
||||
|
||||
//! \~english Returns normalized sinc, `sin(pi*x)/(pi*x)`.
|
||||
//! \~russian Возвращает нормированную функцию sinc, `sin(pi*x)/(pi*x)`.
|
||||
inline double sinc(const double & v) {
|
||||
if (v == 0.) return 1.;
|
||||
double t = M_PI * v;
|
||||
return sin(t) / t;
|
||||
}
|
||||
|
||||
|
||||
//! \name Bessel functions
|
||||
//! \{
|
||||
//!
|
||||
//! \~english Bessel function of the first kind of order 0
|
||||
//! \~russian Функция Бесселя первого рода порядка 0
|
||||
//! \details
|
||||
//! \~english Bessel function of the first kind J0(x), solution to Bessel's differential equation
|
||||
//! \~russian Функция Бесселя первого рода J0(x), решение уравнения Бесселя
|
||||
//! \~\sa piJ1(), piJn()
|
||||
PIP_EXPORT double piJ0(const double & v);
|
||||
|
||||
//! \~english Bessel function of the first kind of order 1
|
||||
//! \~russian Функция Бесселя первого рода порядка 1
|
||||
//! \details
|
||||
//! \~english Bessel function of the first kind J1(x), solution to Bessel's differential equation
|
||||
//! \~russian Функция Бесселя первого рода J1(x), решение уравнения Бесселя
|
||||
//! \~\sa piJ0(), piJn()
|
||||
PIP_EXPORT double piJ1(const double & v);
|
||||
|
||||
//! \~english Bessel function of the first kind of order n
|
||||
//! \~russian Функция Бесселя первого рода порядка n
|
||||
//! \details
|
||||
//! \~english Bessel function of the first kind Jn(n, x), solution to Bessel's differential equation
|
||||
//! \~russian Функция Бесселя первого рода Jn(n, x), решение уравнения Бесселя
|
||||
//! \~\sa piJ0(), piJ1()
|
||||
PIP_EXPORT double piJn(int n, const double & v);
|
||||
|
||||
//! \~english Bessel function of the second kind of order 0
|
||||
//! \~russian Функция Бесселя второго рода порядка 0
|
||||
//! \details
|
||||
//! \~english Bessel function of the second kind Y0(x), also known as Neumann function
|
||||
//! \~russian Функция Бесселя второго рода Y0(x), также известная как функция Неймана
|
||||
//! \~\sa piY1(), piYn()
|
||||
PIP_EXPORT double piY0(const double & v);
|
||||
|
||||
//! \~english Bessel function of the second kind of order 1
|
||||
//! \~russian Функция Бесселя второго рода порядка 1
|
||||
//! \details
|
||||
//! \~english Bessel function of the second kind Y1(x), also known as Neumann function
|
||||
//! \~russian Функция Бесселя второго рода Y1(x), также известная как функция Неймана
|
||||
//! \~\sa piY0(), piYn()
|
||||
PIP_EXPORT double piY1(const double & v);
|
||||
|
||||
//! \~english Bessel function of the second kind of order n
|
||||
//! \~russian Функция Бесселя второго рода порядка n
|
||||
//! \details
|
||||
//! \~english Bessel function of the second kind Yn(n, x), also known as Neumann function
|
||||
//! \~russian Функция Бесселя второго рода Yn(n, x), также известная как функция Неймана
|
||||
//! \~\sa piY0(), piY1()
|
||||
PIP_EXPORT double piYn(int n, const double & v);
|
||||
|
||||
//! \}
|
||||
|
||||
|
||||
// clang-format off
|
||||
//! \~english Converts degrees to radians.
|
||||
//! \~russian Преобразует градусы в радианы.
|
||||
inline constexpr float toRad(float deg) {return deg * M_PI_180;}
|
||||
|
||||
//! \~english Converts degrees to radians.
|
||||
//! \~russian Преобразует градусы в радианы.
|
||||
inline constexpr double toRad(double deg) {return deg * M_PI_180;}
|
||||
|
||||
//! \~english Converts degrees to radians.
|
||||
//! \~russian Преобразует градусы в радианы.
|
||||
inline constexpr ldouble toRad(ldouble deg) {return deg * M_PI_180;}
|
||||
|
||||
//! \~english Converts radians to degrees.
|
||||
//! \~russian Преобразует радианы в градусы.
|
||||
inline constexpr float toDeg(float rad) {return rad * M_180_PI;}
|
||||
|
||||
//! \~english Converts radians to degrees.
|
||||
//! \~russian Преобразует радианы в градусы.
|
||||
inline constexpr double toDeg(double rad) {return rad * M_180_PI;}
|
||||
|
||||
//! \~english Converts radians to degrees.
|
||||
//! \~russian Преобразует радианы в градусы.
|
||||
inline constexpr ldouble toDeg(ldouble rad) {return rad * M_180_PI;}
|
||||
// clang-format on
|
||||
|
||||
|
||||
//! \~english Returns square of a value.
|
||||
//! \~russian Возвращает квадрат значения.
|
||||
template<typename T>
|
||||
inline constexpr T sqr(const T & v) {
|
||||
return v * v;
|
||||
}
|
||||
|
||||
|
||||
//! \~english Converts a power ratio to decibels.
|
||||
//! \~russian Преобразует отношение мощностей в децибелы.
|
||||
template<typename T>
|
||||
inline constexpr T toDb(T val) {
|
||||
return T(10.) * std::log10(val);
|
||||
}
|
||||
|
||||
//! \~english Converts decibels to a linear power ratio.
|
||||
//! \~russian Преобразует децибелы в линейное отношение мощностей.
|
||||
template<typename T>
|
||||
inline constexpr T fromDb(T val) {
|
||||
return std::pow(T(10.), val / T(10.));
|
||||
}
|
||||
|
||||
// [-1 ; 1]
|
||||
|
||||
//! \~english Returns a pseudo-random value in the range `[-1; 1]`.
|
||||
//! \~russian Возвращает псевдослучайное значение в диапазоне `[-1; 1]`.
|
||||
PIP_EXPORT double randomd();
|
||||
// [-1 ; 1] normal
|
||||
|
||||
//! \~english Returns a normally distributed pseudo-random value with mean \a dv and deviation \a sv.
|
||||
//! \~russian Возвращает нормально распределенное псевдослучайное значение со средним \a dv и отклонением \a sv.
|
||||
PIP_EXPORT double randomn(double dv = 0., double sv = 1.);
|
||||
|
||||
|
||||
//! \~english Returns vector with absolute values of each element
|
||||
//! \~russian Возвращает вектор с абсолютными значениями каждого элемента
|
||||
template<typename T>
|
||||
inline PIVector<T> piAbs(const PIVector<T> & v) {
|
||||
PIVector<T> result;
|
||||
@@ -157,6 +304,8 @@ inline PIVector<T> piAbs(const PIVector<T> & v) {
|
||||
}
|
||||
|
||||
|
||||
//! \~english Normalizes an angle to the `[0; 360]` degree range in place.
|
||||
//! \~russian Нормализует угол к диапазону `[0; 360]` градусов на месте.
|
||||
template<typename T>
|
||||
void normalizeAngleDeg360(T & a) {
|
||||
while (a < 0.)
|
||||
@@ -164,6 +313,9 @@ void normalizeAngleDeg360(T & a) {
|
||||
while (a > 360.)
|
||||
a -= 360.;
|
||||
}
|
||||
|
||||
//! \~english Returns an angle normalized to the `[0; 360]` degree range.
|
||||
//! \~russian Возвращает угол, нормализованный к диапазону `[0; 360]` градусов.
|
||||
template<typename T>
|
||||
double normalizedAngleDeg360(T a) {
|
||||
normalizeAngleDeg360(a);
|
||||
@@ -171,6 +323,8 @@ double normalizedAngleDeg360(T a) {
|
||||
}
|
||||
|
||||
|
||||
//! \~english Normalizes an angle to the `[-180; 180]` degree range in place.
|
||||
//! \~russian Нормализует угол к диапазону `[-180; 180]` градусов на месте.
|
||||
template<typename T>
|
||||
void normalizeAngleDeg180(T & a) {
|
||||
while (a < -180.)
|
||||
@@ -178,6 +332,9 @@ void normalizeAngleDeg180(T & a) {
|
||||
while (a > 180.)
|
||||
a -= 360.;
|
||||
}
|
||||
|
||||
//! \~english Returns an angle normalized to the `[-180; 180]` degree range.
|
||||
//! \~russian Возвращает угол, нормализованный к диапазону `[-180; 180]` градусов.
|
||||
template<typename T>
|
||||
double normalizedAngleDeg180(T a) {
|
||||
normalizeAngleDeg180(a);
|
||||
@@ -185,6 +342,11 @@ double normalizedAngleDeg180(T a) {
|
||||
}
|
||||
|
||||
|
||||
//! \~english Fits a linear model `y = a*x + b` with ordinary least squares.
|
||||
//! \~russian Аппроксимирует линейную модель `y = a*x + b` методом наименьших квадратов.
|
||||
//! \~\details
|
||||
//! \~english Returns \c false when fewer than two sample pairs are provided.
|
||||
//! \~russian Возвращает \c false, если передано меньше двух пар значений.
|
||||
template<typename T>
|
||||
bool OLS_Linear(const PIVector<PIPair<T, T>> & input, T * out_a, T * out_b) {
|
||||
static_assert(std::is_arithmetic<T>::value, "Type must be arithmetic");
|
||||
@@ -207,6 +369,11 @@ bool OLS_Linear(const PIVector<PIPair<T, T>> & input, T * out_a, T * out_b) {
|
||||
}
|
||||
|
||||
|
||||
//! \~english Fits a weighted linear model `y = a*x + b`.
|
||||
//! \~russian Аппроксимирует взвешенную линейную модель `y = a*x + b`.
|
||||
//! \~\details
|
||||
//! \~english Returns \c false when the sample is too small or the weights vector has a different size.
|
||||
//! \~russian Возвращает \c false, если выборка слишком мала или размер вектора весов не совпадает.
|
||||
template<typename T>
|
||||
bool WLS_Linear(const PIVector<PIPair<T, T>> & input, const PIVector<T> & weights, T * out_a, T * out_b) {
|
||||
static_assert(std::is_arithmetic<T>::value, "Type must be arithmetic");
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file pimathcomplex.h
|
||||
* \ingroup Math
|
||||
* \~\brief
|
||||
* \~english Complex numbers
|
||||
* \~russian Комплексные числа
|
||||
*/
|
||||
//! \~\file pimathcomplex.h
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english Complex numbers
|
||||
//! \~russian Комплексные числа
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
PIP math complex
|
||||
@@ -36,27 +35,57 @@
|
||||
|
||||
using std::complex;
|
||||
|
||||
//! \~\ingroup Math
|
||||
//! \~english Type trait that reports whether \a T is a specialization of \c std::complex.
|
||||
//! \~russian Признак типа, определяющий, является ли \a T специализацией \c std::complex.
|
||||
template<typename T>
|
||||
struct is_complex: std::false_type {};
|
||||
|
||||
//! \~\ingroup Math
|
||||
//! \~english Specialization for complex types.
|
||||
//! \~russian Специализация для комплексных типов.
|
||||
template<typename T>
|
||||
struct is_complex<std::complex<T>>: std::true_type {};
|
||||
|
||||
//! \~english Complex integer type.
|
||||
//! \~russian Комплексный тип на целых числах.
|
||||
typedef complex<int> complexi;
|
||||
//! \~english Complex short integer type.
|
||||
//! \~russian Комплексный тип на \c short.
|
||||
typedef complex<short> complexs;
|
||||
//! \~english Complex single-precision type.
|
||||
//! \~russian Комплексный тип одинарной точности.
|
||||
typedef complex<float> complexf;
|
||||
//! \~english Complex extended-precision type.
|
||||
//! \~russian Комплексный тип расширенной точности.
|
||||
typedef complex<ldouble> complexld;
|
||||
#ifndef QPIEVALUATOR_COMPLEX
|
||||
//! \~english Complex double-precision type.
|
||||
//! \~russian Комплексный тип двойной точности.
|
||||
typedef complex<double> complexd;
|
||||
|
||||
//! \~english Imaginary unit in double precision.
|
||||
//! \~russian Мнимая единица двойной точности.
|
||||
const complexd complexd_i(0., 1.);
|
||||
//! \~english Zero value in double precision.
|
||||
//! \~russian Нулевое значение двойной точности.
|
||||
const complexd complexd_0(0.);
|
||||
//! \~english Unity value in double precision.
|
||||
//! \~russian Единичное значение двойной точности.
|
||||
const complexd complexd_1(1.);
|
||||
#endif
|
||||
//! \~english Imaginary unit in extended precision.
|
||||
//! \~russian Мнимая единица расширенной точности.
|
||||
const complexld complexld_i(0., 1.);
|
||||
//! \~english Zero value in extended precision.
|
||||
//! \~russian Нулевое значение расширенной точности.
|
||||
const complexld complexld_0(0.);
|
||||
//! \~english Unity value in extended precision.
|
||||
//! \~russian Единичное значение расширенной точности.
|
||||
const complexld complexld_1(1.);
|
||||
|
||||
//! \~english Returns sign for real and imaginary parts independently.
|
||||
//! \~russian Возвращает знак действительной и мнимой частей по отдельности.
|
||||
inline complexd sign(const complexd & x) {
|
||||
return complexd(sign(x.real()), sign(x.imag()));
|
||||
}
|
||||
@@ -103,6 +132,9 @@ inline complexd log10(const complexd & c) {
|
||||
# endif
|
||||
#endif
|
||||
|
||||
//! \relatesalso PICout
|
||||
//! \~english Writes a complex number as `(real; imag)`.
|
||||
//! \~russian Записывает комплексное число в виде `(real; imag)`.
|
||||
template<typename T>
|
||||
inline PICout operator<<(PICout s, const complex<T> & v) {
|
||||
s.space();
|
||||
@@ -113,6 +145,8 @@ inline PICout operator<<(PICout s, const complex<T> & v) {
|
||||
}
|
||||
|
||||
|
||||
//! \~english Returns magnitudes of all complex elements in the vector.
|
||||
//! \~russian Возвращает модули всех комплексных элементов вектора.
|
||||
inline PIVector<double> abs(const PIVector<complexd> & v) {
|
||||
PIVector<double> result;
|
||||
result.resize(v.size());
|
||||
@@ -122,6 +156,8 @@ inline PIVector<double> abs(const PIVector<complexd> & v) {
|
||||
}
|
||||
|
||||
|
||||
//! \~english Returns element-wise magnitudes of a complex matrix.
|
||||
//! \~russian Возвращает матрицу модулей для комплексной матрицы.
|
||||
inline PIVector2D<double> abs(const PIVector2D<complexd> & v) {
|
||||
PIVector2D<double> result(v.rows(), v.cols());
|
||||
for (uint i = 0; i < v.rows(); i++)
|
||||
@@ -131,24 +167,16 @@ inline PIVector2D<double> abs(const PIVector2D<complexd> & v) {
|
||||
}
|
||||
|
||||
|
||||
/**
|
||||
* \brief floating point number specific comparison between value passed as parameter and zero
|
||||
*
|
||||
* @param v floating point parameter for comparison
|
||||
* @return true if v in locality of zero, otherwise false
|
||||
*/
|
||||
//! \~english Checks whether a floating-point value is close to zero.
|
||||
//! \~russian Проверяет, находится ли вещественное значение вблизи нуля.
|
||||
template<typename T, typename std::enable_if<std::is_floating_point<T>::value, int>::type = 0>
|
||||
inline bool PIMathFloatNullCompare(const T v) {
|
||||
static_assert(std::is_floating_point<T>::value, "Type must be floating point");
|
||||
return (piAbs(v) < T(1E-200));
|
||||
}
|
||||
|
||||
/**
|
||||
* \brief floating point number specific comparison between parameter value and zero.
|
||||
*
|
||||
* @param v complex with floating point real and imag parts
|
||||
* @return true if absolute of v in locality of zero, otherwise false
|
||||
*/
|
||||
//! \~english Checks whether a complex value with floating-point components is close to zero.
|
||||
//! \~russian Проверяет, находится ли комплексное значение с вещественными компонентами вблизи нуля.
|
||||
template<typename T,
|
||||
typename std::enable_if<std::is_floating_point<decltype(T::real)>::value && std::is_floating_point<decltype(T::imag)>::value,
|
||||
int>::type = 0>
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
//! \file pimathmatrix.h
|
||||
//! \ingroup Math
|
||||
//! \~\file pimathmatrix.h
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english Math matrix
|
||||
//! \~russian Математическая матрица
|
||||
@@ -32,31 +32,34 @@
|
||||
|
||||
/// Matrix templated
|
||||
|
||||
#define PIMM_FOR \
|
||||
for (uint r = 0; r < Rows; ++r) \
|
||||
for (uint c = 0; c < Cols; ++c)
|
||||
#define PIMM_FOR \
|
||||
for (uint r = 0; r < Rows; ++r) \
|
||||
for (uint c = 0; c < Cols; ++c)
|
||||
#define PIMM_FOR_C for (uint i = 0; i < Cols; ++i)
|
||||
#define PIMM_FOR_R for (uint i = 0; i < Rows; ++i)
|
||||
|
||||
#pragma pack(push, 1)
|
||||
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english
|
||||
//! Fixed-size math matrix. Stores matrix data inline and performs dimension checks at compile time where possible.
|
||||
//! \brief A class for fixed size and type matrix.
|
||||
//! \tparam `Rows` rows number of matrix.
|
||||
//! \tparam `Сols` columns number of matrix.
|
||||
//! \tparam `Type` is the data type of the matrix. There are can be basic C++ language data and different classes where the arithmetic
|
||||
//! operators(=, +=, -=, *=, /=, ==, !=, +, -, *, /)
|
||||
//! of the C++ language are implemented
|
||||
//! operators(=, +=, -=, *=, /=, ==, !=, +, -, *, /) of the C++ language are implemented
|
||||
//! \~russian
|
||||
//! Математическая матрица фиксированного размера. Хранит данные матрицы внутри объекта и по возможности проверяет размерности на этапе
|
||||
//! компиляции.
|
||||
//! \brief Класс для работы с матрицами фиксированного размера и типа данных.
|
||||
//! \details В отличие от \a PIMathMatrix не занимается динамическим выделением памяти и связанными с этим операциями.
|
||||
//! То есть он тривиально копируемый.
|
||||
//! Содержит проверки времени компиляции на несоответствие размера при различных математических операциях,
|
||||
//! что позволяет заранее выявлять ошибки.
|
||||
//! \details В отличие от \a PIMathMatrix не
|
||||
//! занимается динамическим выделением памяти и связанными с этим операциями. То есть он тривиально копируемый. Содержит проверки времени
|
||||
//! компиляции на несоответствие размера при различных математических операциях, что позволяет заранее выявлять ошибки.
|
||||
//! \tparam `Rows` количество строк матрицы.
|
||||
//! \tparam `Сols` количество столбцов матрицы.
|
||||
//! \tparam `Type`тип данных матрицы. Здесь можеть быть базовый тип данных C++ или различные классы,
|
||||
//! где реализованы арифметические операторы(=, +=, -=, *=, /=, ==, !=, +, -, *, /) языка C++.
|
||||
//! \tparam `Type`тип данных матрицы. Здесь можеть быть базовый тип
|
||||
//! данных C++ или различные классы, где реализованы арифметические операторы(=, +=, -=, *=, /=, ==, !=, +, -, *, /) языка C++.
|
||||
template<uint Rows, uint Cols = Rows, typename Type = double>
|
||||
class PIP_EXPORT PIMathMatrixT {
|
||||
typedef PIMathMatrixT<Rows, Cols, Type> _CMatrix;
|
||||
@@ -148,6 +151,7 @@ public:
|
||||
//! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior").
|
||||
//! \param index номер выбранной строки.
|
||||
//! \return строка в формате \a PIMathVectorT.
|
||||
//! \sa col()
|
||||
PIMathVectorT<Cols, Type> row(uint index) {
|
||||
PIMathVectorT<Cols, Type> tv;
|
||||
PIMM_FOR_C tv[i] = m[index][i];
|
||||
@@ -200,6 +204,7 @@ public:
|
||||
//! \param rf номер первой выбранной строки.
|
||||
//! \param rs номер второй выбранной строки.
|
||||
//! \return матрица типа \a PIMathMatrixT<Rows, Cols, Type>.
|
||||
//! \sa swapCols()
|
||||
PIMathMatrixT<Rows, Cols, Type> & swapRows(uint rf, uint rs) {
|
||||
PIMM_FOR_C piSwap<Type>(m[rf][i], m[rs][i]);
|
||||
return *this;
|
||||
@@ -214,9 +219,10 @@ public:
|
||||
//! \~russian
|
||||
//! \brief Метод, меняющий местами выбранные столбцы в матрице.
|
||||
//! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior").
|
||||
//! \param rf номер первого выбранного столбца.
|
||||
//! \param rs номер второго выбранного столбца.
|
||||
//! \param cf номер первого выбранного столбца.
|
||||
//! \param cs номер второго выбранного столбца.
|
||||
//! \return матрица типа \a PIMathMatrixT<Rows, Cols, Type>.
|
||||
//! \sa swapRows()
|
||||
PIMathMatrixT<Rows, Cols, Type> & swapCols(uint cf, uint cs) {
|
||||
PIMM_FOR_R piSwap<Type>(m[i][cf], m[i][cs]);
|
||||
return *this;
|
||||
@@ -260,6 +266,7 @@ public:
|
||||
//! \~russian
|
||||
//! \brief Метод, являются ли все элементы матрицы нулями.
|
||||
//! \return true если матрица нулевая, иначе false.
|
||||
//! \sa isIdentity()
|
||||
bool isNull() const {
|
||||
PIMM_FOR if (m[r][c] != Type(0)) return false;
|
||||
return true;
|
||||
@@ -292,6 +299,7 @@ public:
|
||||
//! \param row номер строки матрицы.
|
||||
//! \param col номер столбца матрицы.
|
||||
//! \return элемент матрицы.
|
||||
//! \sa at(), element(uint, uint) const
|
||||
inline Type & element(uint row, uint col) { return m[row][col]; }
|
||||
|
||||
//! \~english
|
||||
@@ -306,6 +314,7 @@ public:
|
||||
//! \param row номер строки матрицы.
|
||||
//! \param col номер столбца матрицы.
|
||||
//! \return копия элемента матрицы.
|
||||
//! \sa at(), element(uint, uint)
|
||||
inline const Type & element(uint row, uint col) const { return m[row][col]; }
|
||||
|
||||
//! \~english
|
||||
@@ -873,11 +882,23 @@ inline PIMathMatrixT<Rows, Cols, Type> operator*(const Type & x, const PIMathMat
|
||||
}
|
||||
|
||||
|
||||
//! \~english 2 x 2 fixed-size matrix of \c int.
|
||||
//! \~russian Матрица 2 x 2 фиксированного размера из \c int.
|
||||
typedef PIMathMatrixT<2u, 2u, int> PIMathMatrixT22i;
|
||||
//! \~english 3 x 3 fixed-size matrix of \c int.
|
||||
//! \~russian Матрица 3 x 3 фиксированного размера из \c int.
|
||||
typedef PIMathMatrixT<3u, 3u, int> PIMathMatrixT33i;
|
||||
//! \~english 4 x 4 fixed-size matrix of \c int.
|
||||
//! \~russian Матрица 4 x 4 фиксированного размера из \c int.
|
||||
typedef PIMathMatrixT<4u, 4u, int> PIMathMatrixT44i;
|
||||
//! \~english 2 x 2 fixed-size matrix of \c double.
|
||||
//! \~russian Матрица 2 x 2 фиксированного размера из \c double.
|
||||
typedef PIMathMatrixT<2u, 2u, double> PIMathMatrixT22d;
|
||||
//! \~english 3 x 3 fixed-size matrix of \c double.
|
||||
//! \~russian Матрица 3 x 3 фиксированного размера из \c double.
|
||||
typedef PIMathMatrixT<3u, 3u, double> PIMathMatrixT33d;
|
||||
//! \~english 4 x 4 fixed-size matrix of \c double.
|
||||
//! \~russian Матрица 4 x 4 фиксированного размера из \c double.
|
||||
typedef PIMathMatrixT<4u, 4u, double> PIMathMatrixT44d;
|
||||
|
||||
|
||||
@@ -891,21 +912,24 @@ class PIMathMatrix;
|
||||
|
||||
/// Matrix
|
||||
|
||||
#define PIMM_FOR \
|
||||
for (uint r = 0; r < _V2D::rows_; ++r) \
|
||||
for (uint c = 0; c < _V2D::cols_; ++c)
|
||||
#define PIMM_FOR \
|
||||
for (uint r = 0; r < _V2D::rows_; ++r) \
|
||||
for (uint c = 0; c < _V2D::cols_; ++c)
|
||||
#define PIMM_FOR_A for (uint i = 0; i < _V2D::mat.size(); ++i)
|
||||
#define PIMM_FOR_C for (uint i = 0; i < _V2D::cols_; ++i)
|
||||
#define PIMM_FOR_R for (uint i = 0; i < _V2D::rows_; ++i)
|
||||
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english
|
||||
//! Dynamic-size math matrix. Uses \a PIVector2D as storage and keeps the matrix interface aligned with \a PIMathMatrixT.
|
||||
//! \brief A class for dynamic size and fixed type matrix.
|
||||
//! \tparam `Type` There are can be basic C++ language data and different classes where the arithmetic operators(=, +=, -=, *=, /=, ==, !=,
|
||||
//! +, -, *, /) of the C++ language are implemented.
|
||||
//! \~russian
|
||||
//! \brief Класс для работы с матрицами динамического размера и фиксированного типа.
|
||||
//! \tparam `Type` Здесь можеть быть базовый тип данных C++ или различные классы,
|
||||
//! где реализованы арифметические операторы(=, +=, -=, *=, /=, ==, !=, +, -, *, /) языка C++.
|
||||
//! Математическая матрица динамического размера. Использует \a PIVector2D как хранилище и сохраняет интерфейс, согласованный с \a
|
||||
//! PIMathMatrixT. \brief Класс для работы с матрицами динамического размера и фиксированного типа. \tparam `Type` Здесь можеть быть базовый
|
||||
//! тип данных C++ или различные классы, где реализованы арифметические операторы(=, +=, -=, *=, /=, ==, !=, +, -, *, /) языка C++.
|
||||
template<typename Type>
|
||||
class PIP_EXPORT PIMathMatrix: public PIVector2D<Type> {
|
||||
typedef PIVector2D<Type> _V2D;
|
||||
@@ -1113,6 +1137,7 @@ public:
|
||||
//! \~russian
|
||||
//! \brief Метод, проверяющий содержит ли главная диагональ единицы и все остальные поля нули.
|
||||
//! \return true если матрица единичная, иначе false.
|
||||
//! \sa isNull(), isValid()
|
||||
bool isIdentity() const {
|
||||
PIMM_FOR if ((c == r) ? _V2D::element(r, c) != Type(1) : _V2D::element(r, c) != Type(0)) return false;
|
||||
return true;
|
||||
@@ -1124,6 +1149,7 @@ public:
|
||||
//! \~russian
|
||||
//! \brief Метод, являются ли все элементы матрицы нулями.
|
||||
//! \return true если матрица нулевая, иначе false.
|
||||
//! \sa isIdentity()
|
||||
bool isNull() const {
|
||||
PIMM_FOR_A if (_V2D::mat[i] != Type(0)) return false;
|
||||
return true;
|
||||
@@ -1135,6 +1161,7 @@ public:
|
||||
//! \~russian
|
||||
//! \brief Метод, который проверяет является ли матрица пустой.
|
||||
//! \return true если матрица действительна, иначе false.
|
||||
//! \sa isNull(), isIdentity()
|
||||
bool isValid() const { return !PIVector2D<Type>::isEmpty(); }
|
||||
|
||||
//! \~english
|
||||
@@ -1607,17 +1634,15 @@ inline PIMathMatrix<Type> operator*(const Type & x, const PIMathMatrix<Type> & v
|
||||
return v * x;
|
||||
}
|
||||
|
||||
//! \~english Dynamic matrix of \c int.
|
||||
//! \~russian Динамическая матрица из \c int.
|
||||
typedef PIMathMatrix<int> PIMathMatrixi;
|
||||
//! \~english Dynamic matrix of \c double.
|
||||
//! \~russian Динамическая матрица из \c double.
|
||||
typedef PIMathMatrix<double> PIMathMatrixd;
|
||||
|
||||
//! \~english
|
||||
//! \brief Searching hermitian matrix.
|
||||
//! \param m conjugate transpose matrix.
|
||||
//! \return result of the hermitian.
|
||||
//! \~russian
|
||||
//! \brief Поиск эрмитовой матрицы.
|
||||
//! \param m сопряженная транспонированная матрица.
|
||||
//! \return результат преобразования.
|
||||
//! \~english Returns the Hermitian form of complex matrix \a m.
|
||||
//! \~russian Возвращает эрмитову форму комплексной матрицы \a m.
|
||||
template<typename T>
|
||||
PIMathMatrix<complex<T>> hermitian(const PIMathMatrix<complex<T>> & m) {
|
||||
PIMathMatrix<complex<T>> ret(m);
|
||||
|
||||
@@ -1,3 +1,12 @@
|
||||
//! \~\file pimathmodule.h
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english Math module umbrella header
|
||||
//! \~russian Зонтичный заголовок математического модуля
|
||||
//!
|
||||
//! \~\details
|
||||
//! \~english Includes the main public headers for CRC, evaluation, FFT, solving, quaternions, and statistics.
|
||||
//! \~russian Подключает основные публичные заголовки для CRC, вычислений, БПФ, решения задач, кватернионов и статистики.
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Module includes
|
||||
@@ -34,10 +43,10 @@
|
||||
//! \~russian \par Общее
|
||||
//!
|
||||
//! \~english
|
||||
//! These files provides vectors, matrices, complex numbers, quaternions, FFT and geometry classes
|
||||
//! Includes the main public headers for vectors, matrices, quaternions, solvers, statistics and FFT utilities.
|
||||
//!
|
||||
//! \~russian
|
||||
//! Эти файлы обеспечивают вектора, матрицы, комплексные числа, кватернионы, БПФ и классы геометрических фигур
|
||||
//! Подключает основные публичные заголовки для векторов, матриц, кватернионов, решателей, статистики и БПФ.
|
||||
//!
|
||||
//! \~\authors
|
||||
//! \~english
|
||||
|
||||
@@ -1,6 +1,16 @@
|
||||
/*! \file pimathsolver.h
|
||||
* \brief PIMathSolver
|
||||
*/
|
||||
//! \~\file pimathsolver.h
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english Transfer-function-based differential solver
|
||||
//! \~russian Решатель дифференциальной модели на основе передаточной функции
|
||||
//!
|
||||
//! \~\details
|
||||
//! \~english
|
||||
//! Declares a solver that builds an internal state representation from a
|
||||
//! transfer function and advances it with one of several numerical methods.
|
||||
//! \~russian
|
||||
//! Объявляет решатель, который строит внутреннее представление состояния из
|
||||
//! передаточной функции и продвигает его одним из нескольких численных методов.
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
PIMathSolver
|
||||
@@ -25,50 +35,108 @@
|
||||
|
||||
#include "pimathmatrix.h"
|
||||
|
||||
/// Differential evaluations
|
||||
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english Transfer-function coefficient storage.
|
||||
//! \~russian Хранилище коэффициентов передаточной функции.
|
||||
struct PIP_EXPORT TransferFunction {
|
||||
PIVector<double> vector_Bm, vector_An;
|
||||
//! \~english Numerator coefficients in the order expected by \a fromTF().
|
||||
//! \~russian Коэффициенты числителя в порядке, ожидаемом \a fromTF().
|
||||
PIVector<double> vector_Bm;
|
||||
//! \~english Denominator coefficients in the order expected by \a fromTF().
|
||||
//! \~russian Коэффициенты знаменателя в порядке, ожидаемом \a fromTF().
|
||||
PIVector<double> vector_An;
|
||||
};
|
||||
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english Numerical solver for transfer-function models.
|
||||
//! \~russian Численный решатель для моделей в виде передаточной функции.
|
||||
class PIP_EXPORT PIMathSolver {
|
||||
public:
|
||||
//! \~english Integration method selector.
|
||||
//! \~russian Выбор метода интегрирования.
|
||||
enum Method {
|
||||
Global = -1,
|
||||
Eyler_1 = 01,
|
||||
Eyler_2 = 02,
|
||||
EylerKoshi = 03,
|
||||
RungeKutta_4 = 14,
|
||||
AdamsBashfortMoulton_2 = 22,
|
||||
AdamsBashfortMoulton_3 = 23,
|
||||
AdamsBashfortMoulton_4 = 24,
|
||||
PolynomialApproximation_2 = 32,
|
||||
PolynomialApproximation_3 = 33,
|
||||
PolynomialApproximation_4 = 34,
|
||||
PolynomialApproximation_5 = 35
|
||||
Global = -1 /** \~english Use the global default method \~russian Использовать глобальный метод по умолчанию */,
|
||||
Eyler_1 = 01 /** \~english First-order Euler method \~russian Метод Эйлера первого порядка */,
|
||||
Eyler_2 = 02 /** \~english Second-order Euler method \~russian Метод Эйлера второго порядка */,
|
||||
EylerKoshi = 03 /** \~english Euler-Cauchy method identifier \~russian Идентификатор метода Эйлера-Коши */,
|
||||
RungeKutta_4 = 14 /** \~english Fourth-order Runge-Kutta method \~russian Метод Рунге-Кутты четвертого порядка */,
|
||||
AdamsBashfortMoulton_2 =
|
||||
22 /** \~english Second-order Adams-Bashforth-Moulton method \~russian Метод Адамса-Башфорта-Моултона второго порядка */,
|
||||
AdamsBashfortMoulton_3 =
|
||||
23 /** \~english Third-order Adams-Bashforth-Moulton method \~russian Метод Адамса-Башфорта-Моултона третьего порядка */,
|
||||
AdamsBashfortMoulton_4 =
|
||||
24 /** \~english Fourth-order Adams-Bashforth-Moulton method \~russian Метод Адамса-Башфорта-Моултона четвертого порядка */,
|
||||
PolynomialApproximation_2 =
|
||||
32 /** \~english Polynomial approximation of degree 2 \~russian Полиномиальная аппроксимация степени 2 */,
|
||||
PolynomialApproximation_3 =
|
||||
33 /** \~english Polynomial approximation of degree 3 \~russian Полиномиальная аппроксимация степени 3 */,
|
||||
PolynomialApproximation_4 =
|
||||
34 /** \~english Polynomial approximation of degree 4 \~russian Полиномиальная аппроксимация степени 4 */,
|
||||
PolynomialApproximation_5 =
|
||||
35 /** \~english Polynomial approximation of degree 5 \~russian Полиномиальная аппроксимация степени 5 */
|
||||
};
|
||||
|
||||
//! \~english Constructs an empty solver.
|
||||
//! \~russian Создает пустой решатель.
|
||||
PIMathSolver();
|
||||
|
||||
//! \~english Performs one solver step for input \a u and step \a h.
|
||||
//! \~russian Выполняет один шаг решателя для входа \a u и шага \a h.
|
||||
void solve(double u, double h);
|
||||
//! \~english Initializes the internal model from a transfer function.
|
||||
//! \~russian Инициализирует внутреннюю модель из передаточной функции.
|
||||
void fromTF(const TransferFunction & TF);
|
||||
//! \~english Sets the method used by \a solve().
|
||||
//! \~russian Устанавливает метод, используемый \a solve().
|
||||
void setMethod(Method m) { method = m; }
|
||||
//! \~english Updates stored time history used by polynomial methods.
|
||||
//! \~russian Обновляет историю времени, используемую полиномиальными методами.
|
||||
void setTime(double time);
|
||||
|
||||
//! \~english Performs one step with the first-order Euler method.
|
||||
//! \~russian Выполняет один шаг методом Эйлера первого порядка.
|
||||
void solveEyler1(double u, double h);
|
||||
//! \~english Performs one step with the second-order Euler method.
|
||||
//! \~russian Выполняет один шаг методом Эйлера второго порядка.
|
||||
void solveEyler2(double u, double h);
|
||||
//! \~english Performs one step with the fourth-order Runge-Kutta method.
|
||||
//! \~russian Выполняет один шаг методом Рунге-Кутты четвертого порядка.
|
||||
void solveRK4(double u, double h);
|
||||
//! \~english Performs one step with the second-order Adams-Bashforth-Moulton method.
|
||||
//! \~russian Выполняет один шаг методом Адамса-Башфорта-Моултона второго порядка.
|
||||
void solveABM2(double u, double h);
|
||||
//! \~english Performs one step with the third-order Adams-Bashforth-Moulton method.
|
||||
//! \~russian Выполняет один шаг методом Адамса-Башфорта-Моултона третьего порядка.
|
||||
void solveABM3(double u, double h);
|
||||
//! \~english Performs one step with the fourth-order Adams-Bashforth-Moulton method.
|
||||
//! \~russian Выполняет один шаг методом Адамса-Башфорта-Моултона четвертого порядка.
|
||||
void solveABM4(double u, double h);
|
||||
//! \~english Performs one step with a polynomial approximation of degree \a deg.
|
||||
//! \~russian Выполняет один шаг с полиномиальной аппроксимацией степени \a deg.
|
||||
void solvePA(double u, double h, uint deg);
|
||||
//! \~english Performs one step with degree-2 polynomial approximation.
|
||||
//! \~russian Выполняет один шаг с полиномиальной аппроксимацией степени 2.
|
||||
void solvePA2(double u, double h);
|
||||
//! \~english Performs one step with degree-3 polynomial approximation.
|
||||
//! \~russian Выполняет один шаг с полиномиальной аппроксимацией степени 3.
|
||||
void solvePA3(double u, double h);
|
||||
//! \~english Performs one step with degree-4 polynomial approximation.
|
||||
//! \~russian Выполняет один шаг с полиномиальной аппроксимацией степени 4.
|
||||
void solvePA4(double u, double h);
|
||||
//! \~english Performs one step with degree-5 polynomial approximation.
|
||||
//! \~russian Выполняет один шаг с полиномиальной аппроксимацией степени 5.
|
||||
void solvePA5(double u, double h);
|
||||
|
||||
//! \~english Current solver state vector.
|
||||
//! \~russian Текущий вектор состояния решателя.
|
||||
PIMathVectord X;
|
||||
//! \~english Global default method used when \a Method is \a Global.
|
||||
//! \~russian Глобальный метод по умолчанию, используемый при \a Method::Global.
|
||||
static Method method_global;
|
||||
//! \~english Text description of available methods.
|
||||
//! \~russian Текстовое описание доступных методов.
|
||||
static const char methods_desc[];
|
||||
|
||||
private:
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
/*! \file pimathvector.h
|
||||
* \ingroup Math
|
||||
* \~\brief
|
||||
* \~english Math vector
|
||||
* \~russian Математический вектор
|
||||
*/
|
||||
//! \~\file pimathvector.h
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english Math vector
|
||||
//! \~russian Математический вектор
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
PIMathVector
|
||||
Math vector
|
||||
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
@@ -40,6 +39,15 @@ class PIMathMatrixT;
|
||||
|
||||
#define PIMV_FOR for (uint i = 0; i < Size; ++i)
|
||||
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english Fixed-size mathematical vector with compile-time size
|
||||
//! \~russian Вектор математический фиксированного размера с размером во время компиляции
|
||||
//! \details
|
||||
//! \~english Provides vector operations including arithmetic, normalization, angles, cross product, and dot product
|
||||
//! \~russian Предоставляет операции вектора включая арифметику, нормализацию, углы, векторное произведение и скалярное произведение
|
||||
//! \tparam Size The fixed size of the vector
|
||||
//! \tparam Type The element type (arithmetic or complex)
|
||||
template<uint Size, typename Type = double>
|
||||
class PIP_EXPORT PIMathVectorT {
|
||||
typedef PIMathVectorT<Size, Type> _CVector;
|
||||
@@ -47,50 +55,74 @@ class PIP_EXPORT PIMathVectorT {
|
||||
static_assert(Size > 0, "Size must be > 0");
|
||||
|
||||
public:
|
||||
//! \~english Constructs a vector and fills every coordinate with \a v.
|
||||
//! \~russian Создает вектор и заполняет все координаты значением \a v.
|
||||
PIMathVectorT(const Type & v = Type()) { PIMV_FOR c[i] = v; }
|
||||
//! \~english Constructs a fixed-size vector from a dynamic one of the same size.
|
||||
//! \~russian Создает вектор фиксированного размера из динамического вектора той же длины.
|
||||
PIMathVectorT(const PIVector<Type> & val) {
|
||||
assert(Size == val.size());
|
||||
PIMV_FOR c[i] = val[i];
|
||||
}
|
||||
//! \~english Constructs a vector from an initializer list with exactly \a Size elements.
|
||||
//! \~russian Создает вектор из списка инициализации ровно с \a Size элементами.
|
||||
PIMathVectorT(std::initializer_list<Type> init_list) {
|
||||
assert(Size == init_list.size());
|
||||
PIMV_FOR c[i] = init_list.begin()[i];
|
||||
}
|
||||
//! \~english Builds the displacement vector from point \a st to point \a fn.
|
||||
//! \~russian Строит вектор смещения от точки \a st к точке \a fn.
|
||||
static _CVector fromTwoPoints(const _CVector & st, const _CVector & fn) {
|
||||
_CVector tv;
|
||||
PIMV_FOR tv[i] = fn[i] - st[i];
|
||||
return tv;
|
||||
}
|
||||
|
||||
//! \~english Returns the compile-time vector dimension.
|
||||
//! \~russian Возвращает размерность вектора, заданную во время компиляции.
|
||||
constexpr uint size() const { return Size; }
|
||||
//! \~english Fills all coordinates with \a v.
|
||||
//! \~russian Заполняет все координаты значением \a v.
|
||||
_CVector & fill(const Type & v) {
|
||||
PIMV_FOR c[i] = v;
|
||||
return *this;
|
||||
}
|
||||
//! \~english Adds \a v to every coordinate.
|
||||
//! \~russian Прибавляет \a v к каждой координате.
|
||||
_CVector & move(const Type & v) {
|
||||
PIMV_FOR c[i] += v;
|
||||
return *this;
|
||||
}
|
||||
//! \~english Adds another vector component-wise.
|
||||
//! \~russian Прибавляет другой вектор покомпонентно.
|
||||
_CVector & move(const _CVector & v) {
|
||||
PIMV_FOR c[i] += v[i];
|
||||
return *this;
|
||||
}
|
||||
//! \~english Swaps two coordinates in place.
|
||||
//! \~russian Меняет местами две координаты.
|
||||
_CVector & swapElements(uint f, uint s) {
|
||||
piSwap<Type>(c[f], c[s]);
|
||||
return *this;
|
||||
}
|
||||
//! \~english Returns the squared Euclidean length.
|
||||
//! \~russian Возвращает квадрат евклидовой длины.
|
||||
Type lengthSqr() const {
|
||||
Type tv(0);
|
||||
PIMV_FOR tv += c[i] * c[i];
|
||||
return tv;
|
||||
}
|
||||
|
||||
//! \~english Returns the Euclidean length. Available for arithmetic element types.
|
||||
//! \~russian Возвращает евклидову длину. Доступно для арифметических типов элементов.
|
||||
Type length() const {
|
||||
static_assert(std::is_arithmetic<Type>::value, "Unavailable for complex");
|
||||
if (std::is_arithmetic<Type>::value) return std::sqrt(lengthSqr());
|
||||
// if (is_complex<Type>::value) return 1000.; // std::sqrt(lengthSqr());
|
||||
}
|
||||
|
||||
//! \~english Returns the Manhattan length. Available for arithmetic element types.
|
||||
//! \~russian Возвращает манхэттенскую длину. Доступно для арифметических типов элементов.
|
||||
Type manhattanLength() const {
|
||||
static_assert(std::is_arithmetic<Type>::value, "Unavailable for complex");
|
||||
if (std::is_arithmetic<Type>::value) {
|
||||
@@ -99,6 +131,8 @@ public:
|
||||
return tv;
|
||||
}
|
||||
}
|
||||
//! \~english Returns the cosine of the angle to \a v.
|
||||
//! \~russian Возвращает косинус угла к вектору \a v.
|
||||
Type angleCos(const _CVector & v) const {
|
||||
static_assert(std::is_arithmetic<Type>::value, "Unavailable for complex");
|
||||
if (std::is_arithmetic<Type>::value) {
|
||||
@@ -107,6 +141,8 @@ public:
|
||||
return dot(v) / tv;
|
||||
}
|
||||
}
|
||||
//! \~english Returns the sine of the angle to \a v.
|
||||
//! \~russian Возвращает синус угла к вектору \a v.
|
||||
Type angleSin(const _CVector & v) const {
|
||||
static_assert(std::is_arithmetic<Type>::value, "Unavailable for complex");
|
||||
if (std::is_arithmetic<Type>::value) {
|
||||
@@ -114,24 +150,32 @@ public:
|
||||
return std::sqrt(Type(1) - tv * tv);
|
||||
}
|
||||
}
|
||||
//! \~english Returns the angle to \a v in radians.
|
||||
//! \~russian Возвращает угол к вектору \a v в радианах.
|
||||
Type angleRad(const _CVector & v) const {
|
||||
static_assert(std::is_arithmetic<Type>::value, "Unavailable for complex");
|
||||
if (std::is_arithmetic<Type>::value) {
|
||||
return std::acos(angleCos(v));
|
||||
}
|
||||
}
|
||||
//! \~english Returns the angle to \a v in degrees.
|
||||
//! \~russian Возвращает угол к вектору \a v в градусах.
|
||||
Type angleDeg(const _CVector & v) const {
|
||||
static_assert(std::is_arithmetic<Type>::value, "Unavailable for complex");
|
||||
if (std::is_arithmetic<Type>::value) {
|
||||
return toDeg(angleRad(v));
|
||||
}
|
||||
}
|
||||
//! \~english Returns the elevation angle from this point to \a v in degrees.
|
||||
//! \~russian Возвращает угол возвышения от этой точки к \a v в градусах.
|
||||
Type angleElevation(const _CVector & v) const {
|
||||
static_assert(std::is_arithmetic<Type>::value, "Unavailable for complex");
|
||||
if (std::is_arithmetic<Type>::value) {
|
||||
return 90.0 - angleDeg(v - *this);
|
||||
}
|
||||
}
|
||||
//! \~english Returns the projection of this vector onto \a v.
|
||||
//! \~russian Возвращает проекцию этого вектора на \a v.
|
||||
_CVector projection(const _CVector & v) {
|
||||
static_assert(std::is_arithmetic<Type>::value, "Unavailable for complex");
|
||||
if (std::is_arithmetic<Type>::value) {
|
||||
@@ -140,6 +184,8 @@ public:
|
||||
return v * (dot(v) / tv);
|
||||
}
|
||||
}
|
||||
//! \~english Normalizes this vector in place.
|
||||
//! \~russian Нормализует этот вектор на месте.
|
||||
_CVector & normalize() {
|
||||
static_assert(std::is_arithmetic<Type>::value, "Unavailable for complex");
|
||||
if (std::is_arithmetic<Type>::value) {
|
||||
@@ -150,61 +196,101 @@ public:
|
||||
return *this;
|
||||
}
|
||||
}
|
||||
//! \~english Returns a normalized copy of this vector.
|
||||
//! \~russian Возвращает нормализованную копию этого вектора.
|
||||
_CVector normalized() {
|
||||
_CVector tv(*this);
|
||||
tv.normalize();
|
||||
return tv;
|
||||
}
|
||||
//! \~english Returns true when all coordinates are zero.
|
||||
//! \~russian Возвращает true, если все координаты равны нулю.
|
||||
bool isNull() const {
|
||||
PIMV_FOR if (c[i] != Type{}) return false;
|
||||
return true;
|
||||
}
|
||||
//! \~english Returns true when this vector is orthogonal to \a v.
|
||||
//! \~russian Возвращает true, если этот вектор ортогонален \a v.
|
||||
bool isOrtho(const _CVector & v) const { return ((*this) ^ v) == Type{}; }
|
||||
|
||||
//! \~english Returns writable access to a coordinate.
|
||||
//! \~russian Возвращает доступ на запись к координате.
|
||||
Type & operator[](uint index) { return c[index]; }
|
||||
//! \~english Returns read-only access to a coordinate.
|
||||
//! \~russian Возвращает доступ только для чтения к координате.
|
||||
const Type & operator[](uint index) const { return c[index]; }
|
||||
//! \~english Returns a coordinate by value.
|
||||
//! \~russian Возвращает координату по значению.
|
||||
Type at(uint index) const { return c[index]; }
|
||||
//! \~english Returns writable access to a coordinate.
|
||||
//! \~russian Возвращает доступ на запись к координате.
|
||||
inline Type & element(uint index) { return c[index]; }
|
||||
//! \~english Returns read-only access to a coordinate.
|
||||
//! \~russian Возвращает доступ только для чтения к координате.
|
||||
inline const Type & element(uint index) const { return c[index]; }
|
||||
|
||||
//! \~english Assigns the same value to all coordinates.
|
||||
//! \~russian Присваивает всем координатам одно и то же значение.
|
||||
_CVector & operator=(const Type & v) {
|
||||
PIMV_FOR c[i] = v;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Compares two vectors component-wise.
|
||||
//! \~russian Сравнивает два вектора покомпонентно.
|
||||
bool operator==(const _CVector & v) const {
|
||||
PIMV_FOR if (c[i] != v[i]) return false;
|
||||
return true;
|
||||
}
|
||||
//! \~english Returns true when vectors differ in at least one coordinate.
|
||||
//! \~russian Возвращает true, если векторы различаются хотя бы по одной координате.
|
||||
bool operator!=(const _CVector & v) const { return !(*this == c); }
|
||||
|
||||
//! \~english Adds \a v component-wise.
|
||||
//! \~russian Прибавляет \a v покомпонентно.
|
||||
void operator+=(const _CVector & v) { PIMV_FOR c[i] += v[i]; }
|
||||
//! \~english Subtracts \a v component-wise.
|
||||
//! \~russian Вычитает \a v покомпонентно.
|
||||
void operator-=(const _CVector & v) { PIMV_FOR c[i] -= v[i]; }
|
||||
//! \~english Multiplies all coordinates by \a v.
|
||||
//! \~russian Умножает все координаты на \a v.
|
||||
void operator*=(const Type & v) { PIMV_FOR c[i] *= v; }
|
||||
//! \~english Divides all coordinates by \a v.
|
||||
//! \~russian Делит все координаты на \a v.
|
||||
void operator/=(const Type & v) {
|
||||
assert(std::abs(v) > PIMATHVECTOR_ZERO_CMP);
|
||||
PIMV_FOR c[i] /= v;
|
||||
}
|
||||
//! \~english Returns the vector with inverted sign.
|
||||
//! \~russian Возвращает вектор с противоположным знаком.
|
||||
_CVector operator-() const {
|
||||
_CVector tv;
|
||||
PIMV_FOR tv[i] = -c[i];
|
||||
return tv;
|
||||
}
|
||||
//! \~english Returns the component-wise sum with \a v.
|
||||
//! \~russian Возвращает покомпонентную сумму с \a v.
|
||||
_CVector operator+(const _CVector & v) const {
|
||||
_CVector tv(*this);
|
||||
PIMV_FOR tv[i] += v[i];
|
||||
return tv;
|
||||
}
|
||||
//! \~english Returns the component-wise difference with \a v.
|
||||
//! \~russian Возвращает покомпонентную разность с \a v.
|
||||
_CVector operator-(const _CVector & v) const {
|
||||
_CVector tv(*this);
|
||||
PIMV_FOR tv[i] -= v[i];
|
||||
return tv;
|
||||
}
|
||||
//! \~english Returns a copy scaled by \a v.
|
||||
//! \~russian Возвращает копию, масштабированную на \a v.
|
||||
_CVector operator*(const Type & v) const {
|
||||
_CVector tv(*this);
|
||||
PIMV_FOR tv[i] *= v;
|
||||
return tv;
|
||||
}
|
||||
//! \~english Returns a copy divided by \a v.
|
||||
//! \~russian Возвращает копию, поделенную на \a v.
|
||||
_CVector operator/(const Type & v) const {
|
||||
assert(std::abs(v) > PIMATHVECTOR_ZERO_CMP);
|
||||
_CVector tv = _CVector(*this);
|
||||
@@ -212,6 +298,8 @@ public:
|
||||
return tv;
|
||||
}
|
||||
|
||||
//! \~english Returns the 3D cross product with \a v.
|
||||
//! \~russian Возвращает 3D-векторное произведение с \a v.
|
||||
_CVector cross(const _CVector & v) const {
|
||||
static_assert(Size == 3, "cross product avalible only for 3D vectors");
|
||||
_CVector tv;
|
||||
@@ -220,17 +308,25 @@ public:
|
||||
tv[2] = c[0] * v[1] - v[0] * c[1];
|
||||
return tv;
|
||||
}
|
||||
//! \~english Returns the scalar product with \a v.
|
||||
//! \~russian Возвращает скалярное произведение с \a v.
|
||||
Type dot(const _CVector & v) const {
|
||||
Type tv{};
|
||||
PIMV_FOR tv += c[i] * v[i];
|
||||
return tv;
|
||||
}
|
||||
//! \~english Returns the component-wise product with \a v.
|
||||
//! \~russian Возвращает покомпонентное произведение с \a v.
|
||||
_CVector mul(const _CVector & v) const {
|
||||
_CVector tv(*this);
|
||||
PIMV_FOR tv[i] *= v[i];
|
||||
return tv;
|
||||
}
|
||||
//! \~english Returns a copy scaled by \a v.
|
||||
//! \~russian Возвращает копию, масштабированную на \a v.
|
||||
_CVector mul(const Type & v) const { return (*this) * v; }
|
||||
//! \~english Returns the component-wise division by \a v.
|
||||
//! \~russian Возвращает покомпонентное деление на \a v.
|
||||
_CVector div(const _CVector & v) const {
|
||||
_CVector tv(*this);
|
||||
PIMV_FOR {
|
||||
@@ -239,14 +335,20 @@ public:
|
||||
}
|
||||
return tv;
|
||||
}
|
||||
//! \~english Returns a copy divided by \a v.
|
||||
//! \~russian Возвращает копию, поделенную на \a v.
|
||||
_CVector div(const Type & v) const { return (*this) / v; }
|
||||
|
||||
//! \~english Returns the vector as a 1 x Size matrix.
|
||||
//! \~russian Возвращает вектор как матрицу 1 x Size.
|
||||
PIMathMatrixT<1, Size, Type> transposed() const {
|
||||
PIMathMatrixT<1, Size, Type> ret;
|
||||
PIMV_FOR ret[0][i] = c[i];
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! \~english Returns the distance from this 2D point to the line through \a lp0 and \a lp1.
|
||||
//! \~russian Возвращает расстояние от этой 2D-точки до прямой через \a lp0 и \a lp1.
|
||||
Type distToLine(const _CVector & lp0, const _CVector & lp1) {
|
||||
static_assert(std::is_arithmetic<Type>::value, "Unavailable for complex");
|
||||
if (std::is_arithmetic<Type>::value) {
|
||||
@@ -258,7 +360,9 @@ public:
|
||||
}
|
||||
}
|
||||
|
||||
template<uint Size1, typename Type1> /// vector {Size, Type} to vector {Size1, Type1}
|
||||
//! \~english Converts this vector to another dimension and element type.
|
||||
//! \~russian Преобразует этот вектор к другой размерности и типу элементов.
|
||||
template<uint Size1, typename Type1>
|
||||
PIMathVectorT<Size1, Type1> turnTo() const {
|
||||
PIMathVectorT<Size1, Type1> tv;
|
||||
uint sz = piMin<uint>(Size, Size1);
|
||||
@@ -267,10 +371,8 @@ public:
|
||||
return tv;
|
||||
}
|
||||
|
||||
//! \~english
|
||||
//! \brief Returns this vector with another element type.
|
||||
//! \~russian
|
||||
//! \brief Возвращает этот вектор с другим типом элементов.
|
||||
//! \~english Returns this vector with another element type.
|
||||
//! \~russian Возвращает этот вектор с другим типом элементов.
|
||||
template<typename T>
|
||||
PIMathVectorT<Size, T> toType() const {
|
||||
PIMathVectorT<Size, T> ret;
|
||||
@@ -278,13 +380,8 @@ public:
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! \~english
|
||||
//! \brief Returns the subvector with size SubSize. Elements takes from coordinates "offset".
|
||||
//! \details
|
||||
//! \~russian
|
||||
//! \brief Возвращает подвектор с размерами SubSize. Элементы берутся с координат "offset".
|
||||
//! \details Координаты могут быть отрицательными. Возвращаемый подвектор может быть любого размера. Если исходные элементы выходят
|
||||
//! за границы исходного подвектора, то в подвекторе будут нули.
|
||||
//! \~english Returns a subvector starting at \a offset and zero-fills coordinates outside the source range.
|
||||
//! \~russian Возвращает подвектор, начиная с \a offset, и заполняет нулями координаты вне исходного диапазона.
|
||||
template<uint SubSize>
|
||||
PIMathVectorT<SubSize, Type> subvector(int offset = 0) const {
|
||||
PIMathVectorT<SubSize, Type> ret;
|
||||
@@ -296,14 +393,8 @@ public:
|
||||
return ret;
|
||||
}
|
||||
|
||||
//! \~english
|
||||
//! \brief Set the subvector "v" in coordinates "index".
|
||||
//! \details
|
||||
//! \~russian
|
||||
//! \brief Устанавливает подвектор "v" в координаты "index".
|
||||
//! \details Присваивает значения из вектора "v" в область текущиего вектора, ограниченную
|
||||
//! размерами "v", самого вектор и границами, исходя из координат установки. Координаты могут быть отрицательными.
|
||||
//! Вектор "v" может быть любого размера. Возвращает ссылку на этот вектор.
|
||||
//! \~english Writes \a v into this vector starting at \a index and ignores coordinates outside the destination range.
|
||||
//! \~russian Записывает \a v в этот вектор, начиная с \a index, и игнорирует координаты вне диапазона назначения.
|
||||
template<uint SubSize>
|
||||
PIMathVectorT<Size, Type> & setSubvector(int index, const PIMathVectorT<SubSize, Type> & v) {
|
||||
for (int i = 0; i < (int)SubSize; ++i) {
|
||||
@@ -314,23 +405,41 @@ public:
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Returns the cross product of \a v1 and \a v2.
|
||||
//! \~russian Возвращает векторное произведение \a v1 и \a v2.
|
||||
static _CVector cross(const _CVector & v1, const _CVector & v2) { return v1.cross(v2); }
|
||||
//! \~english Returns the scalar product of \a v1 and \a v2.
|
||||
//! \~russian Возвращает скалярное произведение \a v1 и \a v2.
|
||||
static Type dot(const _CVector & v1, const _CVector & v2) { return v1.dot(v2); }
|
||||
//! \~english Returns the component-wise product of \a v1 and \a v2.
|
||||
//! \~russian Возвращает покомпонентное произведение \a v1 и \a v2.
|
||||
static _CVector mul(const _CVector & v1, const _CVector & v2) { return v1.mul(v2); }
|
||||
//! \~english Returns \a v2 scaled by \a v1.
|
||||
//! \~russian Возвращает \a v2, масштабированный на \a v1.
|
||||
static _CVector mul(const Type & v1, const _CVector & v2) { return v2 * v1; }
|
||||
//! \~english Returns \a v1 scaled by \a v2.
|
||||
//! \~russian Возвращает \a v1, масштабированный на \a v2.
|
||||
static _CVector mul(const _CVector & v1, const Type & v2) { return v1 * v2; }
|
||||
//! \~english Returns the component-wise division of \a v1 by \a v2.
|
||||
//! \~russian Возвращает покомпонентное деление \a v1 на \a v2.
|
||||
static _CVector div(const _CVector & v1, const _CVector & v2) { return v1.div(v2); }
|
||||
//! \~english Returns \a v1 divided by scalar \a v2.
|
||||
//! \~russian Возвращает \a v1, поделенный на скаляр \a v2.
|
||||
static _CVector div(const _CVector & v1, const Type & v2) { return v1 / v2; }
|
||||
|
||||
private:
|
||||
Type c[Size];
|
||||
};
|
||||
|
||||
//! \~english Multiplies a fixed-size vector by a scalar from the left.
|
||||
//! \~russian Умножает вектор фиксированного размера на скаляр слева.
|
||||
template<uint Size, typename Type>
|
||||
inline PIMathVectorT<Size, Type> operator*(const Type & x, const PIMathVectorT<Size, Type> & v) {
|
||||
return v * x;
|
||||
}
|
||||
|
||||
//! \~english Writes a fixed-size vector to \a PICout.
|
||||
//! \~russian Записывает вектор фиксированного размера в \a PICout.
|
||||
template<uint Size, typename Type>
|
||||
inline PICout operator<<(PICout s, const PIMathVectorT<Size, Type> & v) {
|
||||
s.space();
|
||||
@@ -345,21 +454,41 @@ inline PICout operator<<(PICout s, const PIMathVectorT<Size, Type> & v) {
|
||||
return s;
|
||||
}
|
||||
|
||||
|
||||
//! \~english Two-dimensional fixed-size vector of \c int.
|
||||
//! \~russian Двумерный вектор фиксированного размера из \c int.
|
||||
typedef PIMathVectorT<2u, int> PIMathVectorT2i;
|
||||
//! \~english Three-dimensional fixed-size vector of \c int.
|
||||
//! \~russian Трехмерный вектор фиксированного размера из \c int.
|
||||
typedef PIMathVectorT<3u, int> PIMathVectorT3i;
|
||||
//! \~english Four-dimensional fixed-size vector of \c int.
|
||||
//! \~russian Четырехмерный вектор фиксированного размера из \c int.
|
||||
typedef PIMathVectorT<4u, int> PIMathVectorT4i;
|
||||
//! \~english Two-dimensional fixed-size vector of \c double.
|
||||
//! \~russian Двумерный вектор фиксированного размера из \c double.
|
||||
typedef PIMathVectorT<2u, double> PIMathVectorT2d;
|
||||
//! \~english Three-dimensional fixed-size vector of \c double.
|
||||
//! \~russian Трехмерный вектор фиксированного размера из \c double.
|
||||
typedef PIMathVectorT<3u, double> PIMathVectorT3d;
|
||||
//! \~english Four-dimensional fixed-size vector of \c double.
|
||||
//! \~russian Четырехмерный вектор фиксированного размера из \c double.
|
||||
typedef PIMathVectorT<4u, double> PIMathVectorT4d;
|
||||
|
||||
|
||||
#undef PIMV_FOR
|
||||
|
||||
/// Vector
|
||||
|
||||
#define PIMV_FOR for (uint i = 0; i < c.size(); ++i)
|
||||
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english Template class for dynamic-size mathematical vector
|
||||
//! \~russian Шаблонный класс для математического вектора динамического размера
|
||||
//! \details
|
||||
//! \~english Provides vector operations including arithmetic, normalization, angles, cross product, and dot product for dynamic-size
|
||||
//! vectors
|
||||
//! \~russian Предоставляет операции вектора включая арифметику, нормализацию, углы, векторное произведение и скалярное произведение для
|
||||
//! векторов динамического размера
|
||||
//! \tparam Type The element type (arithmetic or complex)
|
||||
template<typename Type>
|
||||
class PIP_EXPORT PIMathVector {
|
||||
typedef PIMathVector<Type> _CVector;
|
||||
@@ -369,17 +498,29 @@ class PIP_EXPORT PIMathVector {
|
||||
friend PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIMathVector<Type1> & v);
|
||||
|
||||
public:
|
||||
//! \~english Constructs a vector of \a size elements initialized with \a new_value.
|
||||
//! \~russian Создает вектор из \a size элементов, инициализированных значением \a new_value.
|
||||
PIMathVector(const uint size = 0, const Type & new_value = Type()) { c.resize(size, new_value); }
|
||||
//! \~english Constructs a vector from a raw \a PIVector.
|
||||
//! \~russian Создает вектор из контейнера \a PIVector.
|
||||
PIMathVector(const PIVector<Type> & val) { c = val; }
|
||||
//! \~english Move-constructs a vector from a raw \a PIVector.
|
||||
//! \~russian Создает вектор перемещением из контейнера \a PIVector.
|
||||
PIMathVector(PIVector<Type> && val): c(std::move(val)) {}
|
||||
//! \~english Constructs a vector from an initializer list.
|
||||
//! \~russian Создает вектор из списка инициализации.
|
||||
PIMathVector(std::initializer_list<Type> init_list) { c = PIVector<Type>(init_list); }
|
||||
|
||||
//! \~english Constructs a dynamic vector from a fixed-size one.
|
||||
//! \~russian Создает динамический вектор из вектора фиксированного размера.
|
||||
template<uint Size>
|
||||
PIMathVector(const PIMathVectorT<Size, Type> & val) {
|
||||
c.resize(Size);
|
||||
PIMV_FOR c[i] = val[i];
|
||||
}
|
||||
|
||||
//! \~english Builds the displacement vector from point \a st to point \a fn.
|
||||
//! \~russian Строит вектор смещения от точки \a st к точке \a fn.
|
||||
static PIMathVector fromTwoPoints(const _CVector & st, const _CVector & fn) {
|
||||
assert(st.size() == fn.size());
|
||||
_CVector v(st.size());
|
||||
@@ -387,8 +528,14 @@ public:
|
||||
v.c[i] = fn[i] - st[i];
|
||||
}
|
||||
|
||||
//! \~english Returns a vector of \a size zeros.
|
||||
//! \~russian Возвращает вектор из \a size нулей.
|
||||
static PIMathVector zeros(const uint size) { return PIMathVector(size, Type()); }
|
||||
//! \~english Returns a vector of \a size ones.
|
||||
//! \~russian Возвращает вектор из \a size единиц.
|
||||
static PIMathVector ones(const uint size) { return PIMathVector(size, Type(1)); }
|
||||
//! \~english Returns a vector filled by the arithmetic progression [\a start, \a stop) with step \a step.
|
||||
//! \~russian Возвращает вектор, заполненный арифметической прогрессией [\a start, \a stop) с шагом \a step.
|
||||
static PIMathVector arange(const Type start, const Type stop, const Type step = Type(1)) {
|
||||
PIVector<Type> v;
|
||||
for (Type i = start; i < stop; i += step)
|
||||
@@ -396,63 +543,95 @@ public:
|
||||
return PIMathVector(std::move(v));
|
||||
}
|
||||
|
||||
//! \~english Returns the current vector size.
|
||||
//! \~russian Возвращает текущий размер вектора.
|
||||
uint size() const { return c.size(); }
|
||||
//! \~english Resizes the vector and fills new coordinates with \a new_value.
|
||||
//! \~russian Изменяет размер вектора и заполняет новые координаты значением \a new_value.
|
||||
_CVector & resize(uint size, const Type & new_value = Type()) {
|
||||
c.resize(size, new_value);
|
||||
return *this;
|
||||
}
|
||||
//! \~english Returns a resized copy of this vector.
|
||||
//! \~russian Возвращает копию этого вектора с другим размером.
|
||||
_CVector resized(uint size, const Type & new_value = Type()) {
|
||||
_CVector tv = _CVector(*this);
|
||||
tv.resize(size, new_value);
|
||||
return tv;
|
||||
}
|
||||
//! \~english Fills all coordinates with \a v.
|
||||
//! \~russian Заполняет все координаты значением \a v.
|
||||
_CVector & fill(const Type & v) {
|
||||
c.fill(v);
|
||||
return *this;
|
||||
}
|
||||
//! \~english Adds \a v to every coordinate.
|
||||
//! \~russian Прибавляет \a v к каждой координате.
|
||||
_CVector & move(const Type & v) {
|
||||
PIMV_FOR c[i] += v;
|
||||
return *this;
|
||||
}
|
||||
//! \~english Adds another vector component-wise.
|
||||
//! \~russian Прибавляет другой вектор покомпонентно.
|
||||
_CVector & move(const _CVector & v) {
|
||||
assert(c.size() == v.size());
|
||||
PIMV_FOR c[i] += v[i];
|
||||
return *this;
|
||||
}
|
||||
//! \~english Swaps two coordinates in place.
|
||||
//! \~russian Меняет местами две координаты.
|
||||
_CVector & swapElements(uint f, uint s) {
|
||||
piSwap<Type>(c[f], c[s]);
|
||||
return *this;
|
||||
}
|
||||
//! \~english Returns the squared Euclidean length.
|
||||
//! \~russian Возвращает квадрат евклидовой длины.
|
||||
Type lengthSqr() const {
|
||||
Type tv(0);
|
||||
PIMV_FOR tv += c[i] * c[i];
|
||||
return tv;
|
||||
}
|
||||
//! \~english Returns the Euclidean length.
|
||||
//! \~russian Возвращает евклидову длину.
|
||||
Type length() const { return std::sqrt(lengthSqr()); }
|
||||
//! \~english Returns the Manhattan length.
|
||||
//! \~russian Возвращает манхэттенскую длину.
|
||||
Type manhattanLength() const {
|
||||
Type tv(0);
|
||||
PIMV_FOR tv += piAbs<Type>(c[i]);
|
||||
return tv;
|
||||
}
|
||||
//! \~english Returns the cosine of the angle to \a v.
|
||||
//! \~russian Возвращает косинус угла к вектору \a v.
|
||||
Type angleCos(const _CVector & v) const {
|
||||
assert(c.size() == v.size());
|
||||
Type tv = v.length() * length();
|
||||
assert(std::abs(tv) > PIMATHVECTOR_ZERO_CMP);
|
||||
return dot(v) / tv;
|
||||
}
|
||||
//! \~english Returns the sine of the angle to \a v.
|
||||
//! \~russian Возвращает синус угла к вектору \a v.
|
||||
Type angleSin(const _CVector & v) const {
|
||||
assert(c.size() == v.size());
|
||||
Type tv = angleCos(v);
|
||||
return std::sqrt(Type(1) - tv * tv);
|
||||
}
|
||||
//! \~english Returns the angle to \a v in radians.
|
||||
//! \~russian Возвращает угол к вектору \a v в радианах.
|
||||
Type angleRad(const _CVector & v) const { return std::acos(angleCos(v)); }
|
||||
//! \~english Returns the angle to \a v in degrees.
|
||||
//! \~russian Возвращает угол к вектору \a v в градусах.
|
||||
Type angleDeg(const _CVector & v) const { return toDeg(angleRad(v)); }
|
||||
//! \~english Returns the projection of this vector onto \a v.
|
||||
//! \~russian Возвращает проекцию этого вектора на \a v.
|
||||
_CVector projection(const _CVector & v) {
|
||||
assert(c.size() == v.size());
|
||||
Type tv = v.length();
|
||||
assert(std::abs(tv) > PIMATHVECTOR_ZERO_CMP);
|
||||
return v * (dot(v) / tv);
|
||||
}
|
||||
//! \~english Normalizes this vector in place.
|
||||
//! \~russian Нормализует этот вектор на месте.
|
||||
_CVector & normalize() {
|
||||
Type tv = length();
|
||||
assert(std::abs(tv) > PIMATHVECTOR_ZERO_CMP);
|
||||
@@ -460,71 +639,111 @@ public:
|
||||
PIMV_FOR c[i] /= tv;
|
||||
return *this;
|
||||
}
|
||||
//! \~english Returns a normalized copy of this vector.
|
||||
//! \~russian Возвращает нормализованную копию этого вектора.
|
||||
_CVector normalized() {
|
||||
_CVector tv(*this);
|
||||
tv.normalize();
|
||||
return tv;
|
||||
}
|
||||
//! \~english Returns true when all coordinates are zero.
|
||||
//! \~russian Возвращает true, если все координаты равны нулю.
|
||||
bool isNull() const {
|
||||
PIMV_FOR if (c[i] != Type(0)) return false;
|
||||
return true;
|
||||
}
|
||||
//! \~english Returns true when the vector contains allocated storage.
|
||||
//! \~russian Возвращает true, если у вектора есть выделенное хранилище.
|
||||
bool isValid() const { return !c.isEmpty(); }
|
||||
//! \~english Returns true when this vector is orthogonal to \a v.
|
||||
//! \~russian Возвращает true, если этот вектор ортогонален \a v.
|
||||
bool isOrtho(const _CVector & v) const { return dot(v) == Type(0); }
|
||||
|
||||
//! \~english Returns writable access to a coordinate.
|
||||
//! \~russian Возвращает доступ на запись к координате.
|
||||
Type & operator[](uint index) { return c[index]; }
|
||||
//! \~english Returns read-only access to a coordinate.
|
||||
//! \~russian Возвращает доступ только для чтения к координате.
|
||||
const Type & operator[](uint index) const { return c[index]; }
|
||||
//! \~english Returns a coordinate by value.
|
||||
//! \~russian Возвращает координату по значению.
|
||||
Type at(uint index) const { return c[index]; }
|
||||
|
||||
//! \~english Assigns the same value to all coordinates.
|
||||
//! \~russian Присваивает всем координатам одно и то же значение.
|
||||
_CVector & operator=(const Type & v) {
|
||||
PIMV_FOR c[i] = v;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Compares two vectors component-wise.
|
||||
//! \~russian Сравнивает два вектора покомпонентно.
|
||||
bool operator==(const _CVector & v) const { return c == v.c; }
|
||||
//! \~english Returns true when vectors differ in at least one coordinate.
|
||||
//! \~russian Возвращает true, если векторы различаются хотя бы по одной координате.
|
||||
bool operator!=(const _CVector & v) const { return c != v.c; }
|
||||
|
||||
//! \~english Adds \a v component-wise.
|
||||
//! \~russian Прибавляет \a v покомпонентно.
|
||||
void operator+=(const _CVector & v) {
|
||||
assert(c.size() == v.size());
|
||||
PIMV_FOR c[i] += v[i];
|
||||
}
|
||||
//! \~english Subtracts \a v component-wise.
|
||||
//! \~russian Вычитает \a v покомпонентно.
|
||||
void operator-=(const _CVector & v) {
|
||||
assert(c.size() == v.size());
|
||||
PIMV_FOR c[i] -= v[i];
|
||||
}
|
||||
//! \~english Multiplies all coordinates by \a v.
|
||||
//! \~russian Умножает все координаты на \a v.
|
||||
void operator*=(const Type & v) { PIMV_FOR c[i] *= v; }
|
||||
//! \~english Divides all coordinates by \a v.
|
||||
//! \~russian Делит все координаты на \a v.
|
||||
void operator/=(const Type & v) {
|
||||
assert(std::abs(v) > PIMATHVECTOR_ZERO_CMP);
|
||||
PIMV_FOR c[i] /= v;
|
||||
}
|
||||
//! \~english Returns the vector with inverted sign.
|
||||
//! \~russian Возвращает вектор с противоположным знаком.
|
||||
_CVector operator-() const {
|
||||
_CVector tv(c.size());
|
||||
PIMV_FOR tv[i] = -c[i];
|
||||
return tv;
|
||||
}
|
||||
//! \~english Returns the component-wise sum with \a v.
|
||||
//! \~russian Возвращает покомпонентную сумму с \a v.
|
||||
_CVector operator+(const _CVector & v) const {
|
||||
assert(c.size() == v.size());
|
||||
_CVector tv(*this);
|
||||
PIMV_FOR tv[i] += v[i];
|
||||
return tv;
|
||||
}
|
||||
//! \~english Returns the component-wise difference with \a v.
|
||||
//! \~russian Возвращает покомпонентную разность с \a v.
|
||||
_CVector operator-(const _CVector & v) const {
|
||||
assert(c.size() == v.size());
|
||||
_CVector tv(*this);
|
||||
PIMV_FOR tv[i] -= v[i];
|
||||
return tv;
|
||||
}
|
||||
//! \~english Returns a copy scaled by \a v.
|
||||
//! \~russian Возвращает копию, масштабированную на \a v.
|
||||
_CVector operator*(const Type & v) const {
|
||||
_CVector tv(*this);
|
||||
PIMV_FOR tv[i] *= v;
|
||||
return tv;
|
||||
}
|
||||
//! \~english Returns a copy divided by \a v.
|
||||
//! \~russian Возвращает копию, поделенную на \a v.
|
||||
_CVector operator/(const Type & v) const {
|
||||
assert(std::abs(v) > PIMATHVECTOR_ZERO_CMP);
|
||||
_CVector tv(*this);
|
||||
PIMV_FOR tv[i] /= v;
|
||||
return tv;
|
||||
}
|
||||
//! \~english Returns the 3D cross product with \a v.
|
||||
//! \~russian Возвращает 3D-векторное произведение с \a v.
|
||||
_CVector cross(const _CVector & v) const {
|
||||
assert(c.size() == 3);
|
||||
assert(v.size() == 3);
|
||||
@@ -534,19 +753,27 @@ public:
|
||||
tv[2] = c[0] * v[1] - v[0] * c[1];
|
||||
return tv;
|
||||
}
|
||||
//! \~english Returns the scalar product with \a v.
|
||||
//! \~russian Возвращает скалярное произведение с \a v.
|
||||
Type dot(const _CVector & v) const {
|
||||
assert(c.size() == v.size());
|
||||
Type tv(0);
|
||||
PIMV_FOR tv += c[i] * v[i];
|
||||
return tv;
|
||||
}
|
||||
//! \~english Returns the component-wise product with \a v.
|
||||
//! \~russian Возвращает покомпонентное произведение с \a v.
|
||||
_CVector mul(const _CVector & v) const {
|
||||
assert(c.size() == v.size());
|
||||
_CVector tv(*this);
|
||||
PIMV_FOR tv[i] *= v[i];
|
||||
return tv;
|
||||
}
|
||||
//! \~english Returns a copy scaled by \a v.
|
||||
//! \~russian Возвращает копию, масштабированную на \a v.
|
||||
_CVector mul(const Type & v) const { return (*this) * v; }
|
||||
//! \~english Returns the component-wise division by \a v.
|
||||
//! \~russian Возвращает покомпонентное деление на \a v.
|
||||
_CVector div(const _CVector & v) const {
|
||||
assert(c.size() == v.size());
|
||||
_CVector tv(*this);
|
||||
@@ -556,8 +783,12 @@ public:
|
||||
}
|
||||
return tv;
|
||||
}
|
||||
//! \~english Returns a copy divided by \a v.
|
||||
//! \~russian Возвращает копию, поделенную на \a v.
|
||||
_CVector div(const Type & v) const { return (*this) / v; }
|
||||
|
||||
//! \~english Returns the distance from this 2D point to the line through \a lp0 and \a lp1.
|
||||
//! \~russian Возвращает расстояние от этой 2D-точки до прямой через \a lp0 и \a lp1.
|
||||
Type distToLine(const _CVector & lp0, const _CVector & lp1) {
|
||||
assert(c.size() == lp0.size());
|
||||
assert(c.size() == lp1.size());
|
||||
@@ -568,30 +799,56 @@ public:
|
||||
return piAbs<Type>(a[0] * b[1] - a[1] * b[0]) / tv;
|
||||
}
|
||||
|
||||
//! \~english Returns the underlying \a PIVector copy.
|
||||
//! \~russian Возвращает копию базового контейнера \a PIVector.
|
||||
PIVector<Type> toVector() const { return c; }
|
||||
|
||||
//! \~english Applies \a f to every coordinate without modifying the vector.
|
||||
//! \~russian Применяет \a f к каждой координате без изменения вектора.
|
||||
void forEach(std::function<void(const Type &)> f) const { c.forEach(f); }
|
||||
//! \~english Applies \a f to every coordinate and returns this vector.
|
||||
//! \~russian Применяет \a f к каждой координате и возвращает этот вектор.
|
||||
_CVector & forEach(std::function<void(Type &)> f) {
|
||||
c.forEach(f);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Returns a writable pointer to contiguous vector data.
|
||||
//! \~russian Возвращает указатель на непрерывные данные вектора для записи.
|
||||
inline Type * data() { return c.data(); }
|
||||
//! \~english Returns a read-only pointer to contiguous vector data.
|
||||
//! \~russian Возвращает указатель на непрерывные данные вектора только для чтения.
|
||||
inline const Type * data() const { return c.data(); }
|
||||
|
||||
|
||||
//! \~english Returns the cross product of \a v1 and \a v2.
|
||||
//! \~russian Возвращает векторное произведение \a v1 и \a v2.
|
||||
static _CVector cross(const _CVector & v1, const _CVector & v2) { return v1.cross(v2); }
|
||||
//! \~english Returns the scalar product of \a v1 and \a v2.
|
||||
//! \~russian Возвращает скалярное произведение \a v1 и \a v2.
|
||||
static Type dot(const _CVector & v1, const _CVector & v2) { return v1.dot(v2); }
|
||||
//! \~english Returns the component-wise product of \a v1 and \a v2.
|
||||
//! \~russian Возвращает покомпонентное произведение \a v1 и \a v2.
|
||||
static _CVector mul(const _CVector & v1, const _CVector & v2) { return v1.mul(v2); }
|
||||
//! \~english Returns \a v2 scaled by \a v1.
|
||||
//! \~russian Возвращает \a v2, масштабированный на \a v1.
|
||||
static _CVector mul(const Type & v1, const _CVector & v2) { return v2 * v1; }
|
||||
//! \~english Returns \a v1 scaled by \a v2.
|
||||
//! \~russian Возвращает \a v1, масштабированный на \a v2.
|
||||
static _CVector mul(const _CVector & v1, const Type & v2) { return v1 * v2; }
|
||||
//! \~english Returns the component-wise division of \a v1 by \a v2.
|
||||
//! \~russian Возвращает покомпонентное деление \a v1 на \a v2.
|
||||
static _CVector div(const _CVector & v1, const _CVector & v2) { return v1.div(v2); }
|
||||
//! \~english Returns \a v1 divided by scalar \a v2.
|
||||
//! \~russian Возвращает \a v1, поделенный на скаляр \a v2.
|
||||
static _CVector div(const _CVector & v1, const Type & v2) { return v1 / v2; }
|
||||
|
||||
private:
|
||||
PIVector<Type> c;
|
||||
};
|
||||
|
||||
//! \~english Multiplies a dynamic vector by a scalar from the left.
|
||||
//! \~russian Умножает динамический вектор на скаляр слева.
|
||||
template<typename Type>
|
||||
inline PIMathVector<Type> operator*(const Type & x, const PIMathVector<Type> & v) {
|
||||
return v * x;
|
||||
@@ -612,6 +869,8 @@ inline std::ostream & operator<<(std::ostream & s, const PIMathVector<Type> & v)
|
||||
}
|
||||
#endif
|
||||
|
||||
//! \~english Writes a dynamic vector to \a PICout.
|
||||
//! \~russian Записывает динамический вектор в \a PICout.
|
||||
template<typename Type>
|
||||
inline PICout operator<<(PICout s, const PIMathVector<Type> & v) {
|
||||
s.space();
|
||||
@@ -626,11 +885,15 @@ inline PICout operator<<(PICout s, const PIMathVector<Type> & v) {
|
||||
return s;
|
||||
}
|
||||
|
||||
//! \~english Serializes a dynamic vector into a \a PIBinaryStream.
|
||||
//! \~russian Сериализует динамический вектор в \a PIBinaryStream.
|
||||
template<typename P, typename T>
|
||||
inline PIBinaryStream<P> & operator<<(PIBinaryStream<P> & s, const PIMathVector<T> & v) {
|
||||
s << v.c;
|
||||
return s;
|
||||
}
|
||||
//! \~english Deserializes a dynamic vector from a \a PIBinaryStream.
|
||||
//! \~russian Десериализует динамический вектор из \a PIBinaryStream.
|
||||
template<typename P, typename T>
|
||||
inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIMathVector<T> & v) {
|
||||
s >> v.c;
|
||||
@@ -638,7 +901,11 @@ inline PIBinaryStream<P> & operator>>(PIBinaryStream<P> & s, PIMathVector<T> & v
|
||||
}
|
||||
|
||||
|
||||
//! \~english Dynamic vector of \c int.
|
||||
//! \~russian Динамический вектор из \c int.
|
||||
typedef PIMathVector<int> PIMathVectori;
|
||||
//! \~english Dynamic vector of \c double.
|
||||
//! \~russian Динамический вектор из \c double.
|
||||
typedef PIMathVector<double> PIMathVectord;
|
||||
|
||||
#endif // PIMATHVECTOR_H
|
||||
|
||||
@@ -1,8 +1,8 @@
|
||||
//! \file pipoint.h
|
||||
//! \ingroup Math
|
||||
//! \brief
|
||||
//! \~english Two-dimensional point class
|
||||
//! \~russian Класс двумерной точки
|
||||
//! \~\file pipoint.h
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english The PIPoint class provides a two-dimensional point on the plane.
|
||||
//! \~russian Класс PIPoint представляет точку на плоскости с двумя координатами.
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Two-dimensional point class
|
||||
@@ -24,154 +24,185 @@
|
||||
#include "pimathbase.h"
|
||||
|
||||
|
||||
//! \brief
|
||||
//! \~english Two-dimensional point class
|
||||
//! \~russian Класс двумерной точки
|
||||
//! \details
|
||||
//! Данный класс позволяет хранить и работать с двумерными точками.
|
||||
//! Для работы с объектами реализованы операторы сложения, вычитания и проверки на ревенство и неравенство.
|
||||
//! Также доступны методы для перемещения точек \a translate(), \a translated(), \a move(), \a moved()
|
||||
//! и перевода из декартовой системы координат в полярную \a toPolar() и обратно \a fromPolar().
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english Two-dimensional point.
|
||||
//! \~russian Двумерная точка.
|
||||
//! \~\details
|
||||
//! \~english Stores point coordinates and provides basic translation and conversion helpers.
|
||||
//! \~russian Хранит координаты точки и предоставляет базовые методы смещения и преобразования.
|
||||
template<typename Type>
|
||||
class PIP_EXPORT PIPoint {
|
||||
static_assert(std::is_arithmetic<Type>::value, "Type must be arithmetic");
|
||||
|
||||
public:
|
||||
//! \~english Horizontal coordinate.
|
||||
//! \~russian Горизонтальная координата.
|
||||
Type x;
|
||||
|
||||
//! \~english Vertical coordinate.
|
||||
//! \~russian Вертикальная координата.
|
||||
Type y;
|
||||
|
||||
//! \~russian Создает новую точку.
|
||||
//! \~english Constructs point at the origin.
|
||||
//! \~russian Создает точку в начале координат.
|
||||
PIPoint() { x = y = Type(); }
|
||||
|
||||
//! \~russian Создает новую точку с заданными координатами.
|
||||
//! \~english Constructs point from coordinates.
|
||||
//! \~russian Создает точку с заданными координатами.
|
||||
PIPoint(Type x_, Type y_) { set(x_, y_); }
|
||||
|
||||
//! \~russian Задать новые координаты точке.
|
||||
//! \~english Sets point coordinates.
|
||||
//! \~russian Задает координаты точки.
|
||||
PIPoint<Type> & set(Type x_, Type y_) {
|
||||
x = x_;
|
||||
y = y_;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~russian Задать новые координаты точке.
|
||||
//! \~english Copies coordinates from another point.
|
||||
//! \~russian Копирует координаты из другой точки.
|
||||
PIPoint<Type> & set(const PIPoint<Type> & p) {
|
||||
x = p.x;
|
||||
y = p.y;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~russian Переместить точку.
|
||||
//! \~english Shifts the point by `x_` and `y_`.
|
||||
//! \~russian Сдвигает точку на `x_` и `y_`.
|
||||
PIPoint<Type> & translate(Type x_, Type y_) {
|
||||
x += x_;
|
||||
y += y_;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~russian Переместить точку.
|
||||
//! \~english Shifts the point by another point.
|
||||
//! \~russian Сдвигает точку на координаты другой точки.
|
||||
PIPoint<Type> & translate(const PIPoint<Type> & p) {
|
||||
x += p.x;
|
||||
y += p.y;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~russian Создать копию точки и переместить её.
|
||||
//! \~english Returns translated copy of the point.
|
||||
//! \~russian Возвращает смещенную копию точки.
|
||||
PIPoint<Type> translated(Type x_, Type y_) const {
|
||||
PIPoint<Type> rp(*this);
|
||||
rp.translate(x_, y_);
|
||||
return rp;
|
||||
}
|
||||
|
||||
//! \~russian Создать копию точки и переместить её.
|
||||
//! \~english Returns copy shifted by another point.
|
||||
//! \~russian Возвращает копию, смещенную на другую точку.
|
||||
PIPoint<Type> translated(const PIPoint<Type> & p) const {
|
||||
PIPoint<Type> rp(*this);
|
||||
rp.translate(p);
|
||||
return rp;
|
||||
}
|
||||
|
||||
//! \~russian Переместить точку.
|
||||
//! \details Является копией метода \a translate().
|
||||
//! \~english Same as \a translate().
|
||||
//! \~russian Синоним \a translate().
|
||||
PIPoint<Type> & move(Type x_, Type y_) { return translate(x_, y_); }
|
||||
|
||||
//! \~russian Переместить точку.
|
||||
//! \details Является копией метода \a translate().
|
||||
//! \~english Same as \a translate().
|
||||
//! \~russian Синоним \a translate().
|
||||
PIPoint<Type> & move(const PIPoint<Type> & p) { return translate(p); }
|
||||
|
||||
//! \~russian Создать копию точки и переместить её.
|
||||
//! \details Является копией метода \a translated().
|
||||
//! \~english Same as \a translated().
|
||||
//! \~russian Синоним \a translated().
|
||||
PIPoint<Type> moved(Type x_, Type y_) const {
|
||||
PIPoint<Type> rp(*this);
|
||||
rp.translate(x_, y_);
|
||||
return rp;
|
||||
}
|
||||
|
||||
//! \~russian Создать копию точки и переместить её.
|
||||
//! \details Является копией метода \a translated().
|
||||
//! \~english Same as \a translated().
|
||||
//! \~russian Синоним \a translated().
|
||||
PIPoint<Type> moved(const PIPoint<Type> & p) const {
|
||||
PIPoint<Type> rp(*this);
|
||||
rp.translate(p);
|
||||
return rp;
|
||||
}
|
||||
|
||||
//! \~russian Посчитать угол(радианы) в поолярной системе координат.
|
||||
//! \~english Returns polar angle in radians.
|
||||
//! \~russian Возвращает полярный угол в радианах.
|
||||
double angleRad() const { return atan2(y, x); }
|
||||
|
||||
//! \~russian Посчитать угол(градусы) в поолярной системе координат.
|
||||
//! \~english Returns polar angle in degrees.
|
||||
//! \~russian Возвращает полярный угол в градусах.
|
||||
double angleDeg() const { return toDeg(atan2(y, x)); }
|
||||
|
||||
//! \~russian Перевести копию точки в полярную систему координат.
|
||||
//! \~english Returns polar form with radius in \a x and angle in \a y.
|
||||
//! \~russian Возвращает полярную форму, где радиус хранится в \a x, а угол в \a y.
|
||||
PIPoint<Type> toPolar(bool isDeg = false) const { return PIPoint<Type>(sqrt(x * x + y * y), isDeg ? angleDeg() : angleRad()); }
|
||||
|
||||
//! \~russian Перевести копию точки из полярной системы координат в декартовую.
|
||||
//! \~english Builds Cartesian point from polar pair with angle in \a x and radius in \a y.
|
||||
//! \~russian Строит декартову точку из полярной пары, где угол хранится в \a x, а радиус в \a y.
|
||||
static PIPoint<Type> fromPolar(const PIPoint<Type> & p) { return PIPoint<Type>(p.y * cos(p.x), p.y * sin(p.x)); }
|
||||
|
||||
//! \~russian
|
||||
//! Прибавить координаты второй точки и сохранить.
|
||||
//! \details Является копией метода \a translate().
|
||||
//! \~english Same as \a translate().
|
||||
//! \~russian Синоним \a translate().
|
||||
PIPoint<Type> & operator+=(const PIPoint<Type> & p) {
|
||||
translate(p);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Multiplies both coordinates by `v`.
|
||||
//! \~russian Умножает обе координаты на `v`.
|
||||
PIPoint<Type> & operator*=(Type v) {
|
||||
x *= v;
|
||||
y *= v;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~english Divides both coordinates by `v`.
|
||||
//! \~russian Делит обе координаты на `v`.
|
||||
PIPoint<Type> & operator/=(Type v) {
|
||||
x /= v;
|
||||
y /= v;
|
||||
return *this;
|
||||
}
|
||||
|
||||
//! \~russian Сложить координаты двух точек.
|
||||
//! \~english Returns sum of two points.
|
||||
//! \~russian Возвращает сумму двух точек.
|
||||
PIPoint<Type> operator+(const PIPoint<Type> & p) { return PIPoint<Type>(x + p.x, y + p.y); }
|
||||
|
||||
//! \~russian Прибавить к координатам одинаковое значение.
|
||||
//! \~english Returns point with `p` added to both coordinates.
|
||||
//! \~russian Возвращает точку с добавлением `p` к обеим координатам.
|
||||
PIPoint<Type> operator+(const Type & p) { return PIPoint<Type>(x + p, y + p); }
|
||||
|
||||
//! \~russian Вычесть из координат координаты второй точки - найти смещение.
|
||||
//! \~english Returns difference between two points.
|
||||
//! \~russian Возвращает разность двух точек.
|
||||
PIPoint<Type> operator-(const PIPoint<Type> & p) { return PIPoint<Type>(x - p.x, y - p.y); }
|
||||
|
||||
//! \~russian Вычесть из координат одинаковое значение.
|
||||
//! \~english Returns point with `p` subtracted from both coordinates.
|
||||
//! \~russian Возвращает точку с вычитанием `p` из обеих координат.
|
||||
PIPoint<Type> operator-(const Type & p) { return PIPoint<Type>(x - p, y - p); }
|
||||
|
||||
//! \~russian Инвертировать координаты точки.
|
||||
//! \~english Returns point with inverted coordinates.
|
||||
//! \~russian Возвращает точку с инвертированными координатами.
|
||||
PIPoint<Type> operator-() { return PIPoint<Type>(-x, -y); }
|
||||
|
||||
//! \~russian Умножить координаты точки.
|
||||
//! \~english Returns point scaled by `v`.
|
||||
//! \~russian Возвращает точку, масштабированную на `v`.
|
||||
PIPoint<Type> operator*(Type v) { return PIPoint<Type>(x * v, y * v); }
|
||||
|
||||
//! \~russian Делить координаты точки.
|
||||
//! \~english Returns point divided by `v`.
|
||||
//! \~russian Возвращает точку, деленную на `v`.
|
||||
PIPoint<Type> operator/(Type v) { return PIPoint<Type>(x / v, y / v); }
|
||||
|
||||
//! \~russian Проверить равенство координат двух точек.
|
||||
//! \~english Checks whether point coordinates are equal.
|
||||
//! \~russian Проверяет равенство координат точек.
|
||||
bool operator==(const PIPoint<Type> & p) const { return (x == p.x && y == p.y); }
|
||||
|
||||
//! \~russian Проверить неравенство координат двух точек.
|
||||
//! \~english Checks whether point coordinates differ.
|
||||
//! \~russian Проверяет неравенство координат точек.
|
||||
bool operator!=(const PIPoint<Type> & p) const { return (x != p.x || y != p.y); }
|
||||
};
|
||||
|
||||
//! \~russian Перегруженный оператор для вывода координат в \a PICout.
|
||||
//! \relatesalso PICout
|
||||
//! \~english Writes point coordinates to \a PICout.
|
||||
//! \~russian Выводит координаты точки в \a PICout.
|
||||
template<typename Type>
|
||||
PICout operator<<(PICout & s, const PIPoint<Type> & v) {
|
||||
s.space();
|
||||
@@ -182,9 +213,20 @@ PICout operator<<(PICout & s, const PIPoint<Type> & v) {
|
||||
}
|
||||
|
||||
|
||||
//! \~english Alias for point with `int` coordinates.
|
||||
//! \~russian Псевдоним точки с координатами типа `int`.
|
||||
typedef PIPoint<int> PIPointi;
|
||||
|
||||
//! \~english Alias for point with `uint` coordinates.
|
||||
//! \~russian Псевдоним точки с координатами типа `uint`.
|
||||
typedef PIPoint<uint> PIPointu;
|
||||
|
||||
//! \~english Alias for point with `float` coordinates.
|
||||
//! \~russian Псевдоним точки с координатами типа `float`.
|
||||
typedef PIPoint<float> PIPointf;
|
||||
|
||||
//! \~english Alias for point with `double` coordinates.
|
||||
//! \~russian Псевдоним точки с координатами типа `double`.
|
||||
typedef PIPoint<double> PIPointd;
|
||||
|
||||
#endif // PIPOINT_H
|
||||
|
||||
@@ -1,9 +1,8 @@
|
||||
/*! \file piquaternion.h
|
||||
* \ingroup Math
|
||||
* \~\brief
|
||||
* \~english Quaternion
|
||||
* \~russian Кватернион
|
||||
*/
|
||||
//! \~\file piquaternion.h
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english Quaternion
|
||||
//! \~russian Кватернион
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Class for quaternions
|
||||
@@ -28,43 +27,120 @@
|
||||
|
||||
#include "pimathmatrix.h"
|
||||
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english Quaternion for representing 3D rotations and orientations
|
||||
//! \~russian Кватернион для представления 3D вращений и ориентаций
|
||||
class PIP_EXPORT PIQuaternion {
|
||||
friend PIP_EXPORT PIQuaternion operator*(const PIQuaternion & q0, const PIQuaternion & q1);
|
||||
friend PIP_EXPORT PIQuaternion operator*(const double & a, const PIQuaternion & q);
|
||||
|
||||
public:
|
||||
//! \~english Construct quaternion from rotation axis and angle
|
||||
//! \~russian Создать кватернион из оси вращения и угла
|
||||
PIQuaternion(const PIMathVectorT3d & u = PIMathVectorT3d(), double a = 0.);
|
||||
|
||||
//! \~english Returns conjugate of this quaternion (negated vector part)
|
||||
//! \~russian Возвращает сопряженный кватернион (с инвертированной векторной частью)
|
||||
PIQuaternion conjugate() const { return PIQuaternion(-vector(), scalar()); }
|
||||
|
||||
//! \~english Returns new quaternion rotated around axis u by angle a
|
||||
//! \~russian Возвращает новый кватернион, повернутый вокруг оси u на угол a
|
||||
PIQuaternion rotated(const PIMathVectorT3d & u, double a) const;
|
||||
|
||||
//! \~english Rotate this quaternion around axis u by angle a
|
||||
//! \~russian Повернуть этот кватернион вокруг оси u на угол a
|
||||
void rotate(const PIMathVectorT3d & u, double a);
|
||||
|
||||
//! \~english Normalize quaternion to unit length
|
||||
//! \~russian Нормализовать кватернион к единичной длине
|
||||
void normalize();
|
||||
|
||||
//! \~english Get/Set scalar component
|
||||
//! \~russian Получить/установить скалярную компоненту
|
||||
double & scalar() { return q[0]; }
|
||||
|
||||
//! \~english Get scalar component
|
||||
//! \~russian Получить скалярную компоненту
|
||||
double scalar() const { return q[0]; }
|
||||
|
||||
//! \~english Returns vector part of quaternion
|
||||
//! \~russian Возвращает векторную часть кватерниона
|
||||
PIMathVectorT3d vector() const { return PIMathVectorT3d({q[1], q[2], q[3]}); }
|
||||
|
||||
//! \~english Returns Euler angles from quaternion
|
||||
//! \~russian Возвращает углы Эйлера из кватерниона
|
||||
PIMathVectorT3d eyler() const;
|
||||
|
||||
//! \~english Returns 3x3 rotation matrix from quaternion
|
||||
//! \~russian Возвращает матрицу вращения 3x3 из кватерниона
|
||||
PIMathMatrixT33d rotationMatrix() const;
|
||||
|
||||
//! \~english Extracts rotation axis from quaternion
|
||||
//! \~russian Извлекает ось вращения из кватерниона
|
||||
void axis(PIMathVectorT3d * ret) const;
|
||||
|
||||
//! \~english Create quaternion from Euler angles (roll, pitch, yaw)
|
||||
//! \~russian Создать кватернион из углов Эйлера (крен, тангаж, рыскание)
|
||||
static PIQuaternion fromEyler(double ax, double ay, double az);
|
||||
|
||||
//! \~english Create quaternion from 3x3 rotation matrix
|
||||
//! \~russian Создать кватернион из матрицы вращения 3x3
|
||||
static PIQuaternion fromRotationMatrix(const PIMathMatrixT33d & m);
|
||||
|
||||
//! \~english Create quaternion from rotation angles
|
||||
//! \~russian Создать кватернион из углов поворота
|
||||
static PIQuaternion fromAngles(double ax, double ay, double az);
|
||||
|
||||
//! \~english Create quaternion from rotation angles (alternative method)
|
||||
//! \~russian Создать кватернион из углов поворота (альтернативный метод)
|
||||
static PIQuaternion fromAngles2(double ax, double ay, double az);
|
||||
|
||||
protected:
|
||||
double q[4];
|
||||
};
|
||||
|
||||
//! \~english Scalar multiplication with quaternion
|
||||
//! \~russian Умножение скаляра на кватернион
|
||||
PIP_EXPORT PIQuaternion operator*(const double & a, const PIQuaternion & q);
|
||||
|
||||
//! \~english Quaternion multiplication
|
||||
//! \~russian Умножение кватернионов
|
||||
//! \~\details
|
||||
//! \~english Performs quaternion multiplication (Hamilton product)
|
||||
//! \~russian Выполняет умножение кватернионов (произведение Гамильтона)
|
||||
//! \~\sa operator+(const PIQuaternion &, const PIQuaternion &)
|
||||
//! \~\sa operator-(const PIQuaternion &, const PIQuaternion &)
|
||||
PIP_EXPORT PIQuaternion operator*(const PIQuaternion & q0, const PIQuaternion & q1);
|
||||
|
||||
//! \~english Quaternion addition
|
||||
//! \~russian Сложение кватернионов
|
||||
//! \~\details
|
||||
//! \~english Adds corresponding components of two quaternions
|
||||
//! \~russian Складывает соответствующие компоненты двух кватернионов
|
||||
//! \~\sa operator*(const PIQuaternion &, const PIQuaternion &)
|
||||
//! \~\sa operator-(const PIQuaternion &, const PIQuaternion &)
|
||||
inline PIQuaternion operator+(const PIQuaternion & q0, const PIQuaternion & q1) {
|
||||
return PIQuaternion(q0.vector() + q1.vector(), q0.scalar() + q1.scalar());
|
||||
}
|
||||
|
||||
//! \~english Quaternion subtraction
|
||||
//! \~russian Вычитание кватернионов
|
||||
//! \~\details
|
||||
//! \~english Subtracts corresponding components of two quaternions
|
||||
//! \~russian Вычитает соответствующие компоненты двух кватернионов
|
||||
//! \~\sa operator*(const PIQuaternion &, const PIQuaternion &)
|
||||
//! \~\sa operator+(const PIQuaternion &, const PIQuaternion &)
|
||||
inline PIQuaternion operator-(const PIQuaternion & q0, const PIQuaternion & q1) {
|
||||
return PIQuaternion(q0.vector() - q1.vector(), q0.scalar() - q1.scalar());
|
||||
}
|
||||
|
||||
//! \~english Quaternion negation
|
||||
//! \~russian Унарный минус кватерниона
|
||||
//! \~\details
|
||||
//! \~english Negates both vector and scalar parts of the quaternion
|
||||
//! \~russian Меняет знаки как векторной, так и скалярной частей кватерниона
|
||||
//! \~\sa conjugate()
|
||||
inline PIQuaternion operator-(const PIQuaternion & q0) {
|
||||
return PIQuaternion(-q0.vector(), -q0.scalar());
|
||||
}
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
//! \file pirect.h
|
||||
//! \ingroup Math
|
||||
//! \brief
|
||||
//! \~english Rect class
|
||||
//! \~russian Класс прямоугольника
|
||||
//! \~\file pirect.h
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english Rect class for 2D geometry
|
||||
//! \~russian Класс прямоугольника для 2D геометрии
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Rect class
|
||||
Rect class for 2D geometry
|
||||
Ivan Pelipenko peri4ko@yandex.ru, Andrey Bychkov work.a.b@yandex.ru
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
@@ -27,29 +27,28 @@
|
||||
#include "pipoint.h"
|
||||
|
||||
|
||||
//! \brief
|
||||
//! \~english Rect class
|
||||
//! \~russian Класс прямоугольника
|
||||
//! \~\details
|
||||
//! \~russian
|
||||
//! Этот класс описывает прямоугольник на плоскости в прямоугольной системе координат
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english The PIRect class provides a two-dimensional rectangle class for 2D geometry.
|
||||
//! \~russian Класс PIRect предоставляет двумерный класс прямоугольника для 2D геометрии.
|
||||
template<typename Type>
|
||||
class PIP_EXPORT PIRect {
|
||||
static_assert(std::is_arithmetic<Type>::value, "Type must be arithmetic");
|
||||
|
||||
public:
|
||||
//!
|
||||
//! \~english Constructs empty rectangle.
|
||||
//! \~russian Создает пустой прямоугольник.
|
||||
PIRect() {}
|
||||
|
||||
//! \brief
|
||||
//! \~russian Конструктор прямоугольника из координат левого нижнего угла и размеров ширины и высоты
|
||||
//! \~english Constructs rectangle from bottom-left corner, width and height.
|
||||
//! \~russian Создает прямоугольник по левому нижнему углу, ширине и высоте.
|
||||
PIRect(Type left_, Type bottom_, Type width_, Type height_) {
|
||||
set(left_, bottom_, width_, height_);
|
||||
normalize();
|
||||
}
|
||||
|
||||
//! \brief
|
||||
//! \~russian Конструктор прямоугольника из координат левого нижнего угла и правого верхнего угла
|
||||
//! \~english Constructs rectangle from opposite corners.
|
||||
//! \~russian Создает прямоугольник по двум противоположным углам.
|
||||
PIRect(const PIPoint<Type> & bottom_left, const PIPoint<Type> & top_right) {
|
||||
bl = bottom_left;
|
||||
tr = top_right;
|
||||
@@ -61,128 +60,148 @@ public:
|
||||
// piMax<Type>(p0.x, p1.x, p2.x), piMax<Type>(p0.y, p1.y, p2.y));
|
||||
// }
|
||||
|
||||
//!
|
||||
//! \~english Sets rectangle from bottom-left corner, width and height.
|
||||
//! \~russian Задает прямоугольник по левому нижнему углу, ширине и высоте.
|
||||
PIRect<Type> & set(Type left_, Type bottom_, Type width_, Type height_) {
|
||||
bl = PIPoint<Type>(left_, bottom_);
|
||||
tr = PIPoint<Type>(left_ + width_, bottom_ + height_);
|
||||
return normalize();
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Sets rectangle from two opposite corners.
|
||||
//! \~russian Задает прямоугольник по двум противоположным углам.
|
||||
PIRect<Type> & set(const PIPoint<Type> & top_left, const PIPoint<Type> & bottom_right) {
|
||||
bl = top_left;
|
||||
tr = bottom_right;
|
||||
return normalize();
|
||||
}
|
||||
|
||||
//! \brief
|
||||
//! \~russian Возвращает true если точка с указанными координатами принадлежит прямоугольнику
|
||||
//! \~english Checks point against current rectangle bounds.
|
||||
//! \~russian Проверяет точку относительно текущих границ прямоугольника.
|
||||
bool pointIn(Type x, Type y) const { return (x <= bl.x && x >= tr.x && y <= bl.y && y >= tr.y); }
|
||||
|
||||
//! \brief
|
||||
//! \~russian Возвращает true если точка с указанными координатами принадлежит прямоугольнику
|
||||
//! \~english Checks point against current rectangle bounds.
|
||||
//! \~russian Проверяет точку относительно текущих границ прямоугольника.
|
||||
bool pointIn(const PIPoint<Type> & p) const { return pointIn(p.x, p.y); }
|
||||
|
||||
//!
|
||||
//! \~english Returns `true` if width and height are zero.
|
||||
//! \~russian Возвращает `true`, если ширина и высота равны нулю.
|
||||
bool isEmpty() const { return (width() == 0 && height() == 0); }
|
||||
|
||||
//!
|
||||
//! \~english Shifts the rectangle by `x` and `y`.
|
||||
//! \~russian Сдвигает прямоугольник на `x` и `y`.
|
||||
PIRect<Type> & translate(Type x, Type y) {
|
||||
bl.translate(x, y);
|
||||
tr.translate(x, y);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Shifts the rectangle by a point offset.
|
||||
//! \~russian Сдвигает прямоугольник на смещение, заданное точкой.
|
||||
PIRect<Type> & translate(const PIPoint<Type> & p) {
|
||||
bl.translate(p);
|
||||
tr.translate(p);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Returns translated copy of the rectangle.
|
||||
//! \~russian Возвращает смещенную копию прямоугольника.
|
||||
PIRect<Type> translated(Type x, Type y) const {
|
||||
PIRect<Type> r(*this);
|
||||
r.translate(x, y);
|
||||
return r;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Returns copy shifted by a point offset.
|
||||
//! \~russian Возвращает копию, смещенную на точку.
|
||||
PIRect<Type> translated(const PIPoint<Type> & p) const {
|
||||
PIRect<Type> r(*this);
|
||||
r.translate(p);
|
||||
return r;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Same as \a translate().
|
||||
//! \~russian Синоним \a translate().
|
||||
PIRect<Type> & move(Type x, Type y) { return translate(x, y); }
|
||||
|
||||
//!
|
||||
//! \~english Same as \a translate().
|
||||
//! \~russian Синоним \a translate().
|
||||
PIRect<Type> & move(const PIPoint<Type> & p) { return translate(p); }
|
||||
|
||||
//!
|
||||
//! \~english Same as \a translated().
|
||||
//! \~russian Синоним \a translated().
|
||||
PIRect<Type> moved(Type x, Type y) const {
|
||||
PIRect<Type> r(*this);
|
||||
r.translate(x, y);
|
||||
return r;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Same as \a translated().
|
||||
//! \~russian Синоним \a translated().
|
||||
PIRect<Type> moved(const PIPoint<Type> & p) const {
|
||||
PIRect<Type> r(*this);
|
||||
r.translate(p);
|
||||
return r;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Scales rectangle extents by `x` and `y`.
|
||||
//! \~russian Масштабирует размеры прямоугольника по `x` и `y`.
|
||||
PIRect<Type> & scale(Type x, Type y) {
|
||||
setWidth(width() * x);
|
||||
setHeight(height() * y);
|
||||
return normalize();
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Scales both extents by `s`.
|
||||
//! \~russian Масштабирует обе стороны на `s`.
|
||||
PIRect<Type> & scale(Type s) { return scale(s, s); }
|
||||
|
||||
//!
|
||||
//! \~english Scales extents by point components.
|
||||
//! \~russian Масштабирует стороны по компонентам точки.
|
||||
PIRect<Type> & scale(const PIPoint<Type> & p) { return scale(p.x, p.y); }
|
||||
|
||||
//!
|
||||
//! \~english Returns scaled copy of the rectangle.
|
||||
//! \~russian Возвращает масштабированную копию прямоугольника.
|
||||
PIRect<Type> scaled(Type x, Type y) const {
|
||||
PIRect<Type> r(*this);
|
||||
r.scale(x, y);
|
||||
return r;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Returns copy scaled uniformly.
|
||||
//! \~russian Возвращает копию с равномерным масштабированием.
|
||||
PIRect<Type> scaled(Type s) const {
|
||||
PIRect<Type> r(*this);
|
||||
r.scale(s);
|
||||
return r;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Returns copy scaled by point components.
|
||||
//! \~russian Возвращает копию, масштабированную по компонентам точки.
|
||||
PIRect<Type> scaled(const PIPoint<Type> & p) const {
|
||||
PIRect<Type> r(*this);
|
||||
r.scale(p);
|
||||
return r;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Normalizes corner order.
|
||||
//! \~russian Нормализует порядок углов.
|
||||
PIRect<Type> & normalize() {
|
||||
if (bl.x > tr.x) piSwap<Type>(bl.x, tr.x);
|
||||
if (bl.y > tr.y) piSwap<Type>(bl.y, tr.y);
|
||||
return *this;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Returns normalized copy of the rectangle.
|
||||
//! \~russian Возвращает нормализованную копию прямоугольника.
|
||||
PIRect<Type> normalized() const {
|
||||
PIRect<Type> r(*this);
|
||||
r.normalize();
|
||||
return r;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Updates bounds using rectangle `r` and normalizes the result.
|
||||
//! \~russian Обновляет границы по прямоугольнику `r` и нормализует результат.
|
||||
PIRect<Type> & unite(const PIRect<Type> & r) {
|
||||
bl.x = piMax<Type>(bl.x, r.left());
|
||||
bl.y = piMax<Type>(bl.y, r.bottom());
|
||||
@@ -191,14 +210,16 @@ public:
|
||||
return normalize();
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Returns copy after \a unite().
|
||||
//! \~russian Возвращает копию после \a unite().
|
||||
PIRect<Type> united(const PIRect<Type> & rect) const {
|
||||
PIRect<Type> r(*this);
|
||||
r.unite(rect);
|
||||
return r;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Replaces rectangle with intersection with `r`.
|
||||
//! \~russian Заменяет прямоугольник пересечением с `r`.
|
||||
PIRect<Type> & intersect(const PIRect<Type> & r) {
|
||||
bl.x = piMax<Type>(bl.x, r.left());
|
||||
bl.y = piMax<Type>(bl.y, r.bottom());
|
||||
@@ -208,101 +229,124 @@ public:
|
||||
return *this;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Returns copy after \a intersect().
|
||||
//! \~russian Возвращает копию после \a intersect().
|
||||
PIRect<Type> intersected(const PIRect<Type> & rect) const {
|
||||
PIRect<Type> r(*this);
|
||||
r.intersect(rect);
|
||||
return r;
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Returns top edge coordinate.
|
||||
//! \~russian Возвращает координату верхней границы.
|
||||
Type top() const { return tr.y; }
|
||||
|
||||
//!
|
||||
//! \~english Returns left edge coordinate.
|
||||
//! \~russian Возвращает координату левой границы.
|
||||
Type left() const { return bl.x; }
|
||||
|
||||
//!
|
||||
//! \~english Returns right edge coordinate.
|
||||
//! \~russian Возвращает координату правой границы.
|
||||
Type right() const { return tr.x; }
|
||||
|
||||
//!
|
||||
//! \~english Returns bottom edge coordinate.
|
||||
//! \~russian Возвращает координату нижней границы.
|
||||
Type bottom() const { return bl.y; }
|
||||
|
||||
//!
|
||||
//! \~english Returns rectangle width.
|
||||
//! \~russian Возвращает ширину прямоугольника.
|
||||
Type width() const { return tr.x - bl.x; }
|
||||
|
||||
//!
|
||||
//! \~english Returns rectangle height.
|
||||
//! \~russian Возвращает высоту прямоугольника.
|
||||
Type height() const { return tr.y - bl.y; }
|
||||
|
||||
//!
|
||||
//! \~english Returns top-left corner.
|
||||
//! \~russian Возвращает левый верхний угол.
|
||||
PIPoint<Type> topLeft() const { return PIPoint<Type>(bl.x, tr.y); }
|
||||
|
||||
//!
|
||||
//! \~english Returns top-right corner.
|
||||
//! \~russian Возвращает правый верхний угол.
|
||||
PIPoint<Type> topRigth() const { return tr; }
|
||||
|
||||
//!
|
||||
//! \~english Returns bottom-left corner.
|
||||
//! \~russian Возвращает левый нижний угол.
|
||||
PIPoint<Type> bottomLeft() const { return bl; }
|
||||
|
||||
//!
|
||||
//! \~english Returns bottom-right corner.
|
||||
//! \~russian Возвращает правый нижний угол.
|
||||
PIPoint<Type> bottomRight() const { return PIPoint<Type>(tr.x, bl.y); }
|
||||
|
||||
//!
|
||||
//! \~english Returns rectangle center.
|
||||
//! \~russian Возвращает центр прямоугольника.
|
||||
PIPoint<Type> center() const { return bl.moved(width() / 2, height() / 2); }
|
||||
|
||||
//!
|
||||
//! \~english Sets top edge coordinate.
|
||||
//! \~russian Задает координату верхней границы.
|
||||
void setTop(Type v) {
|
||||
tr.y = v;
|
||||
normalize();
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Sets left edge coordinate.
|
||||
//! \~russian Задает координату левой границы.
|
||||
void setLeft(Type v) {
|
||||
bl.x = v;
|
||||
normalize();
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Sets right edge coordinate.
|
||||
//! \~russian Задает координату правой границы.
|
||||
void setRigth(Type v) {
|
||||
tr.x = v;
|
||||
normalize();
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Sets bottom edge coordinate.
|
||||
//! \~russian Задает координату нижней границы.
|
||||
void setBottom(Type v) {
|
||||
bl.y = v;
|
||||
normalize();
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Updates stored width-related extent.
|
||||
//! \~russian Обновляет хранимую горизонтальную размерность.
|
||||
void setWidth(Type v) { setTop(bl.x + v); }
|
||||
|
||||
//!
|
||||
//! \~english Updates stored height-related extent.
|
||||
//! \~russian Обновляет хранимую вертикальную размерность.
|
||||
void setHeight(Type v) { setRigth(bl.y + v); }
|
||||
|
||||
//!
|
||||
//! \~english Sets top-left corner.
|
||||
//! \~russian Задает левый верхний угол.
|
||||
void setTopLeft(const PIPoint<Type> & p) {
|
||||
setLeft(p.x);
|
||||
setTop(p.y);
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Sets bottom-right corner.
|
||||
//! \~russian Задает правый нижний угол.
|
||||
void setBottomRight(const PIPoint<Type> & p) {
|
||||
setRigth(p.x);
|
||||
setBottom(p.y);
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Sets bottom-left corner.
|
||||
//! \~russian Задает левый нижний угол.
|
||||
void setBottomLeft(const PIPoint<Type> & p) {
|
||||
bl = p;
|
||||
normalize();
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Sets top-right corner.
|
||||
//! \~russian Задает правый верхний угол.
|
||||
void setTopRigth(const PIPoint<Type> & p) {
|
||||
tr = p;
|
||||
normalize();
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Repositions rectangle around center point `p`.
|
||||
//! \~russian Перемещает прямоугольник так, чтобы его центром стала точка `p`.
|
||||
void setCenter(const PIPoint<Type> & p) {
|
||||
Type w = width();
|
||||
Type h = height();
|
||||
@@ -310,46 +354,59 @@ public:
|
||||
tr = PIPoint<Type>(bl.x + w, bl.y + h);
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Sets rectangle size from current bottom-left corner.
|
||||
//! \~russian Задает размер прямоугольника от текущего левого нижнего угла.
|
||||
void setSize(Type w, Type h) {
|
||||
tr = PIPoint<Type>(bl.x + w, bl.y + h);
|
||||
normalize();
|
||||
}
|
||||
|
||||
//!
|
||||
//! \~english Shifts both coordinates by `x`.
|
||||
//! \~russian Сдвигает обе координаты на `x`.
|
||||
void operator+=(Type x) { translate(x, x); }
|
||||
|
||||
//!
|
||||
//! \~english Shifts rectangle by a point offset.
|
||||
//! \~russian Сдвигает прямоугольник на смещение, заданное точкой.
|
||||
void operator+=(const PIPoint<Type> & p) { translate(p); }
|
||||
|
||||
//!
|
||||
//! \~english Shifts both coordinates by `-x`.
|
||||
//! \~russian Сдвигает обе координаты на `-x`.
|
||||
void operator-=(Type x) { translate(-x, -x); }
|
||||
|
||||
//!
|
||||
//! \~english Shifts rectangle by the negated point offset.
|
||||
//! \~russian Сдвигает прямоугольник на отрицательное смещение точки.
|
||||
void operator-=(const PIPoint<Type> & p) { translate(-p); }
|
||||
|
||||
//!
|
||||
//! \~english Same as \a unite().
|
||||
//! \~russian Синоним \a unite().
|
||||
void operator|=(const PIRect<Type> & r) { unite(r); }
|
||||
|
||||
//!
|
||||
//! \~english Same as \a intersect().
|
||||
//! \~russian Синоним \a intersect().
|
||||
void operator&=(const PIRect<Type> & r) { intersect(r); }
|
||||
|
||||
//!
|
||||
//! \~english Returns translated copy of the rectangle.
|
||||
//! \~russian Возвращает смещенную копию прямоугольника.
|
||||
PIRect<Type> operator+(const PIPoint<Type> & p) { return translated(p); }
|
||||
|
||||
//!
|
||||
//! \~english Returns copy shifted by the negated point offset.
|
||||
//! \~russian Возвращает копию, смещенную на отрицательное смещение точки.
|
||||
PIRect<Type> operator-(const PIPoint<Type> & p) { return translated(-p); }
|
||||
|
||||
//!
|
||||
//! \~english Returns copy after \a unite().
|
||||
//! \~russian Возвращает копию после \a unite().
|
||||
PIRect<Type> operator|(const PIRect<Type> & r) { return united(r); }
|
||||
|
||||
//!
|
||||
//! \~english Returns copy after \a intersect().
|
||||
//! \~russian Возвращает копию после \a intersect().
|
||||
PIRect<Type> operator&(const PIRect<Type> & r) { return intersected(r); }
|
||||
|
||||
//!
|
||||
//! \~english Checks whether rectangle corners are equal.
|
||||
//! \~russian Проверяет равенство углов прямоугольников.
|
||||
bool operator==(const PIRect<Type> & r) const { return (bl == r.bl && tr == r.tr); }
|
||||
|
||||
//!
|
||||
//! \~english Checks whether rectangle corners differ.
|
||||
//! \~russian Проверяет различие углов прямоугольников.
|
||||
bool operator!=(const PIRect<Type> & r) const { return (bl != r.bl || tr != r.tr); }
|
||||
|
||||
private:
|
||||
@@ -358,6 +415,9 @@ private:
|
||||
};
|
||||
|
||||
|
||||
//! \relatesalso PICout
|
||||
//! \~english Writes rectangle description to \a PICout.
|
||||
//! \~russian Выводит описание прямоугольника в \a PICout.
|
||||
template<typename Type>
|
||||
PICout operator<<(PICout & s, const PIRect<Type> & v) {
|
||||
s.space();
|
||||
@@ -368,9 +428,20 @@ PICout operator<<(PICout & s, const PIRect<Type> & v) {
|
||||
}
|
||||
|
||||
|
||||
//! \~english Alias for rectangle with `int` coordinates.
|
||||
//! \~russian Псевдоним прямоугольника с координатами типа `int`.
|
||||
typedef PIRect<int> PIRecti;
|
||||
|
||||
//! \~english Alias for rectangle with `uint` coordinates.
|
||||
//! \~russian Псевдоним прямоугольника с координатами типа `uint`.
|
||||
typedef PIRect<uint> PIRectu;
|
||||
|
||||
//! \~english Alias for rectangle with `float` coordinates.
|
||||
//! \~russian Псевдоним прямоугольника с координатами типа `float`.
|
||||
typedef PIRect<float> PIRectf;
|
||||
|
||||
//! \~english Alias for rectangle with `double` coordinates.
|
||||
//! \~russian Псевдоним прямоугольника с координатами типа `double`.
|
||||
typedef PIRect<double> PIRectd;
|
||||
|
||||
#endif // PIRECT_H
|
||||
|
||||
@@ -1,12 +1,11 @@
|
||||
/*! \file pistatistic.h
|
||||
* \ingroup Math
|
||||
* \~\brief
|
||||
* \~english Calculating math statistic of values array
|
||||
* \~russian Вычисление математической статистики у массива чисел
|
||||
*/
|
||||
//! \~\ingroup Math
|
||||
//! \~\file pistatistic.h
|
||||
//! \brief
|
||||
//! \~english Calculating math statistic of values array
|
||||
//! \~russian Вычисление математической статистики у массива чисел
|
||||
/*
|
||||
PIP - Platform Independent Primitives
|
||||
Class for calculacing math statistic in values array
|
||||
Calculating math statistic of values array
|
||||
Andrey Bychkov work.a.b@yandex.ru
|
||||
|
||||
This program is free software: you can redistribute it and/or modify
|
||||
@@ -28,13 +27,24 @@
|
||||
|
||||
#include "pimathbase.h"
|
||||
|
||||
//! \~\ingroup Math
|
||||
//! \~\brief
|
||||
//! \~english Template class for calculating statistical measures of a data set
|
||||
//! \~russian Шаблонный класс для вычисления статистических характеристик набора данных
|
||||
//! \details
|
||||
//! \~english Calculates mean, variance, skewness and kurtosis for a numeric sample.
|
||||
//! \~russian Вычисляет среднее, дисперсию, асимметрию и эксцесс для числовой выборки.
|
||||
template<typename T>
|
||||
class PIStatistic {
|
||||
static_assert(std::is_arithmetic<T>::value, "Type must be arithmetic");
|
||||
|
||||
public:
|
||||
//! \~english Constructs an object with all accumulated values set to zero.
|
||||
//! \~russian Создает объект со всеми накопленными значениями, равными нулю.
|
||||
PIStatistic() { mean = variance = skewness = kurtosis = T(); }
|
||||
|
||||
//! \~english Returns arithmetic mean of the sample, or zero for an empty vector.
|
||||
//! \~russian Возвращает среднее арифметическое выборки или ноль для пустого вектора.
|
||||
static T calculateMean(const PIVector<T> & val) {
|
||||
T ret = T();
|
||||
int n = val.size();
|
||||
@@ -43,10 +53,16 @@ public:
|
||||
ret += val[i];
|
||||
return ret / n;
|
||||
}
|
||||
|
||||
//! \~english Calculates all statistics using the supplied mean value.
|
||||
//! \~russian Вычисляет всю статистику, используя переданное среднее значение.
|
||||
//! \~\details
|
||||
//! \~english Returns \c false when the sample contains fewer than two values.
|
||||
//! \~russian Возвращает \c false, если в выборке меньше двух значений.
|
||||
bool calculate(const PIVector<T> & val, const T & given_mean) {
|
||||
T v = T(), v1 = T(), v2 = T(), stddev = T(), var = T();
|
||||
int i, n = val.size();
|
||||
mean = given_mean;
|
||||
mean = given_mean;
|
||||
if (n < 2) return false;
|
||||
variance = skewness = kurtosis = T();
|
||||
// Variance (using corrected two-pass algorithm)
|
||||
@@ -72,16 +88,38 @@ public:
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
//! \~english Calculates all statistics and derives the mean from the sample.
|
||||
//! \~russian Вычисляет всю статистику, определяя среднее по самой выборке.
|
||||
bool calculate(const PIVector<T> & val) { return calculate(val, calculateMean(val)); }
|
||||
|
||||
//! \~english Sample mean.
|
||||
//! \~russian Среднее значение выборки.
|
||||
T mean;
|
||||
|
||||
//! \~english Variance estimate accumulated for the sample.
|
||||
//! \~russian Оценка дисперсии, вычисленная по выборке.
|
||||
T variance;
|
||||
|
||||
//! \~english Sample skewness.
|
||||
//! \~russian Асимметрия выборки.
|
||||
T skewness;
|
||||
|
||||
//! \~english Excess kurtosis of the sample.
|
||||
//! \~russian Эксцесс выборки.
|
||||
T kurtosis;
|
||||
};
|
||||
|
||||
//! \~english Integer statistics helper.
|
||||
//! \~russian Вспомогательный тип статистики для целых чисел.
|
||||
typedef PIStatistic<int> PIStatistici;
|
||||
|
||||
//! \~english Single-precision statistics helper.
|
||||
//! \~russian Вспомогательный тип статистики одинарной точности.
|
||||
typedef PIStatistic<float> PIStatisticf;
|
||||
|
||||
//! \~english Double-precision statistics helper.
|
||||
//! \~russian Вспомогательный тип статистики двойной точности.
|
||||
typedef PIStatistic<double> PIStatisticd;
|
||||
|
||||
#endif // PISTATISTIC_H
|
||||
|
||||
Reference in New Issue
Block a user