more ai generated doc with human review

This commit is contained in:
2026-02-28 12:29:00 +03:00
parent 077f12c9e5
commit 0878891cd8
86 changed files with 2215 additions and 637 deletions

View File

@@ -1,9 +1,13 @@
/*! \file pievaluator.h
* \ingroup Math
* \~\brief
* \~english Mathematic expressions calculator
* \~russian Вычислитель математических выражений
*/
//! \addtogroup Math
//! \{
//! \file pievaluator.h
//! \brief
//! \~english Mathematic expressions calculator
//! \~russian Вычислитель математических выражений
//! \details
//! \~english Evaluator for parsing and calculating mathematical expressions
//! \~russian Вычислитель для разбора и вычисления математических выражений
//! \}
/*
PIP - Platform Independent Primitives
Evaluator designed for stream calculations
@@ -180,36 +184,72 @@ struct PIP_EXPORT Variable {
|
*/
//! Content container for variables and functions
//! \~\english Container for variables and functions of the evaluator
//! \~russian Контейнер для переменных и функций вычислителя
class PIP_EXPORT PIEvaluatorContent {
friend class PIEvaluator;
BINARY_STREAM_FRIEND(PIEvaluatorContent);
public:
//! Constructs an empty evaluator content
PIEvaluatorContent();
~PIEvaluatorContent() { ; }
//! Add function with specified name and argument count
//! \~english Add function with name and default 1 argument
//! \~russian Добавить функцию с указанным именем и количеством аргументов (по умолчанию 1)
void addFunction(const PIString & name, int args = 1);
//! Add variable with specified name and value
//! \~english Add variable with name and optional value, returns variable index
//! \~russian Добавить переменную с указанным именем и значением, возвращает индекс переменной
int addVariable(const PIString & name, const complexd & val = 0.);
//! Add custom function with handler
//! \~english Add custom function with name, argument count and handler function
//! \~russian Добавить пользовательскую функцию с обработчиком
void addCustomFunction(const PIString & name, int args_count, PIEvaluatorTypes::FuncHanlder func);
//! Get number of functions
int functionsCount() const { return functions.size(); }
//! Get number of variables
int variablesCount() const { return variables.size(); }
//! Get number of custom variables
int customVariablesCount() const;
//! Find function index by name
int findFunction(const PIString & name) const;
//! Find variable index by name
int findVariable(const PIString & var_name) const;
//! Get function by index
PIEvaluatorTypes::Function function(int index);
//! Get variable by index
PIEvaluatorTypes::Variable variable(int index);
//! Get function by name
PIEvaluatorTypes::Function function(const PIString & name) { return function(findFunction(name)); }
//! Get variable by name
PIEvaluatorTypes::Variable variable(const PIString & name) { return variable(findVariable(name)); }
//! Get custom variable by index
PIEvaluatorTypes::Variable customVariable(int index);
//! Set variable value by index
//! \~english Set variable value by index, returns true on success
//! \~russian Установить значение переменной по индексу, возвращает true при успехе
bool setVariableValue(int index, complexd new_value);
//! Set variable value by name
//! \~english Set variable value by name, returns true on success
//! \~russian Установить значение переменной по имени, возвращает true при успехе
bool setVariableValue(const PIString & var_name, const complexd & new_value) {
return setVariableValue(findVariable(var_name), new_value);
}
//! Set variable name by index
bool setVariableName(int index, const PIString & new_name);
//! Set variable name by name
bool setVariableName(const PIString & var_name, const PIString & new_name) { return setVariableName(findVariable(var_name), new_name); }
//! Clear all custom variables
void clearCustomVariables();
//! Get base function type by name
PIEvaluatorTypes::BaseFunctions getBaseFunction(const PIString & name);
//! Dump content to console for debugging
//! \~english Print all functions and variables to console
//! \~russian Вывести все функции и переменные в консоль
void dump();
private:
@@ -219,6 +259,9 @@ private:
};
//! Main evaluator class for parsing and calculating mathematical expressions
//! \~\english Main class for parsing and evaluating mathematical expressions
//! \~russian Главный класс для разбора и вычисления математических выражений
class PIP_EXPORT PIEvaluator {
public:
//! Constructs an empty evaluator

View File

@@ -43,98 +43,99 @@ public:
PIPoint<Type> p0;
PIPoint<Type> p1;
//! \~russian
//! Пустой конструктор.
//! \~english Default constructor.
//! \~russian Пустой конструктор.
//! \details
//! При выполнении пустого конструктора координаты не изменяются.
//! Начало и конец совпадают.
//! \~english Creates an empty line where start and end points coincide.
//! \~russian При выполнении пустого конструктора координаты не изменяются. Начало и конец совпадают.
PILine() {}
//! \~russian
//! Создает линию по двум принятым точкам \a PIPoint начала и конца.
//! \~english Creates a line from two points.
//! \~russian Создает линию по двум принятым точкам \a PIPoint начала и конца.
PILine(const PIPoint<Type> & p0_, const PIPoint<Type> & p1_) {
p0 = p0_;
p1 = p1_;
}
//! \~russian
//! Создает линию по принятым координатам начала и конца.
//! \~english Creates a line from coordinates.
//! \~russian Создает линию по принятым координатам начала и конца.
PILine(Type x0, Type y0, Type x1, Type y1) {
p0.set(x0, y0);
p1.set(x1, y1);
}
//! \~russian
//! Задать новые координаты начала и конца по двум принятым точкам \a PIPoint.
//! \~english Set new coordinates from two points.
//! \~russian Задать новые координаты начала и конца по двум принятым точкам \a PIPoint.
PILine<Type> & set(const PIPoint<Type> & p0_, const PIPoint<Type> & p1_) {
p0 = p0_;
p1 = p1_;
return *this;
}
//! \~russian
//! Задать новые координаты начала и конца.
//! \~english Set new 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 Check if start and end points coincide.
//! \~russian Проверить на совпадение координат начала и конца.
bool isEmpty() const { return (p0 == p1); }
//! \~russian
//! Вычислить ширину прямоугольника, диагональю которого является данный отрезок.
//! \~english Calculate width of the rectangle whose diagonal is this line.
//! \~russian Вычислить ширину прямоугольника, диагональю которого является данный отрезок.
Type width() const { return piAbs<Type>(p1.x - p0.x); }
//! \~russian
//! Вычислить высоту прямоугольника, диагональю которого является данный отрезок.
//! \~english Calculate height of the rectangle whose diagonal is this line.
//! \~russian Вычислить высоту прямоугольника, диагональю которого является данный отрезок.
Type height() const { return piAbs<Type>(p1.y - p0.y); }
//! \~russian
//! Сдвинуть линию на \a x, \a y.
//! \~english Translate line by x and y.
//! \~russian Сдвинуть линию на \a x, \a y.
PILine<Type> & translate(Type x, Type y) {
p0.translate(x, y);
p1.translate(x, y);
return *this;
}
//! \~russian
//! Сдвинуть линию на значение координат точки \a PIPoint.
//! \~english Translate line by point coordinates.
//! \~russian Сдвинуть линию на значение координат точки \a PIPoint.
PILine<Type> & translate(const PIPoint<Type> & p) {
p0.translate(p);
p1.translate(p);
return *this;
}
//! Создать копию отрезка и сдвинуть её на `x` и `y`.
//! \~english Create a copy of the line and translate it by x and y.
//! \~russian Создать копию отрезка и сдвинуть её на `x` и `y`.
PILine<Type> translated(Type x, Type y) const {
PILine<Type> l(*this);
l.translate(x, y);
return l;
}
//! \~russian
//! Создать копию отрезка и сдвинуть её на значение координат точки \a PIPoint.
//! \~english Create a copy of the line and translate it by point coordinates.
//! \~russian Создать копию отрезка и сдвинуть её на значение координат точки \a PIPoint.
PILine<Type> translated(const PIPoint<Type> & p) const {
PILine<Type> l(*this);
l.translate(p);
return l;
}
//! \~russian
//! Сдвинуть линию на \a x, \a y.
//! \~english Translate line by x and y. Alias for \a translate().
//! \~russian Сдвинуть линию на \a x, \a y.
//! \details Является копией метода \a translate().
PILine<Type> & move(Type x, Type y) { return translate(x, y); }
//! \~russian
//! Сдвинуть линию на значение координат точки \a PIPoint.
//! \~english Translate line by point coordinates. Alias for \a translate().
//! \~russian Сдвинуть линию на значение координат точки \a PIPoint.
//! \details Является копией метода \a translate().
PILine<Type> & move(const PIPoint<Type> & p) { return translate(p); }
//! \~russian
//! Создать копию отрезка и сдвинуть её на \a x, \a y.
//! \~english Create a copy of the line and translate it by x and y. Alias for \a translated().
//! \~russian Создать копию отрезка и сдвинуть её на \a x, \a y.
//! \details Является копией метода \a translated().
PILine<Type> moved(Type x, Type y) const {
PILine<Type> l(*this);
@@ -142,8 +143,8 @@ public:
return l;
}
//! \~russian
//! Создать копию отрезка и сдвинуть её на значение координат точки \a PIPoint.
//! \~english Create a copy of the line and translate it by point coordinates. Alias for \a translated().
//! \~russian Создать копию отрезка и сдвинуть её на значение координат точки \a PIPoint.
//! \details Является копией метода \a translated().
PILine<Type> moved(const PIPoint<Type> & p) const {
PILine<Type> l(*this);
@@ -151,31 +152,40 @@ public:
return l;
}
//! \~english Translate line by x value on both coordinates.
//! \~russian Сдвинуть линию по двум координатам на значение \a x.
void operator+=(Type x) { translate(x, x); }
//! \~english Translate line by point coordinates.
//! \~russian Сдвинуть линию по двум координатам на величину координат точки \a PIPoint.
void operator+=(const PIPoint<Type> & p) { translate(p); }
//! \~english Translate line by negative x value on both coordinates.
//! \~russian Сдвинуть линию по двум координатам на значение \a x.
void operator-=(Type x) { translate(-x, -x); }
//! \~english Translate line by negative point coordinates.
//! \~russian Сдвинуть линию по двум координатам на величину координат точки \a PIPoint.
void operator-=(const PIPoint<Type> & p) { translate(-p); }
//! \~english Translate line by point coordinates.
//! \~russian Сдвинуть линию по двум координатам на величину координат точки \a PIPoint.
PILine<Type> operator+(const PIPoint<Type> & p) { return translated(p); }
//! \~english Translate line by negative point coordinates.
//! \~russian Сдвинуть линию по двум координатам на величину координат точки \a PIPoint.
PILine<Type> operator-(const PIPoint<Type> & p) { return translated(-p); }
//! \~english Check equality of two lines.
//! \~russian Проверить равенство координат двух отрезков.
bool operator==(const PILine<Type> & r) const { return (p0 == r.p0 && p1 == r.p1); }
//! \~english Check inequality of two lines.
//! \~russian Проверить неравенство координат двух отрезков.
bool operator!=(const PILine<Type> & r) const { return (p1 != r.p1 || p1 != r.p1); }
};
//! \~english Stream output operator for PILine.
//! \~russian Перегруженный оператор для вывода координат в \a PICout.
template<typename Type>
PICout operator<<(PICout & s, const PILine<Type> & v) {

View File

@@ -1,9 +1,13 @@
/*! \file pimathbase.h
* \ingroup Math
* \~\brief
* \~english Basic mathematical functions and defines
* \~russian Базовые математические функции и дефайны
*/
//! \addtogroup Math
//! \{
//! \file pimathbase.h
//! \brief
//! \~english Basic mathematical functions and defines
//! \~russian Базовые математические функции и дефайны
//! \details
//! \~english Common mathematical constants, conversion functions and utility functions
//! \~russian Общие математические константы, функции преобразования и утилиты
//! \}
/*
PIP - Platform Independent Primitives
Basic mathematical functions and defines
@@ -114,11 +118,29 @@ inline double sinc(const double & v) {
return sin(t) / t;
}
//! Bessel function of the first kind of order 0
//! \~english Bessel function J0(x)
//! \~russian Функция Бесселя первого рода порядка 0
PIP_EXPORT double piJ0(const double & v);
//! Bessel function of the first kind of order 1
//! \~english Bessel function J1(x)
//! \~russian Функция Бесселя первого рода порядка 1
PIP_EXPORT double piJ1(const double & v);
//! Bessel function of the first kind of order n
//! \~english Bessel function Jn(n, x)
//! \~russian Функция Бесселя первого рода порядка n
PIP_EXPORT double piJn(int n, const double & v);
//! Bessel function of the second kind of order 0
//! \~english Bessel function Y0(x)
//! \~russian Функция Бесселя второго рода порядка 0
PIP_EXPORT double piY0(const double & v);
//! Bessel function of the second kind of order 1
//! \~english Bessel function Y1(x)
//! \~russian Функция Бесселя второго рода порядка 1
PIP_EXPORT double piY1(const double & v);
//! Bessel function of the second kind of order n
//! \~english Bessel function Yn(n, x)
//! \~russian Функция Бесселя второго рода порядка n
PIP_EXPORT double piYn(int n, const double & v);
// clang-format off
@@ -129,24 +151,45 @@ inline constexpr float toDeg(float rad) {return rad * M_180_PI;}
inline constexpr double toDeg(double rad) {return rad * M_180_PI;}
inline constexpr ldouble toDeg(ldouble rad) {return rad * M_180_PI;}
// clang-format on
//! Square of a value
//! \~english Returns the square of value v (v * v)
//! \~russian Возвращает квадрат значения v (v * v)
template<typename T>
inline constexpr T sqr(const T & v) {
return v * v;
}
//! Convert linear value to decibels
//! \~english Convert linear value to decibels: 10 * log10(val)
//! \~russian Преобразовать линейное значение в децибелы: 10 * log10(val)
template<typename T>
inline constexpr T toDb(T val) {
return T(10.) * std::log10(val);
}
//! Convert decibels to linear value
//! \~english Convert decibels to linear value: 10^(val/10)
//! \~russian Преобразовать децибелы в линейное значение: 10^(val/10)
template<typename T>
inline constexpr T fromDb(T val) {
return std::pow(T(10.), val / T(10.));
}
// [-1 ; 1]
//! Generate random double in range [-1, 1]
//! \~english Returns random double in range [-1, 1]
//! \~russian Генерирует случайное число double в диапазоне [-1, 1]
PIP_EXPORT double randomd();
// [-1 ; 1] normal
//! Generate random double with normal (Gaussian) distribution
//! \~english Returns random double with normal distribution, mean=dv, stddev=sv
//! \~russian Генерирует случайное число double с нормальным распределением, среднее=dv, стандартное отклонение=sv
PIP_EXPORT double randomn(double dv = 0., double sv = 1.);
//! Absolute value of vector elements
//! \~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 +200,9 @@ inline PIVector<T> piAbs(const PIVector<T> & v) {
}
//! Normalize angle to [0, 360) range (in-place)
//! \~english Normalizes angle to range [0, 360) degrees
//! \~russian Нормализует угол в диапазон [0, 360) градусов (на месте)
template<typename T>
void normalizeAngleDeg360(T & a) {
while (a < 0.)
@@ -164,6 +210,9 @@ void normalizeAngleDeg360(T & a) {
while (a > 360.)
a -= 360.;
}
//! Normalize angle to [0, 360) range
//! \~english Returns angle normalized to range [0, 360) degrees
//! \~russian Возвращает угол нормализованный в диапазон [0, 360) градусов
template<typename T>
double normalizedAngleDeg360(T a) {
normalizeAngleDeg360(a);
@@ -171,6 +220,9 @@ double normalizedAngleDeg360(T a) {
}
//! Normalize angle to (-180, 180] range (in-place)
//! \~english Normalizes angle to range (-180, 180] degrees
//! \~russian Нормализует угол в диапазон (-180, 180] градусов (на месте)
template<typename T>
void normalizeAngleDeg180(T & a) {
while (a < -180.)
@@ -178,6 +230,9 @@ void normalizeAngleDeg180(T & a) {
while (a > 180.)
a -= 360.;
}
//! Normalize angle to (-180, 180] range
//! \~english Returns angle normalized to range (-180, 180] degrees
//! \~russian Возвращает угол нормализованный в диапазон (-180, 180] градусов
template<typename T>
double normalizedAngleDeg180(T a) {
normalizeAngleDeg180(a);
@@ -185,6 +240,13 @@ double normalizedAngleDeg180(T a) {
}
//! Ordinary Least Squares linear regression
//! \~english Calculates linear regression coefficients using OLS method
//! \~russian Вычисляет коэффициенты линейной регрессии методом наименьших квадратов
//! \param input Vector of (x, y) pairs
//! \param out_a Output pointer for slope coefficient (a), can be nullptr
//! \param out_b Output pointer for intercept coefficient (b), can be nullptr
//! \return true on success
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 +269,14 @@ bool OLS_Linear(const PIVector<PIPair<T, T>> & input, T * out_a, T * out_b) {
}
//! Weighted Least Squares linear regression
//! \~english Calculates linear regression coefficients using WLS method
//! \~russian Вычисляет коэффициенты линейной регрессии методом взвешенных наименьших квадратов
//! \param input Vector of (x, y) pairs
//! \param weights Vector of weights for each point
//! \param out_a Output pointer for slope coefficient (a), can be nullptr
//! \param out_b Output pointer for intercept coefficient (b), can be nullptr
//! \return true on success
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");

View File

@@ -32,9 +32,9 @@
/// 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)
@@ -891,9 +891,9 @@ 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)

View File

@@ -1,6 +1,13 @@
/*! \file pimathsolver.h
* \brief PIMathSolver
*/
//! \addtogroup Math
//! \{
//! \file pimathsolver.h
//! \brief
//! \~english Mathematical solver for differential equations
//! \~russian Математический решатель дифференциальных уравнений
//! \details
//! \~english Solver for ordinary differential equations using various numerical methods
//! \~russian Решатель обыкновенных дифференциальных уравнений с использованием различных численных методов
//! \}
/*
PIP - Platform Independent Primitives
PIMathSolver
@@ -27,48 +34,83 @@
/// Differential evaluations
//! Transfer function representation
//! \~english Structure representing transfer function with numerator and denominator coefficients
//! \~russian Структура, представляющая передаточную функцию с коэффициентами числителя и знаменателя
struct PIP_EXPORT TransferFunction {
PIVector<double> vector_Bm, vector_An;
};
//! Mathematical solver for differential equations
//! \~\english Solver for ordinary differential equations using various numerical methods
//! \~russian Решатель обыкновенных дифференциальных уравнений
class PIP_EXPORT PIMathSolver {
public:
//! Solving methods for differential equations
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, //!< Use global method
Eyler_1 = 01, //!< Euler method (first order)
Eyler_2 = 02, //!< Euler method (second order)
EylerKoshi = 03, //!< Euler-Cauchy method
RungeKutta_4 = 14, //!< Runge-Kutta 4th order
AdamsBashfortMoulton_2 = 22, //!< Adams-Bashforth-Moulton 2nd order
AdamsBashfortMoulton_3 = 23, //!< Adams-Bashforth-Moulton 3rd order
AdamsBashfortMoulton_4 = 24, //!< Adams-Bashforth-Moulton 4th order
PolynomialApproximation_2 = 32, //!< Polynomial approximation 2nd order
PolynomialApproximation_3 = 33, //!< Polynomial approximation 3rd order
PolynomialApproximation_4 = 34, //!< Polynomial approximation 4th order
PolynomialApproximation_5 = 35 //!< Polynomial approximation 5th order
};
//! Constructs an empty solver
PIMathSolver();
//! Solve differential equation with step h
//! \~english Solve differential equation at point u with step h
//! \~russian Решить дифференциальное уравнение в точке u с шагом h
void solve(double u, double h);
//! Initialize from transfer function
//! \~english Set up solver from transfer function coefficients
//! \~russian Инициализировать решатель из коэффициентов передаточной функции
void fromTF(const TransferFunction & TF);
//! Set solving method
//! \~english Set numerical method for solving
//! \~russian Установить численный метод решения
void setMethod(Method m) { method = m; }
//! Set simulation time
//! \~english Set simulation time
//! \~russian Установить время моделирования
void setTime(double time);
//! Solve using Euler method (1st order)
void solveEyler1(double u, double h);
//! Solve using Euler method (2nd order)
void solveEyler2(double u, double h);
//! Solve using Runge-Kutta 4th order
void solveRK4(double u, double h);
//! Solve using Adams-Bashforth-Moulton 2nd order
void solveABM2(double u, double h);
//! Solve using Adams-Bashforth-Moulton 3rd order
void solveABM3(double u, double h);
//! Solve using Adams-Bashforth-Moulton 4th order
void solveABM4(double u, double h);
//! Solve using polynomial approximation
void solvePA(double u, double h, uint deg);
//! Solve using polynomial approximation 2nd order
void solvePA2(double u, double h);
//! Solve using polynomial approximation 3rd order
void solvePA3(double u, double h);
//! Solve using polynomial approximation 4th order
void solvePA4(double u, double h);
//! Solve using polynomial approximation 5th order
void solvePA5(double u, double h);
//! Solution vector
PIMathVectord X;
//! Global default method
static Method method_global;
//! Description of available methods
static const char methods_desc[];
private:

View File

@@ -1,9 +1,13 @@
/*! \file pimathvector.h
* \ingroup Math
* \~\brief
* \~english Math vector
* \~russian Математический вектор
*/
//! \addtogroup Math
//! \{
//! \file pimathvector.h
//! \brief
//! \~english Math vector
//! \~russian Математический вектор
//! \details
//! \~english Fixed-size and dynamic mathematical vector implementations
//! \~russian Реализации математических векторов фиксированного и динамического размера
//! \}
/*
PIP - Platform Independent Primitives
PIMathVector
@@ -40,6 +44,9 @@ class PIMathMatrixT;
#define PIMV_FOR for (uint i = 0; i < Size; ++i)
//! Fixed-size mathematical vector
//! \~english Template class for fixed-size mathematical vector
//! \~russian Шаблонный класс для математического вектора фиксированного размера
template<uint Size, typename Type = double>
class PIP_EXPORT PIMathVectorT {
typedef PIMathVectorT<Size, Type> _CVector;
@@ -360,6 +367,9 @@ typedef PIMathVectorT<4u, double> PIMathVectorT4d;
#define PIMV_FOR for (uint i = 0; i < c.size(); ++i)
//! Dynamic-size mathematical vector
//! \~english Template class for dynamic-size mathematical vector
//! \~russian Шаблонный класс для математического вектора динамического размера
template<typename Type>
class PIP_EXPORT PIMathVector {
typedef PIMathVector<Type> _CVector;

View File

@@ -40,12 +40,15 @@ public:
Type x;
Type y;
//! \~english Creates a new point.
//! \~russian Создает новую точку.
PIPoint() { x = y = Type(); }
//! \~english Creates a new point with given coordinates.
//! \~russian Создает новую точку с заданными координатами.
PIPoint(Type x_, Type y_) { set(x_, y_); }
//! \~english Set new coordinates for the point.
//! \~russian Задать новые координаты точке.
PIPoint<Type> & set(Type x_, Type y_) {
x = x_;
@@ -53,6 +56,7 @@ public:
return *this;
}
//! \~english Set new coordinates from another point.
//! \~russian Задать новые координаты точке.
PIPoint<Type> & set(const PIPoint<Type> & p) {
x = p.x;
@@ -60,6 +64,7 @@ public:
return *this;
}
//! \~english Translate the point by x and y.
//! \~russian Переместить точку.
PIPoint<Type> & translate(Type x_, Type y_) {
x += x_;
@@ -67,6 +72,7 @@ public:
return *this;
}
//! \~english Translate the point by another point.
//! \~russian Переместить точку.
PIPoint<Type> & translate(const PIPoint<Type> & p) {
x += p.x;
@@ -74,6 +80,7 @@ public:
return *this;
}
//! \~english Create a copy of the point and translate it.
//! \~russian Создать копию точки и переместить её.
PIPoint<Type> translated(Type x_, Type y_) const {
PIPoint<Type> rp(*this);
@@ -81,6 +88,7 @@ public:
return rp;
}
//! \~english Create a copy of the point and translate it by another point.
//! \~russian Создать копию точки и переместить её.
PIPoint<Type> translated(const PIPoint<Type> & p) const {
PIPoint<Type> rp(*this);
@@ -88,14 +96,17 @@ public:
return rp;
}
//! \~english Translate the point. Alias for \a translate().
//! \~russian Переместить точку.
//! \details Является копией метода \a translate().
PIPoint<Type> & move(Type x_, Type y_) { return translate(x_, y_); }
//! \~english Translate the point by another point. Alias for \a translate().
//! \~russian Переместить точку.
//! \details Является копией метода \a translate().
PIPoint<Type> & move(const PIPoint<Type> & p) { return translate(p); }
//! \~english Create a copy of the point and translate it. Alias for \a translated().
//! \~russian Создать копию точки и переместить её.
//! \details Является копией метода \a translated().
PIPoint<Type> moved(Type x_, Type y_) const {
@@ -104,6 +115,7 @@ public:
return rp;
}
//! \~english Create a copy of the point and translate it by another point. Alias for \a translated().
//! \~russian Создать копию точки и переместить её.
//! \details Является копией метода \a translated().
PIPoint<Type> moved(const PIPoint<Type> & p) const {
@@ -112,65 +124,82 @@ public:
return rp;
}
//! \~english Calculate angle in radians in polar coordinate system.
//! \~russian Посчитать угол(радианы) в поолярной системе координат.
double angleRad() const { return atan2(y, x); }
//! \~english Calculate angle in degrees in polar coordinate system.
//! \~russian Посчитать угол(градусы) в поолярной системе координат.
double angleDeg() const { return toDeg(atan2(y, x)); }
//! \~english Convert copy of point to polar coordinate system.
//! \~russian Перевести копию точки в полярную систему координат.
PIPoint<Type> toPolar(bool isDeg = false) const { return PIPoint<Type>(sqrt(x * x + y * y), isDeg ? angleDeg() : angleRad()); }
//! \~english Convert point from polar to cartesian coordinate system.
//! \~russian Перевести копию точки из полярной системы координат в декартовую.
static PIPoint<Type> fromPolar(const PIPoint<Type> & p) { return PIPoint<Type>(p.y * cos(p.x), p.y * sin(p.x)); }
//! \~russian
//! Прибавить координаты второй точки и сохранить.
//! \~english Add second point coordinates and save.
//! \~russian Прибавить координаты второй точки и сохранить.
//! \details Является копией метода \a translate().
PIPoint<Type> & operator+=(const PIPoint<Type> & p) {
translate(p);
return *this;
}
//! \~english Multiply coordinates by value.
PIPoint<Type> & operator*=(Type v) {
x *= v;
y *= v;
return *this;
}
//! \~english Divide coordinates by value.
PIPoint<Type> & operator/=(Type v) {
x /= v;
y /= v;
return *this;
}
//! \~english Add coordinates of two points.
//! \~russian Сложить координаты двух точек.
PIPoint<Type> operator+(const PIPoint<Type> & p) { return PIPoint<Type>(x + p.x, y + p.y); }
//! \~english Add value to both coordinates.
//! \~russian Прибавить к координатам одинаковое значение.
PIPoint<Type> operator+(const Type & p) { return PIPoint<Type>(x + p, y + p); }
//! \~english Subtract second point coordinates - get offset.
//! \~russian Вычесть из координат координаты второй точки - найти смещение.
PIPoint<Type> operator-(const PIPoint<Type> & p) { return PIPoint<Type>(x - p.x, y - p.y); }
//! \~english Subtract value from both coordinates.
//! \~russian Вычесть из координат одинаковое значение.
PIPoint<Type> operator-(const Type & p) { return PIPoint<Type>(x - p, y - p); }
//! \~english Invert point coordinates.
//! \~russian Инвертировать координаты точки.
PIPoint<Type> operator-() { return PIPoint<Type>(-x, -y); }
//! \~english Multiply point coordinates.
//! \~russian Умножить координаты точки.
PIPoint<Type> operator*(Type v) { return PIPoint<Type>(x * v, y * v); }
//! \~english Divide point coordinates.
//! \~russian Делить координаты точки.
PIPoint<Type> operator/(Type v) { return PIPoint<Type>(x / v, y / v); }
//! \~english Check equality of two points.
//! \~russian Проверить равенство координат двух точек.
bool operator==(const PIPoint<Type> & p) const { return (x == p.x && y == p.y); }
//! \~english Check inequality of two points.
//! \~russian Проверить неравенство координат двух точек.
bool operator!=(const PIPoint<Type> & p) const { return (x != p.x || y != p.y); }
};
//! \~english Stream output operator for PIPoint.
//! \~russian Перегруженный оператор для вывода координат в \a PICout.
template<typename Type>
PICout operator<<(PICout & s, const PIPoint<Type> & v) {

View File

@@ -1,9 +1,13 @@
/*! \file piquaternion.h
* \ingroup Math
* \~\brief
* \~english Quaternion
* \~russian Кватернион
*/
//! \addtogroup Math
//! \{
//! \file piquaternion.h
//! \brief
//! \~english Quaternion
//! \~russian Кватернион
//! \details
//! \~english Quaternion for 3D rotations and orientations
//! \~russian Кватернион для 3D вращений и ориентаций
//! \}
/*
PIP - Platform Independent Primitives
Class for quaternions
@@ -28,29 +32,69 @@
#include "pimathmatrix.h"
//! \~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();
//! Get/Set scalar component
double & scalar() { return q[0]; }
//! Get scalar component
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:

View File

@@ -38,17 +38,18 @@ class PIP_EXPORT PIRect {
static_assert(std::is_arithmetic<Type>::value, "Type must be arithmetic");
public:
//!
//! \~english Default constructor.
//! \~russian Конструктор по умолчанию.
PIRect() {}
//! \brief
//! \~english Constructor from bottom-left corner coordinates and width/height.
//! \~russian Конструктор прямоугольника из координат левого нижнего угла и размеров ширины и высоты
PIRect(Type left_, Type bottom_, Type width_, Type height_) {
set(left_, bottom_, width_, height_);
normalize();
}
//! \brief
//! \~english Constructor from bottom-left and top-right points.
//! \~russian Конструктор прямоугольника из координат левого нижнего угла и правого верхнего угла
PIRect(const PIPoint<Type> & bottom_left, const PIPoint<Type> & top_right) {
bl = bottom_left;
@@ -61,128 +62,128 @@ public:
// piMax<Type>(p0.x, p1.x, p2.x), piMax<Type>(p0.y, p1.y, p2.y));
// }
//!
//! \~english Set rectangle from coordinates and dimensions.
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 Set rectangle from two points.
PIRect<Type> & set(const PIPoint<Type> & top_left, const PIPoint<Type> & bottom_right) {
bl = top_left;
tr = bottom_right;
return normalize();
}
//! \brief
//! \~english Check if point with given coordinates is inside the rectangle.
//! \~russian Возвращает true если точка с указанными координатами принадлежит прямоугольнику
bool pointIn(Type x, Type y) const { return (x <= bl.x && x >= tr.x && y <= bl.y && y >= tr.y); }
//! \brief
//! \~english Check if point is inside the rectangle.
//! \~russian Возвращает true если точка с указанными координатами принадлежит прямоугольнику
bool pointIn(const PIPoint<Type> & p) const { return pointIn(p.x, p.y); }
//!
//! \~english Check if rectangle is empty.
bool isEmpty() const { return (width() == 0 && height() == 0); }
//!
//! \~english Translate rectangle by x and y.
PIRect<Type> & translate(Type x, Type y) {
bl.translate(x, y);
tr.translate(x, y);
return *this;
}
//!
//! \~english Translate rectangle by point.
PIRect<Type> & translate(const PIPoint<Type> & p) {
bl.translate(p);
tr.translate(p);
return *this;
}
//!
//! \~english Create a copy of rectangle and translate it by x and y.
PIRect<Type> translated(Type x, Type y) const {
PIRect<Type> r(*this);
r.translate(x, y);
return r;
}
//!
//! \~english Create a copy of rectangle and translate it by point.
PIRect<Type> translated(const PIPoint<Type> & p) const {
PIRect<Type> r(*this);
r.translate(p);
return r;
}
//!
//! \~english Translate rectangle by x and y. Alias for \a translate().
PIRect<Type> & move(Type x, Type y) { return translate(x, y); }
//!
//! \~english Translate rectangle by point. Alias for \a translate().
PIRect<Type> & move(const PIPoint<Type> & p) { return translate(p); }
//!
//! \~english Create a copy of rectangle and translate it by x and y. Alias for \a translated().
PIRect<Type> moved(Type x, Type y) const {
PIRect<Type> r(*this);
r.translate(x, y);
return r;
}
//!
//! \~english Create a copy of rectangle and translate it by point. Alias for \a translated().
PIRect<Type> moved(const PIPoint<Type> & p) const {
PIRect<Type> r(*this);
r.translate(p);
return r;
}
//!
//! \~english Scale rectangle by x and y factors.
PIRect<Type> & scale(Type x, Type y) {
setWidth(width() * x);
setHeight(height() * y);
return normalize();
}
//!
//! \~english Scale rectangle uniformly.
PIRect<Type> & scale(Type s) { return scale(s, s); }
//!
//! \~english Scale rectangle by point factors.
PIRect<Type> & scale(const PIPoint<Type> & p) { return scale(p.x, p.y); }
//!
//! \~english Create a copy of rectangle and scale it by x and y factors.
PIRect<Type> scaled(Type x, Type y) const {
PIRect<Type> r(*this);
r.scale(x, y);
return r;
}
//!
//! \~english Create a copy of rectangle and scale it uniformly.
PIRect<Type> scaled(Type s) const {
PIRect<Type> r(*this);
r.scale(s);
return r;
}
//!
//! \~english Create a copy of rectangle and scale it by point factors.
PIRect<Type> scaled(const PIPoint<Type> & p) const {
PIRect<Type> r(*this);
r.scale(p);
return r;
}
//!
//! \~english Normalize rectangle so that left <= right and bottom <= top.
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 Create normalized copy of rectangle.
PIRect<Type> normalized() const {
PIRect<Type> r(*this);
r.normalize();
return r;
}
//!
//! \~english Unite rectangle with another rectangle.
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 +192,14 @@ public:
return normalize();
}
//!
//! \~english Create united copy of rectangle with another rectangle.
PIRect<Type> united(const PIRect<Type> & rect) const {
PIRect<Type> r(*this);
r.unite(rect);
return r;
}
//!
//! \~english Intersect rectangle with another rectangle.
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 +209,101 @@ public:
return *this;
}
//!
//! \~english Create intersected copy of rectangle with another rectangle.
PIRect<Type> intersected(const PIRect<Type> & rect) const {
PIRect<Type> r(*this);
r.intersect(rect);
return r;
}
//!
//! \~english Get top coordinate.
Type top() const { return tr.y; }
//!
//! \~english Get left coordinate.
Type left() const { return bl.x; }
//!
//! \~english Get right coordinate.
Type right() const { return tr.x; }
//!
//! \~english Get bottom coordinate.
Type bottom() const { return bl.y; }
//!
//! \~english Get rectangle width.
Type width() const { return tr.x - bl.x; }
//!
//! \~english Get rectangle height.
Type height() const { return tr.y - bl.y; }
//!
//! \~english Get top-left corner point.
PIPoint<Type> topLeft() const { return PIPoint<Type>(bl.x, tr.y); }
//!
//! \~english Get top-right corner point.
PIPoint<Type> topRigth() const { return tr; }
//!
//! \~english Get bottom-left corner point.
PIPoint<Type> bottomLeft() const { return bl; }
//!
//! \~english Get bottom-right corner point.
PIPoint<Type> bottomRight() const { return PIPoint<Type>(tr.x, bl.y); }
//!
//! \~english Get center point of rectangle.
PIPoint<Type> center() const { return bl.moved(width() / 2, height() / 2); }
//!
//! \~english Set top coordinate.
void setTop(Type v) {
tr.y = v;
normalize();
}
//!
//! \~english Set left coordinate.
void setLeft(Type v) {
bl.x = v;
normalize();
}
//!
//! \~english Set right coordinate.
void setRigth(Type v) {
tr.x = v;
normalize();
}
//!
//! \~english Set bottom coordinate.
void setBottom(Type v) {
bl.y = v;
normalize();
}
//!
//! \~english Set rectangle width.
void setWidth(Type v) { setTop(bl.x + v); }
//!
//! \~english Set rectangle height.
void setHeight(Type v) { setRigth(bl.y + v); }
//!
//! \~english Set top-left corner point.
void setTopLeft(const PIPoint<Type> & p) {
setLeft(p.x);
setTop(p.y);
}
//!
//! \~english Set bottom-right corner point.
void setBottomRight(const PIPoint<Type> & p) {
setRigth(p.x);
setBottom(p.y);
}
//!
//! \~english Set bottom-left corner point.
void setBottomLeft(const PIPoint<Type> & p) {
bl = p;
normalize();
}
//!
//! \~english Set top-right corner point.
void setTopRigth(const PIPoint<Type> & p) {
tr = p;
normalize();
}
//!
//! \~english Set center point.
void setCenter(const PIPoint<Type> & p) {
Type w = width();
Type h = height();
@@ -310,46 +311,46 @@ public:
tr = PIPoint<Type>(bl.x + w, bl.y + h);
}
//!
//! \~english Set rectangle size.
void setSize(Type w, Type h) {
tr = PIPoint<Type>(bl.x + w, bl.y + h);
normalize();
}
//!
//! \~english Translate rectangle by x on both coordinates.
void operator+=(Type x) { translate(x, x); }
//!
//! \~english Translate rectangle by point.
void operator+=(const PIPoint<Type> & p) { translate(p); }
//!
//! \~english Translate rectangle by negative x on both coordinates.
void operator-=(Type x) { translate(-x, -x); }
//!
//! \~english Translate rectangle by negative point.
void operator-=(const PIPoint<Type> & p) { translate(-p); }
//!
//! \~english Unite rectangle with another.
void operator|=(const PIRect<Type> & r) { unite(r); }
//!
//! \~english Intersect rectangle with another.
void operator&=(const PIRect<Type> & r) { intersect(r); }
//!
//! \~english Translate rectangle by point.
PIRect<Type> operator+(const PIPoint<Type> & p) { return translated(p); }
//!
//! \~english Translate rectangle by negative point.
PIRect<Type> operator-(const PIPoint<Type> & p) { return translated(-p); }
//!
//! \~english Unite rectangle with another.
PIRect<Type> operator|(const PIRect<Type> & r) { return united(r); }
//!
//! \~english Intersect rectangle with another.
PIRect<Type> operator&(const PIRect<Type> & r) { return intersected(r); }
//!
//! \~english Check equality of two rectangles.
bool operator==(const PIRect<Type> & r) const { return (bl == r.bl && tr == r.tr); }
//!
//! \~english Check inequality of two rectangles.
bool operator!=(const PIRect<Type> & r) const { return (bl != r.bl || tr != r.tr); }
private:
@@ -357,7 +358,8 @@ private:
PIPoint<Type> tr;
};
//! \~english Stream output operator for PIRect.
//! \~russian Перегруженный оператор для вывода прямоугольника в \a PICout.
template<typename Type>
PICout operator<<(PICout & s, const PIRect<Type> & v) {
s.space();

View File

@@ -1,9 +1,13 @@
/*! \file pistatistic.h
* \ingroup Math
* \~\brief
* \~english Calculating math statistic of values array
* \~russian Вычисление математической статистики у массива чисел
*/
//! \addtogroup Math
//! \{
//! \file pistatistic.h
//! \brief
//! \~english Calculating math statistic of values array
//! \~russian Вычисление математической статистики у массива чисел
//! \details
//! \~english Template class for calculating statistical measures of a data set
//! \~russian Шаблонный класс для вычисления статистических характеристик набора данных
//! \}
/*
PIP - Platform Independent Primitives
Class for calculacing math statistic in values array
@@ -28,13 +32,20 @@
#include "pimathbase.h"
//! Statistical calculator template class
//! \~english Template class for calculating statistical measures (mean, variance, skewness, kurtosis)
//! \~russian Шаблонный класс для вычисления статистических показателей (среднее, дисперсия, асимметрия, эксцесс)
template<typename T>
class PIStatistic {
static_assert(std::is_arithmetic<T>::value, "Type must be arithmetic");
public:
//! Construct empty statistic calculator
PIStatistic() { mean = variance = skewness = kurtosis = T(); }
//! Calculate arithmetic mean
//! \~english Calculate arithmetic mean of values
//! \~russian Вычислить среднее арифметическое значение
static T calculateMean(const PIVector<T> & val) {
T ret = T();
int n = val.size();
@@ -43,10 +54,13 @@ public:
ret += val[i];
return ret / n;
}
//! Calculate all statistics with given mean
//! \~english Calculate variance, skewness and kurtosis using provided mean value
//! \~russian Вычислить дисперсию, асимметрию и эксцесс с использованием заданного среднего значения
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,11 +86,18 @@ public:
}
return true;
}
//! Calculate all statistics
//! \~english Calculate mean, variance, skewness and kurtosis
//! \~russian Вычислить среднее, дисперсию, асимметрию и эксцесс
bool calculate(const PIVector<T> & val) { return calculate(val, calculateMean(val)); }
//! Arithmetic mean
T mean;
//! Variance
T variance;
//! Skewness (third standardized moment)
T skewness;
//! Kurtosis (fourth standardized moment)
T kurtosis;
};