diff --git a/libs/main/math/piline.h b/libs/main/math/piline.h index 6d43bfeb..b26e9f42 100644 --- a/libs/main/math/piline.h +++ b/libs/main/math/piline.h @@ -42,120 +42,142 @@ public: PIPoint p0; PIPoint p1; - //! + //! \~russian + //! Пустой конструктор. + //! \details + //! При выполнении пустого конструктора координаты не изменяются. + //! Начало и конец совпадают. PILine() {} - //! + //! \~russian + //! Создает линию по двум принятым точкам \a PIPoint начала и конца. PILine(const PIPoint & p0_, const PIPoint & p1_) { p0 = p0_; p1 = p1_; } - //! + //! \~russian + //! Создает линию по принятым координатам начала и конца. PILine(Type x0, Type y0, Type x1, Type y1) { p0.set(x0, y0); p1.set(x1, y1); } - //! + //! \~russian + //! Задать новые координаты начала и конца по двум принятым точкам \a PIPoint. PILine & set(const PIPoint & p0_, const PIPoint & p1_) { p0 = p0_; p1 = p1_; return *this; } - //! + //! \~russian + //! Задать новые координаты начала и конца. PILine & set(Type x0, Type y0, Type x1, Type y1) { p0.set(x0, y0); p1.set(x1, y1); return *this; } - //! + //! \~russian + //! Проверить на совпадение координат начала и конца. bool isEmpty() const { return (p0 == p1); } - //! + //! \~russian + //! Вычислить ширину прямоугольника, диагональю которого является данный отрезок. Type width() const {return piAbs(p1.x - p0.x);} - //! + //! \~russian + //! Вычислить высоту прямоугольника, диагональю которого является данный отрезок. Type height() const {return piAbs(p1.y - p0.y);} - //! + //! \~russian + //! Сдвинуть линию на \a x, \a y. PILine & translate(Type x, Type y) { p0.translate(x, y); p1.translate(x, y); return *this; } - //! + //! \~russian + //! Сдвинуть линию на значение координат точки \a PIPoint. PILine & translate(const PIPoint & p) { p0.translate(p); p1.translate(p); return *this; } - //! + //! Создать копию отрезка и сдвинуть её на `x` и `y`. PILine translated(Type x, Type y) const { PILine l(*this); l.translate(x, y); return l; } - //! + //! \~russian + //! Создать копию отрезка и сдвинуть её на значение координат точки \a PIPoint. PILine translated(const PIPoint & p) const { PILine l(*this); l.translate(p); return l; } - //! + //! \~russian + //! Сдвинуть линию на \a x, \a y. + //! \details Является копией метода \a translate(). PILine & move(Type x, Type y) {return translate(x, y);} - //! + //! \~russian + //! Сдвинуть линию на значение координат точки \a PIPoint. + //! \details Является копией метода \a translate(). PILine & move(const PIPoint & p) {return translate(p);} - //! + //! \~russian + //! Создать копию отрезка и сдвинуть её на \a x, \a y. + //! \details Является копией метода \a translated(). PILine moved(Type x, Type y) const { PILine l(*this); l.translate(x, y); return l; } - - //! + + //! \~russian + //! Создать копию отрезка и сдвинуть её на значение координат точки \a PIPoint. + //! \details Является копией метода \a translated(). PILine moved(const PIPoint & p) const { PILine l(*this); l.translate(p); return l; } - //! + //! \~russian Сдвинуть линию по двум координатам на значение \a x. void operator +=(Type x) {translate(x, x);} - //! + //! \~russian Сдвинуть линию по двум координатам на величину координат точки \a PIPoint. void operator +=(const PIPoint & p) {translate(p);} - //! + //! \~russian Сдвинуть линию по двум координатам на значение \a x. void operator -=(Type x) {translate(-x, -x);} - //! + //! \~russian Сдвинуть линию по двум координатам на величину координат точки \a PIPoint. void operator -=(const PIPoint & p) {translate(-p);} - //! + //! \~russian Сдвинуть линию по двум координатам на величину координат точки \a PIPoint. PILine operator +(const PIPoint & p) {return translated(p);} - //! + //! \~russian Сдвинуть линию по двум координатам на величину координат точки \a PIPoint. PILine operator -(const PIPoint & p) {return translated(-p);} - //! + //! \~russian Проверить равенство координат двух отрезков. bool operator ==(const PILine & r) const {return (p0 == r.p0 && p1 == r.p1);} - //! + //! \~russian Проверить неравенство координат двух отрезков. bool operator !=(const PILine & r) const {return (p1 != r.p1 || p1 != r.p1);} }; - +//! \~russian Перегруженный оператор для вывода координат в \a PICout. template PICout operator <<(PICout & s, const PILine & v) { s.setControl(0, true); diff --git a/libs/main/math/pimathmatrix.h b/libs/main/math/pimathmatrix.h index 92a48b7d..1e96a3e5 100644 --- a/libs/main/math/pimathmatrix.h +++ b/libs/main/math/pimathmatrix.h @@ -1,9 +1,9 @@ -/*! \file pimathmatrix.h - * \ingroup Math - * \~\brief - * \~english Math matrix - * \~russian Математическая матрица - */ +//! \file pimathmatrix.h +//! \ingroup Math +//! \~\brief +//! \~english Math matrix +//! \~russian Математическая матрица + /* PIP - Platform Independent Primitives PIMathMatrix @@ -38,11 +38,18 @@ #pragma pack(push, 1) -//! \brief A class that works with square matrix operations, the input data of which are columns, rows and the data type of the 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(=, +=, -=, *=, /=, ==, !=, +, -, *, /) +//! \~english +//! \brief A class that works with square matrix operations, the input data of which are columns, rows and the data type of the 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 +//! \~russian +//! \brief Класс, работающий с операциями над квадратными матрицами, входными данными которого являются столбцы, строки и матричный типа данных. +//! \tparam `Rows` количество строк матрицы. +//! \tparam `Сols` количество столбцов матрицы. +//! \tparam `Type`типа данных матрицы. Здесь можеть быть базовый тип данных C++ или различные классы, +//! где реализованы арифметические операторы(=, +=, -=, *=, /=, ==, !=, +, -, *, /) языка C++. template class PIP_EXPORT PIMathMatrixT { typedef PIMathMatrixT _CMatrix; @@ -53,337 +60,410 @@ class PIP_EXPORT PIMathMatrixT { static_assert(Rows > 0, "Row count must be > 0"); static_assert(Cols > 0, "Column count must be > 0"); public: - /** - * \brief Constructs PIMathMatrixT that is filled by \a new_value - */ + //! \~english + //! \brief Constructs \a PIMathMatrixT that is filled by \a new_value. + //! \~russian + //! \brief Создает \a PIMathMatrixT и заполняет её из \a new_value. PIMathMatrixT(const Type &new_value = Type()) {PIMM_FOR m[r][c] = new_value;} - /** - * \brief Contructs PIMathMatrixT from PIVector - */ + //! \~english + //! \brief Contructs \a PIMathMatrixT from \a PIVector. + //! \~russian + //! \brief Создает \a PIMathMatrixT и заполняет её из \a PIVector. PIMathMatrixT(const PIVector &val) { assert(Rows*Cols == val.size()); int i = 0; PIMM_FOR m[r][c] = val[i++]; } - /** - * \brief Contructs PIMathMatrixT from C++11 initializer list - */ + //! \~english + //! \brief Contructs \a PIMathMatrixT from [C++11 initializer list](https://en.cppreference.com/w/cpp/utility/initializer_list). + //! \~russian + //! \brief Создает \a PIMathMatrixT и заполняет её из [списка инициализации C++11](https://ru.cppreference.com/w/cpp/utility/initializer_list). PIMathMatrixT(std::initializer_list init_list) { assert(Rows*Cols == init_list.size()); int i = 0; PIMM_FOR m[r][c] = init_list.begin()[i++]; } - /** - * \brief Сreates a matrix whose main diagonal is filled with ones and the remaining elements are zeros - * - * @return identity matrix of type PIMathMatrixT - */ - static _CMatrix identity() { - _CMatrix tm = _CMatrix(); + //! \~english + //! \brief Сreates a matrix whose main diagonal is filled with ones and the remaining elements are zeros. + //! \return identity matrix of type \a PIMathMatrixT. + //! \~russian + //! \brief Создает матрицу, главная диагональ которой заполнена единицами, а остальные элементы — нулями. + //! \return единичная матрица типа \a PIMathMatrixT. + static PIMathMatrixT identity() { + PIMathMatrixT tm = PIMathMatrixT(); PIMM_FOR tm.m[r][c] = (c == r ? Type(1) : Type(0)); return tm; } - /** - * \brief Method which returns number of columns in matrix - * - * @return type uint shows number of columns - */ + //! \~english + //! \brief Method which returns number of columns in matrix. + //! \return type \a uint shows number of columns. + //! \~russian + //! \brief Метод возвращающий количество столбцов в матрице. + //! \return \a uint количество столбцов. constexpr uint cols() const {return Cols;} - /** - * \brief Method which returns number of rows in matrix - * - * @return type uint shows number of rows - */ + //! \~english + //! \brief Method which returns number of rows in matrix. + //! \return type uint shows number of rows. + //! \~russian + //! \brief Метод возвращающий количество строк в матрице. + //! \return \a uint количество строк. constexpr uint rows() const {return Rows;} - /** - * \brief Method which returns the selected column in PIMathVectorT format. - * If you enter an index out of the border of the matrix there will be "undefined behavior" - * - * @param index is the number of the selected column - * @return column in PIMathVectorT format - */ - _CMCol col(uint index) { - _CMCol tv; + //! \~english + //! \brief Method which returns the selected column in PIMathVectorT format. + //! \details If you enter an index out of the border of the matrix there will be "undefined behavior". + //! \param index is the number of the selected column. + //! \return column in PIMathVectorT format. + //! \~russian + //! \brief Метод возвращающий выбранную строку в формате \a PIMathVectorT. + //! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior"). + //! \param index номер выбранного столбца. + //! \return столбец в формате \a PIMathVectorT. + PIMathVectorT col(uint index) { + PIMathVectorT tv; PIMM_FOR_R tv[i] = m[i][index]; return tv; } - /** - * \brief Method which returns the selected row in PIMathVectorT format - * If you enter an index out of the border of the matrix there will be "undefined behavior" - * - * @param index is the number of the selected row - * @return row in PIMathVectorT format - */ - _CMRow row(uint index) { - _CMRow tv; + //! \brief Method which returns the selected row in PIMathVectorT format. + //! \details If you enter an index out of the border of the matrix there will be "undefined behavior". + //! \param index is the number of the selected row. + //! \return row in PIMathVectorT format. + //! \~russian + //! \brief Метод возвращающий выбранный столбец в формате \a PIMathVectorT. + //! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior"). + //! \param index номер выбранной строки. + //! \return строка в формате \a PIMathVectorT. + PIMathVectorT row(uint index) { + PIMathVectorT tv; PIMM_FOR_C tv[i] = m[index][i]; return tv; } - /** - * \brief Set the selected column in matrix. - * If you enter an index out of the border of the matrix there will be "undefined behavior" - * - * @param index is the number of the selected column - * @param v is a vector of the type _CMCol that needs to fill the column - * @return matrix type _CMatrix - */ - _CMatrix &setCol(uint index, const _CMCol &v) { + //! \~english + //! \brief Set the selected column in matrix. + //! \details If you enter an index out of the border of the matrix there will be "undefined behavior". + //! \param index is the number of the selected column. + //! \param v is a vector of the type \a PIMathVectorT that needs to fill the column. + //! \return matrix type \a PIMathMatrixT. + //! \~russian + //! \brief Определить выбранный столбец матрицы. + //! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior"). + //! \param index номер выбранного столбца. + //! \param v вектор типа \a PIMathVectorT, которым необходимо заполнить столбец. + //! \return матрица типа \a PIMathMatrixT. + PIMathMatrixT &setCol(uint index, const PIMathVectorT &v) { PIMM_FOR_R m[i][index] = v[i]; return *this; } - /** - * \brief Set the selected row in matrix - * If you enter an index out of the border of the matrix there will be "undefined behavior" - * - * @param index is the number of the selected row - * @param v is a vector of the type _CMCol that needs to fill the row - * @return matrix type _CMatrix - */ - _CMatrix &setRow(uint index, const _CMRow &v) { + //! \~english + //! \brief Set the selected row in matrix. + //! \details If you enter an index out of the border of the matrix there will be "undefined behavior". + //! \param index is the number of the selected row. + //! \param v is a vector of the type PIMathVectorT that needs to fill the row. + //! \return matrix type PIMathMatrixT + //! \~russian + //! \brief Определить выбранную строку матрицы. + //! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior"). + //! \param index номер выбранной строки. + //! \param v вектор типа \a PIMathVectorT, которым необходимо заполнить строку. + //! \return матрица типа \a PIMathMatrixT. + PIMathMatrixT &setRow(uint index, const PIMathVectorT &v) { PIMM_FOR_C m[index][i] = v[i]; return *this; } - /** - * \brief Method which changes selected rows in a matrix. - * If you enter an index out of the border of the matrix there will be "undefined behavior" - * - * @param rf is the number of the first selected row - * @param rs is the number of the second selected row - * @return matrix type _CMatrix - */ - _CMatrix &swapRows(uint rf, uint rs) { + //! \~english + //! \brief Method which swaps the selected rows in a matrix. + //! \details If you enter an index out of the border of the matrix there will be "undefined behavior" + //! \param rf is the number of the first selected row + //! \param rs is the number of the second selected row + //! \return matrix type \a PIMathMatrixT + //! \~russian + //! \brief Метод, меняющий местами выбранные строки в матрице. + //! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior"). + //! \param rf номер первой выбранной строки. + //! \param rs номер второй выбранной строки. + //! \return матрица типа \a PIMathMatrixT. + PIMathMatrixT &swapRows(uint rf, uint rs) { PIMM_FOR_C piSwap(m[rf][i], m[rs][i]); return *this; } - /** - * \brief Method which changes selected columns in a matrix. - * If you enter an index out of the border of the matrix there will be "undefined behavior" - * - * @param cf is the number of the first selected column - * @param cs is the number of the second selected column - * @return matrix type _CMatrix - */ - _CMatrix &swapCols(uint cf, uint cs) { + //! \~english + //! \brief Method which swaps the selected columns in a matrix. + //! \details If you enter an index out of the border of the matrix there will be "undefined behavior" + //! \param cf is the number of the first selected column + //! \param cs is the number of the second selected column + //! \return matrix type \a PIMathMatrixT + //! \~russian + //! \brief Метод, меняющий местами выбранные столбцы в матрице. + //! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior"). + //! \param rf номер первого выбранного столбца. + //! \param rs номер второго выбранного столбца. + //! \return матрица типа \a PIMathMatrixT. + PIMathMatrixT &swapCols(uint cf, uint cs) { PIMM_FOR_R piSwap(m[i][cf], m[i][cs]); return *this; } - /** - * \brief Method which fills the matrix with selected value - * - * @param v is a parameter the type and value of which is selected and later filled into the matrix - * @return filled matrix type _CMatrix - */ - _CMatrix &fill(const Type &v) { + //! \~english + //! \brief Method which fills the matrix with selected value. + //! \param v is a parameter the type and value of which is selected and later filled into the matrix. + //! \return filled matrix type \a PIMathMatrixT. + //! \~russian + //! \brief Метод, заполняющий матрицу выбранным значением. + //! \param v параметр тип и значения, которого выбираются и заносятся в матрицу. + //! \return заполненная матрица типа \a PIMathMatrixT. + PIMathMatrixT &fill(const Type &v) { PIMM_FOR m[r][c] = v; return *this; } - /** - * \brief Method which checks if matrix is square - * - * @return true if matrix is square, else false - */ + //! \~english + //! \brief Method which checks if matrix is square. + //! \return true if matrix is square, else false. + //! \~russian + //! \brief Метод, проверяющий является ли матрицей квадратной. + //! \return true если матрица квадратная, иначе false. constexpr bool isSquare() const { return Rows == Cols; } - /** - * \brief Method which checks if main diagonal of matrix consists of ones and another elements are zeros - * - * @return true if matrix is identitied, else false - */ + //! \~english + //! \brief Method which checks if main diagonal of matrix consists of ones and another elements are zeros. + //! \return true if matrix is identitied, else false. + //! \~russian + //! \brief Метод, проверяющий содержит ли главная диагональ единицы и все остальные поля нули. + //! \return true если матрица единичная, иначе false. bool isIdentity() const { PIMM_FOR if ((c == r) ? m[r][c] != Type(1) : m[r][c] != Type(0)) return false; return true; } - /** - * \brief Method which checks if every elements of matrix are zeros - * - * @return true if matrix is null, else false - */ + //! \~english + //! \brief Method which checks if every elements of matrix are zeros. + //! \return true if matrix is null, else false. + //! \~russian + //! \brief Метод, являются ли все элементы матрицы нулями. + //! \return true если матрица нулевая, иначе false. bool isNull() const { PIMM_FOR if (m[r][c] != Type(0)) return false; return true; } - /** - * \brief Read-only access to element by \a row and \a col. - * If you enter an index out of the border of the matrix there will be "undefined behavior" - * - * @param row of matrix - * @param col of matrix - * @return copy of element of matrix - */ + //! \~english + //! \brief Read-only access to element by `row` number and `col` number. + //! \details If you enter an index out of the border of the matrix there will be "undefined behavior". + //! \param row matrix row number. + //! \param col matrix column number. + //! \return copy of element of matrix. + //! \~russian + //! \brief Доступ только для чтения к элементу по номеру \a строки `row` и номеру \a столбца `col`. + //! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior"). + //! \param row номер строки матрицы. + //! \param col номер столбца матрицы. + //! \return копия элемента матрицы. Type at(uint row, uint col) const { return m[row][col]; } - /** - * \brief Full access to element by \a row and \a col. - * If you enter an index out of the border of the matrix there will be "undefined behavior" - * - * @param row of matrix - * @param col of matrix - * @return element of matrix - */ + //! \~english + //! \brief Full access to element by `row` number and `col` number. + //! \details If you enter an index out of the border of the matrix there will be "undefined behavior" + //! \param row matrix row number. + //! \param col matrix column number. + //! \return element of matrix + //! \~russian + //! \brief Полный доступ к элементу по номеру \a строки `row` и номеру \a столбца `col`. + //! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior"). + //! \param row номер строки матрицы. + //! \param col номер столбца матрицы. + //! \return элемент матрицы. inline Type & element(uint row, uint col) {return m[row][col];} - /** - * \brief Read-only access to element by \a row and \a col. - * If you enter an index out of the border of the matrix there will be "undefined behavior" - * - * @param row of matrix - * @param col of matrix - * @return element of matrix - */ + //! \~english + //! \brief Read-only access to element by `row` number and `col` number. + //! \details If you enter an index out of the border of the matrix there will be "undefined behavior". + //! \param row matrix row number. + //! \param col matrix column number. + //! \return copy of element of matrix. + //! \~russian + //! \brief Доступ только для чтения к элементу по номеру \a строки `row` и номеру \a столбца `col`. + //! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior"). + //! \param row номер строки матрицы. + //! \param col номер столбца матрицы. + //! \return копия элемента матрицы. inline const Type & element(uint row, uint col) const {return m[row][col];} - /** - * \brief Full access to the matrix row pointer. If you enter an index out of the border of the matrix there will be "undefined behavior" - * - * @param row of matrix - * @return matrix row pointer - */ + //! \~english + //! \brief Full access to the matrix row pointer. + //! \details If you enter an index out of the border of the matrix there will be "undefined behavior". + //! \param row matrix row number. + //! \return matrix row pointer + //! \~russian + //! \brief Полный доступ к указателю на строку матрицы. + //! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior"). + //! \param row номер строки матрицы. + //! \return указатель на строку матрицы. Type *operator[](uint row) { return m[row]; } - /** - * \brief Read-only access to the matrix row pointer. If you enter an index out of the border of the matrix there will be "undefined behavior" - * - * @param row of matrix - * @return matrix row pointer - */ + //! \~english + //! \brief Read-only access to the matrix row pointer. + //! \details If you enter an index out of the border of the matrix there will be "undefined behavior". + //! \param row matrix row number. + //! \return matrix row pointer + //! \~russian + //! \brief Доступ только для чтения к указателю на строку матрицы. + //! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior"). + //! \param row номер строки матрицы. + //! \return указатель на строку матрицы. const Type *operator[](uint row) const {return m[row];} - /** - * \brief Matrix compare - * - * @param sm matrix for compare - * @return if matrices are equal true, else false - */ - bool operator==(const _CMatrix &sm) const { + //! \~english + //! \brief Matrix compare. + //! \param sm matrix for compare. + //! \return if matrices are equal true, else false. + //! \~russian + //! \brief Сравнение матриц. + //! \param sm матрица для сравнения. + //! \return если матрицы равны true, иначе false. + bool operator==(const PIMathMatrixT &sm) const { PIMM_FOR if (m[r][c] != sm.m[r][c]) return false; return true; } - /** - * \brief Matrix negative compare - * - * @param sm matrix for compare - * @return if matrices are not equal true, else false - */ - bool operator!=(const _CMatrix &sm) const { return !(*this == sm); } + //! \~english + //! \brief Matrix negative compare. + //! \param sm matrix for compare. + //! \return if matrices are not equal true, else false. + //! \~russian + //! \brief Отрицательное сравнение матриц. + //! \param sm матрица для сравнения. + //! \return если матрицы не равны true, иначе false. + bool operator!=(const PIMathMatrixT &sm) const { return !(*this == sm); } - /** - * \brief Addition assignment with matrix "sm" - * - * @param sm matrix for the addition assigment - */ - void operator+=(const _CMatrix &sm) {PIMM_FOR m[r][c] += sm.m[r][c];} + //! \~english + //! \brief Addition assignment with matrix `sm`. + //! \param sm matrix for the addition assigment. + //! \~russian + //! \brief Сложение с присваиванием с матрицей `sm`. + //! \param sm матрица для сложения с присваиванием. + void operator+=(const PIMathMatrixT &sm) {PIMM_FOR m[r][c] += sm.m[r][c];} - /** - * \brief Subtraction assignment with matrix "sm" - * - * @param sm matrix for the subtraction assigment - */ - void operator-=(const _CMatrix &sm) {PIMM_FOR m[r][c] -= sm.m[r][c];} + //! \~english + //! \brief Subtraction assignment with matrix `sm`. + //! \param sm matrix for the subtraction assigment. + //! \~russian + //! \brief Вычитание с присваиванием с матрицей `sm`. + //! \param sm матрица для вычитания с присваиванием. + void operator-=(const PIMathMatrixT &sm) {PIMM_FOR m[r][c] -= sm.m[r][c];} - /** - * \brief Multiplication assignment with value "v" - * - * @param v value for the multiplication assigment - */ + //! \~english + //! \brief Multiplication assignment with value `v`. + //! \param v value for the multiplication assigment. + //! \~russian + //! \brief Умножение с присваиванием с матрицей `v`. + //! \param sm матрица для умножения с присваиванием. void operator*=(const Type &v) { PIMM_FOR m[r][c] *= v; } - /** - * \brief Division assignment with value "v" - * - * @param v value for the division assigment - */ + //! \~english + //! \brief Division assignment with value `v`. + //! \param v value for the division assigment. + //! \~russian + //! \brief Деление с присваиванием с матрицей `v`. + //! \param sm матрица для деления с присваиванием. void operator/=(const Type &v) { assert(piAbs(v) > PIMATHVECTOR_ZERO_CMP); PIMM_FOR m[r][c] /= v; } - /** - * \brief Matrix substraction - * - * @return the result of matrix substraction - */ - _CMatrix operator-() const { - _CMatrix tm; + //! \~english + //! \brief Negation operation + //! \return copy of the negative matrix + //! \~russian + //! \brief Операция отрицания + //! \return копия отрицательной матрицы + PIMathMatrixT operator-() const { + PIMathMatrixT tm; PIMM_FOR tm.m[r][c] = -m[r][c]; return tm; } - /** - * \brief Matrix addition - * - * @param sm is matrix term - * @return the result of matrix addition - */ - _CMatrix operator+(const _CMatrix &sm) const { - _CMatrix tm = _CMatrix(*this); + //! \~english + //! \brief Matrix addition. + //! \param sm is matrix term. + //! \return the result of matrix addition. + //! \~russian + //! \brief Матричное сложение. + //! \param sm матричное слагаемое. + //! \return результат матричного сложения. + PIMathMatrixT operator+(const PIMathMatrixT &sm) const { + PIMathMatrixT tm = PIMathMatrixT(*this); PIMM_FOR tm.m[r][c] += sm.m[r][c]; return tm; } - /** - * \brief Matrix substraction - * - * @param sm is matrix subtractor - * @return the result of matrix substraction - */ - _CMatrix operator-(const _CMatrix &sm) const { - _CMatrix tm = _CMatrix(*this); + //! \~english + //! \brief Matrix substraction. + //! \param sm is matrix subtrahend. + //! \return the result of matrix substraction. + //! \~russian + //! \brief Матричная разность. + //! \param sm матричное вычитаемое. + //! \return результат матричной разности. + PIMathMatrixT operator-(const PIMathMatrixT &sm) const { + PIMathMatrixT tm = PIMathMatrixT(*this); PIMM_FOR tm.m[r][c] -= sm.m[r][c]; return tm; } - /** - * \brief Matrix multiplication - * - * @param v is value factor - * @return the result of matrix multiplication - */ - _CMatrix operator*(const Type &v) const { - _CMatrix tm = _CMatrix(*this); + //! \~english + //! \brief Matrix multiplication by a constant. + //! \param v is value factor. + //! \return the result of matrix multiplication. + //! \~russian + //! \brief Умножение матрицы на константу. + //! \param v множитель. + //! \return результат произведения. + PIMathMatrixT operator*(const Type &v) const { + PIMathMatrixT tm = PIMathMatrixT(*this); PIMM_FOR tm.m[r][c] *= v; return tm; } - /** - * \brief Matrix division - * - * @param v is value divider - * @return the result of matrix division - */ - _CMatrix operator/(const Type &v) const { + //! \~english + //! \brief Division a matrix by a constant. + //! \param v is value divider. + //! \return the result of matrix division. + //! \~russian + //! \brief Деление матрицы на константу. + //! \param v делитель. + //! \return результат деления. + PIMathMatrixT operator/(const Type &v) const { assert(piAbs(v) > PIMATHVECTOR_ZERO_CMP); - _CMatrix tm = _CMatrix(*this); + PIMathMatrixT tm = PIMathMatrixT(*this); PIMM_FOR tm.m[r][c] /= v; return tm; } - /** - * \brief Determinant of the matrix is ​​calculated. Works only with square matrix, nonzero matrices and invertible matrix - * - * @param ok is a parameter with which we can find out if the method worked correctly - * @return matrix determinant - */ + //! \~english + //! \brief Calculate Determinant of the matrix. + //! \details Works only with square matrix, nonzero matrices and invertible matrix. + //! \param ok is a parameter with which we can find out if the method worked correctly. + //! \return matrix determinant. + //! \~russian + //! \brief Вычислить определитель матрицы. + //! \details Работает только с квадратными, ненулевыми и обратимыми матрицами. + //! \param ok это параметр, с помощью которого мы можем узнать, правильно ли сработал метод. + //! \return опеределитель матрицы. Type determinant(bool *ok = 0) const { - _CMatrix m(*this); + PIMathMatrixT m(*this); bool k; Type ret = Type(0); m.toUpperTriangular(&k); @@ -394,11 +474,14 @@ public: return ret; } - /** - * \brief Trace of the matrix is calculated. Works only with square matrix, nonzero matrices and invertible matrix - * - * @return matrix trace - */ + //! \~english + //! \brief Calculate the trace of a matrix. + //! \details Works only with square matrix. + //! \return matrix trace. + //! \~russian + //! \brief Вычислить след матрицы. + //! \details Работает только с квадратными матрицами. + //! \return след матрицы. Type trace() const { static_assert(Rows == Cols, "Works only with square matrix"); Type ret = Type(0); @@ -408,15 +491,19 @@ public: return ret; } - /** - * \brief Transforming matrix to upper triangular. Works only with square matrix, nonzero matrices and invertible matrix - * - * @param ok is a parameter with which we can find out if the method worked correctly - * @return copy of transformed upper triangular matrix - */ - _CMatrix &toUpperTriangular(bool *ok = 0) { + //! \~english + //! \brief Transforming matrix to upper triangular. + //! \details Works only with square matrix, nonzero matrices and invertible matrix. + //! \param ok is a parameter with which we can find out if the method worked correctly. + //! \return a transformed upper triangular matrix. + //! \~russian + //! \brief Преобразование матрицы в верхнетреугольную. + //! \details Работает только с квадратными, ненулевыми и обратимыми матрицами. + //! \param ok это параметр, с помощью которого мы можем узнать, правильно ли сработал метод. + //! \return преобразованная верхнетреугольная матрицы. + PIMathMatrixT &toUpperTriangular(bool *ok = 0) { static_assert(Rows == Cols, "Works only with square matrix"); - _CMatrix smat(*this); + PIMathMatrixT smat(*this); bool ndet; uint crow; Type mul; @@ -448,15 +535,19 @@ public: return *this; } - /** - * \brief Matrix inversion operation. Works only with square matrix, nonzero matrices and invertible matrix - * - * @param ok is a parameter with which we can find out if the method worked correctly - * @return copy of inverted matrix - */ - _CMatrix &invert(bool *ok = 0) { + //! \~english + //! \brief Matrix inversion operation. + //! \details Works only with square matrix, nonzero matrices and invertible matrix. + //! \param ok is a parameter with which we can find out if the method worked correctly. + //! \return inverted matrix. + //! \~russian + //! \brief Операция обращения матрицы. + //! \details Работает только с квадратными, ненулевыми и обратимыми матрицами. + //! \param ok это параметр, с помощью которого мы можем узнать, правильно ли сработал метод. + //! \return обратная матрица. + PIMathMatrixT &invert(bool *ok = 0) { static_assert(Rows == Cols, "Works only with square matrix"); - _CMatrix mtmp = _CMatrix::identity(), smat(*this); + PIMathMatrixT mtmp = PIMathMatrixT::identity(), smat(*this); bool ndet; uint crow; Type mul, iddiv; @@ -502,35 +593,45 @@ public: return *this; } - /** - * \brief Matrix inversion operation. Works only with square matrix, nonzero matrices and invertible matrix - * - * @param ok is a parameter with which we can find out if the method worked correctly - * @return inverted matrix - */ - _CMatrix inverted(bool *ok = 0) const { - _CMatrix tm(*this); + //! \~english + //! \brief Matrix inversion operation. + //! \details Works only with square matrix, nonzero matrices and invertible matrix. + //! \param ok is a parameter with which we can find out if the method worked correctly. + //! \return copy of inverted matrix. + //! \~russian + //! \brief Операция обращения матрицы. + //! \details Работает только с квадратными, ненулевыми и обратимыми матрицами. + //! \param ok это параметр, с помощью которого мы можем узнать, правильно ли сработал метод. + //! \return копия обратной матрицы. + PIMathMatrixT inverted(bool *ok = 0) const { + PIMathMatrixT tm(*this); tm.invert(ok); return tm; } - /** - * \brief Matrix transposition operation. Works only with square matrix, nonzero matrices and invertible matrix - * - * @return transposed matrix - */ - _CMatrixI transposed() const { - _CMatrixI tm; + //! \~english + //! \brief Matrix transposition operation. + //! \details Works only with square matrix. + //! \return copy of transposed matrix + //! \~russian + //! \brief Транспонирование матрицы. + //! \details Работает только с квадратными матрицами. + //! \return копия транспонированной матрицы. + PIMathMatrixT transposed() const { + PIMathMatrixT tm; PIMM_FOR tm[c][r] = m[r][c]; return tm; } - /** - * \brief Matrix rotation operation. Works only with 2x2 matrix - * - * @return rotated matrix - */ - _CMatrix rotate(Type angle) { + //! \~english + //! \brief Matrix rotation operation. + //! \details Works only with 2x2 matrix. + //! \return rotated matrix. + //! \~russian + //! \brief Операция поворота матрицы. + //! \details Работает только с матрицами 2x2. + //! \return повернутая матрица. + PIMathMatrixT rotate(Type angle) { static_assert(Rows == 2 && Cols == 2, "Works only with 2x2 matrix"); Type c = std::cos(angle); Type s = std::sin(angle); @@ -542,6 +643,27 @@ public: return *this; } + //! \~english + //! \brief Matrix rotation operation. + //! \details Works only with 2x2 matrix. + //! \return copy of rotated matrix. + //! \~russian + //! \brief Операция поворота матрицы. + //! \details Работает только с матрицами 2x2. + //! \return копия повернутой матрицы. + PIMathMatrixT& rotated(Type angle) { + static_assert(Rows == 2 && Cols == 2, "Works only with 2x2 matrix"); + PIMathMatrixT outm; + Type c = std::cos(angle); + Type s = std::sin(angle); + PIMathMatrixT<2u, 2u> tm; + tm[0][0] = tm[1][1] = c; + tm[0][1] = -s; + tm[1][0] = s; + outm = outm * tm; + return outm; + } + private: Type m[Rows][Cols]; }; @@ -565,13 +687,16 @@ inline std::ostream & operator <<(std::ostream & s, const PIMathMatrixT inline PICout operator<<(PICout s, const PIMathMatrixT &m) { s << "{"; @@ -586,13 +711,16 @@ inline PICout operator<<(PICout s, const PIMathMatrixT &m) { return s; } -/** -* \brief Multiplying matrices by each other. If you enter an index out of the border of the matrix there will be "undefined behavior" -* -* @param fm first matrix multiplier -* @param sm second matrix multiplier -* @return matrix that is the result of multiplication -*/ +//! \~english +//! \brief Multiplying matrices by each other. +//! \param fm first matrix multiplier. +//! \param sm second matrix multiplier. +//! \return matrix that is the result of multiplication. +//! \~russian +//! \brief Умножение матриц друг на друга. +//! \param fm первый множитель-матрица. +//! \param sm второй множитель-матрица. +//! \return матрица, являющаяся результатом умножения. template inline PIMathMatrixT operator*(const PIMathMatrixT &fm, const PIMathMatrixT &sm) { @@ -609,13 +737,16 @@ inline PIMathMatrixT operator*(const PIMathMatrixT inline PIMathVectorT operator*(const PIMathMatrixT &fm, const PIMathVectorT &sv) { @@ -630,13 +761,16 @@ inline PIMathVectorT operator*(const PIMathMatrixT return tv; } -/** -* \brief Multiplying vector and matrix. If you enter an index out of the border of the matrix there will be "undefined behavior" -* -* @param sv first vector multiplier -* @param fm second matrix multiplier -* @return vector that is the result of multiplication -*/ +//! \~english +//! \brief Multiplying a vector by a matrix. +//! \param sv first vector multiplier +//! \param fm second matrix multiplier +//! \return vector that is the result of multiplication +//! \~russian +//! \brief Умножения вектора на матрицу. +//! \param sv второй множитель-вектор. +//! \param fm первый множитель-матрица. +//! \return вектор, являющийся результатом умножения. template inline PIMathVectorT operator*(const PIMathVectorT &sv, const PIMathMatrixT &fm) { @@ -651,13 +785,16 @@ inline PIMathVectorT operator*(const PIMathVectorT &sv, return tv; } -/** -* \brief Multiplying value of type Type and matrix -* -* @param x first multiplier of type Type -* @param fm second matrix multiplier -* @return matrix that is the result of multiplication -*/ +//! \~english +//! \brief Multiplying a value of type `Type` by a matrix. +//! \param x first multiplier of type `Type`. +//! \param v second matrix multiplier. +//! \return matrix that is the result of multiplication. +//! \~russian +//! \brief Умножение значения тип `Type` на матрицу. +//! \param x первый множитель типа `Type`. +//! \param v вторая множитель-матрица. +//! \return матрица, являющаяся результатом умножения. template inline PIMathMatrixT operator*(const Type &x, const PIMathMatrixT &v) { return v * x; @@ -690,41 +827,53 @@ class PIMathMatrix; #define PIMM_FOR_C for (uint i = 0; i < _V2D::cols_; ++i) #define PIMM_FOR_R for (uint i = 0; i < _V2D::rows_; ++i) -//! \brief A class that works with matrix operations, the input data of which is the data type of the matrix -//! @tparam There are can be basic C++ language data and different classes where the arithmetic operators(=, +=, -=, *=, /=, ==, !=, +, -, *, /) -//! of the C++ language are implemented +//! \~english +//! \brief A class that works with matrix operations, the input data of which is the data type of the 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++. template class PIP_EXPORT PIMathMatrix : public PIVector2D { typedef PIVector2D _V2D; typedef PIMathMatrix _CMatrix; public: - /** - * \brief Constructor of class PIMathMatrix, which creates a matrix - * - * @param cols is number of matrix column uint type - * @param rows is number of matrix row uint type - * @param f is type of matrix elements - */ + //! \~english + //! \brief Constructor of class \a PIMathMatrix, which creates a matrix. + //! \param cols is number of matrix column \a uint type. + //! \param rows is number of matrix row \a uint type. + //! \param f is type of matrix elements. + //! \~russian + //! \brief Конструктор класса \a PIMathMatrix, который создает матрицу. + //! \param cols количество столбов матрицы типа \a uint. + //! \param rows количество строк матрицы типа \a uint. + //! \param f тип элементов матрицы. PIMathMatrix(const uint cols = 0, const uint rows = 0, const Type &f = Type()) { _V2D::resize(rows, cols, f); } - /** - * \brief Constructor of class PIMathMatrix, which creates a matrix - * - * @param cols is number of matrix column uint type - * @param rows is number of matrix row uint type - * @param val is PIVector of matrix elements - */ + //! \~english + //! \brief Constructor of class \a PIMathMatrix, which creates a matrix + //! \param cols is number of matrix column \a uint type + //! \param rows is number of matrix row \a uint type + //! \param val is \a PIVector of matrix elements + //! \~russian + //! \brief Конструктор класса \a PIMathMatrix, который создает матрицу. + //! \param cols количество столбов матрицы типа \a uint. + //! \param rows количество строк матрицы типа \a uint. + //! \param val тип \a PIVector элементов матрицы. PIMathMatrix(const uint cols, const uint rows, const PIVector &val) { _V2D::resize(rows, cols); int i = 0; PIMM_FOR _V2D::element(r, c) = val[i++]; } - /** - * \brief Constructor of class PIMathMatrix, which creates a matrix - * - * @param val is PIVector of PIVector, which creates matrix - */ + //! \~english + //! \brief Constructor of class \a PIMathMatrix, which creates a matrix. + //! \param val is PIVector of PIVector, which creates matrix. + //! \~russian + //! \brief Конструктор класса \a PIMathMatrix, который создает матрицу. + //! \param val тип \a PIVector, который создает матрицу. PIMathMatrix(const PIVector > &val) { if (!val.isEmpty()) { _V2D::resize(val.size(), val[0].size()); @@ -736,11 +885,12 @@ public: } } - /** - * \brief Constructor of class PIMathMatrix, which creates a matrix - * - * @param val is PIVector2D, which creates matrix - */ + //! \~english + //! \brief Constructor of class \a PIMathMatrix, which creates a matrix. + //! \param val is \a PIVector2D, which creates matrix. + //! \~russian + //! \brief Конструктор класса \a PIMathMatrix, который создает матрицу. + //! \param val тип \a PIVector2D, который создает матрицу. PIMathMatrix(const PIVector2D &val) { if (!val.isEmpty()) { _V2D::resize(val.rows(), val.cols()); @@ -748,246 +898,301 @@ public: } } - /** - * \brief Creates a matrix whose main diagonal is filled with ones and the remaining elements are zeros - * - * @param cols is number of matrix column uint type - * @param rows is number of matrix row uint type - * @return identity matrix(cols,rows) - */ - static _CMatrix identity(const uint cols, const uint rows) { - _CMatrix tm(cols, rows); + //! \~english + //! \brief Creates a matrix whose main diagonal is filled with ones and the remaining elements are zeros + //! \param cols is number of matrix column uint type + //! \param rows is number of matrix row uint type + //! \return identity matrix(cols, rows) + //! \~russian + //! \brief Создает матрицу, главная диагональ которой заполнена, а оставшиеся элементы - нулями. + //! \param cols количество столбов матрицы типа \a uint. + //! \param rows количество строк матрицы типа \a uint. + //! \return единичная матрица matrix(`cols`, `rows`) + static PIMathMatrix identity(const uint cols, const uint rows) { + PIMathMatrix tm(cols, rows); for (uint r = 0; r < rows; ++r) for (uint c = 0; c < cols; ++c) tm.element(r, c) = (c == r ? Type(1) : Type(0)); return tm; } - /** - * \brief Creates a row matrix of every element that is equal to every element of the vector - * - * @param val is the vector type PIMathVector - * @return row matrix of every element that is equal to every element of the vector - */ - static _CMatrix matrixRow(const PIMathVector &val) {return _CMatrix(val.size(), 1, val.toVector());} + //! \~english + //! \brief Creates a row matrix of every element that is equal to every element of the vector + //! \param val is the vector type \a PIMathVector + //! \return row matrix of every element that is equal to every element of the vector + //! \~russian + //! \brief Создает матрицу-строку, каждый элемент которой равен каждому элементу вектора + //! \param val вектор типа \a PIMathVector + //! \return матрица-строка, каждый элемент которой равен каждому элементу вектора + static PIMathMatrix matrixRow(const PIMathVector &val) {return PIMathMatrix(val.size(), 1, val.toVector());} - /** - * \brief Creates a column matrix of every element that is equal to every element of the vector - * - * @param val is the vector type PIMathVector - * @return column matrix of every element that is equal to every element of the vector - */ - static _CMatrix matrixCol(const PIMathVector &val) {return _CMatrix(1, val.size(), val.toVector());} + //! \~english + //! \brief Creates a column matrix of every element that is equal to every element of the vector + //! \param val is the vector type \a PIMathVector + //! \return column matrix of every element that is equal to every element of the vector + //! \~russian + //! \brief Создает матрицу-столбец, каждый элемент которой равен каждому элементу вектора + //! \param val вектор типа \a PIMathVector + //! \return матрица-столбец, каждый элемент которой равен каждому элементу вектора + static PIMathMatrix matrixCol(const PIMathVector &val) {return PIMathMatrix(1, val.size(), val.toVector());} - /** - * \brief Set the selected column in matrix. If there are more elements of the vector than elements in the column of the matrix - * or index larger than the number of columns otherwise there will be "undefined behavior" - * - * @param index is the number of the selected column - * @param v is a vector of the type _CMCol that needs to fill the column - * @return matrix type _CMatrix - */ - _CMatrix &setCol(uint index, const PIMathVector &v) { + //! \~english + //! \brief Set the selected column in matrix. + //! \details If there are more elements of the vector than elements in the column of the matrix + //! or index larger than the number of columns otherwise there will be "undefined behavior". + //! \param index is the number of the selected column. + //! \param v is a vector of the type \a PIMathVector that needs to fill the column. + //! \return matrix type \a PIMathMatrix + //! \~russian + //! \brief Определить выбранный столбец матрицы. + //! \details Если элементов в векторе больше, чем элементов в столбце матрицы + //! или индекс больше количества стобцов, то поведение не определено ("undefined behavior"). + //! \param index номер выбранного столбца. + //! \param v вектор типа \a PIMathVector, которым нужно заполнить столбец. + //! \return матрица типа \a PIMathMatrix. + PIMathMatrix &setCol(uint index, const PIMathVector &v) { assert(_V2D::rows() == v.size()); PIMM_FOR_R _V2D::element(i, index) = v[i]; return *this; } - /** - * \brief Set the selected row in matrix. If there are more elements of the vector than elements in the row of the matrix, - * or index larger than the number of rows otherwise there will be "undefined behavior" - * @param index is the number of the selected row - * @param v is a vector of the type _CMCol that needs to fill the row - * @return matrix type _CMatrix - */ - _CMatrix &setRow(uint index, const PIMathVector &v) { + //! \~english + //! \brief Set the selected row in matrix. + //! \details If there are more elements of the vector than elements in the row of the matrix, + //! or index larger than the number of rows otherwise there will be "undefined behavior". + //! \param index is the number of the selected row. + //! \param v is a vector of the type \a PIMathVector that needs to fill the row. + //! \return matrix type \a PIMathMatrix. + //! \~russian + //! \brief Определить выбранную строку матрицы. + //! \details Если элементов в векторе больше, чем элементов в строке матрицы + //! или индекс больше количества стобцов, то поведение не определено ("undefined behavior"). + //! \param index номер выбранной строки. + //! \param v вектор типа \a PIMathVector, которым нужно заполнить строку. + //! \return матрица типа \a PIMathMatrix. + PIMathMatrix &setRow(uint index, const PIMathVector &v) { assert(_V2D::cols() == v.size()); PIMM_FOR_C _V2D::element(index, i) = v[i]; return *this; } - /** - * \brief Method which replace selected columns in a matrix. You cannot use an index larger than the number of columns, - * otherwise there will be "undefined behavior" - * - * @param r0 is the number of the first selected row - * @param r1 is the number of the second selected row - * @return matrix type _CMatrix - */ - _CMatrix &swapCols(uint r0, uint r1) { + //! \~english + //! \brief Method which swaps selected columns in a matrix. + //! \details You cannot use an index larger than the number of columns, + //! otherwise there will be "undefined behavior". + //! \param r0 is the number of the first selected column. + //! \param r1 is the number of the second selected column. + //! \return matrix type \a PIMathMatrix. + //! \~russian + //! \brief Метод меняющий местами выбранные строки в матрице. + //! \details Вы не можете использовать индекс, который больше количества столбцов, + //! иначе будет неопределенное повередение ("undefined behavior"). + //! \param r0 номер первой выбранного стобца. + //! \param r1 номер второй выбранного столбца. + //! \return матрица типа \a PIMathMatrix. + PIMathMatrix &swapCols(uint r0, uint r1) { PIMM_FOR_C piSwap(_V2D::element(i, r0), _V2D::element(i, r1)); return *this; } - /** - * \brief Method which replace selected rows in a matrix. You cannot use an index larger than the number of rows, - * otherwise there will be "undefined behavior" - * - * @param c0 is the number of the first selected row - * @param c1 is the number of the second selected row - * @return matrix type _CMatrix - */ - _CMatrix &swapRows(uint c0, uint c1) { + //! \~english + //! \brief Method which replace selected rows in a matrix. + //! \details You cannot use an index larger than the number of rows, + //! otherwise there will be "undefined behavior" + //! \param c0 is the number of the first selected row. + //! \param c1 is the number of the second selected row. + //! \return matrix type \a PIMathMatrix. + //! \~russian + //! \brief Метод меняющий местами выбранные строки в матрице. + //! \details Вы не можете использовать индекс, который больше количества строк, + //! иначе будет неопределенное повередение ("undefined behavior"). + //! \param с0 номер первой выбранной строки. + //! \param с1 номер второй выбранной строки. + //! \return матрица типа \a PIMathMatrix. + PIMathMatrix &swapRows(uint c0, uint c1) { PIMM_FOR_R piSwap(_V2D::element(c0, i), _V2D::element(c1, i)); return *this; } - /** - * \brief Method which fills the matrix with selected value - * - * @param v is a parameter the type and value of which is selected and later filled into the matrix - * @return filled matrix type _CMatrix - */ - _CMatrix &fill(const Type &v) { + //! \~english + //! \brief Method which fills the matrix with selected value. + //! \param v is a parameter the type and value of which is selected and later filled into the matrix. + //! \return filled matrix type \a PIMathMatrix. + //! \~russian + //! \brief Метод заполняющий матрицу выбранным значением. + //! \param v параметр выбранного типа и значения, которым будет заполнена матрица. + //! \return заполненная матрица типа \a PIMathMatrix. + PIMathMatrix &fill(const Type &v) { PIMM_FOR_A _V2D::mat[i] = v; return *this; } - /** - * \brief Method which checks if matrix is square - * - * @return true if matrix is square, else false - */ + //! \~english + //! \brief Method which checks if matrix is square. + //! \return true if matrix is square, else false. + //! \~russian + //! \brief Метод, проверющий является ли матрица квадратной. + //! \return true если матрица квадратная, иначе false. bool isSquare() const { return _V2D::cols_ == _V2D::rows_; } - /** - * \brief Method which checks if main diagonal of matrix consists of ones and another elements are zeros - * - * @return true if matrix is identity, else false - */ + //! \~english + //! \brief Method which checks if main diagonal of matrix consists of ones and another elements are zeros. + //! \return true if matrix is identitied, else false. + //! \~russian + //! \brief Метод, проверяющий содержит ли главная диагональ единицы и все остальные поля нули. + //! \return true если матрица единичная, иначе false. bool isIdentity() const { PIMM_FOR if ((c == r) ? _V2D::element(r, c) != Type(1) : _V2D::element(r, c) != Type(0))return false; return true; } - /** - * \brief Method which checks if every elements of matrix are zeros - * - * @return true if matrix elements equal to zero, else false - */ + //! \~english + //! \brief Method which checks if every elements of matrix are zeros. + //! \return true if matrix is null, else false. + //! \~russian + //! \brief Метод, являются ли все элементы матрицы нулями. + //! \return true если матрица нулевая, иначе false. bool isNull() const { PIMM_FOR_A if (_V2D::mat[i] != Type(0)) return false; return true; } - /** - * \brief Method which checks if matrix is empty - * - * @return true if matrix is valid, else false - */ + //! \~english + //! \brief Method which checks if matrix is empty. + //! \return true if matrix is valid, else false. + //! \~russian + //! \brief Метод, который проверяет является ли матрица пустой. + //! \return true если матрица действительна, иначе false. bool isValid() const { return !PIVector2D::isEmpty(); } - /** - * \brief Addition assignment with matrix "sm" - * - * @param sm matrix for the addition assigment - */ - void operator+=(const _CMatrix &sm) { + //! \~english + //! \brief Addition assignment with matrix `sm`. + //! \param sm matrix for the addition assigment. + //! \~russian + //! \brief Сложение с присваиванием с матрицей `sm`. + //! \param sm матрица для сложения с присваиванием. + void operator+=(const PIMathMatrix &sm) { assert(_V2D::rows() == sm.rows()); assert(_V2D::cols() == sm.cols()); PIMM_FOR_A _V2D::mat[i] += sm.mat[i]; } - /** - * \brief Subtraction assignment with matrix "sm" - * - * @param sm matrix for the subtraction assigment - */ - void operator-=(const _CMatrix &sm) { + //! \~english + //! \brief Subtraction assignment with matrix `sm`. + //! \param sm matrix for the subtraction assigment. + //! \~russian + //! \brief Вычитание с присваиванием с матрицей `sm`. + //! \param sm матрица для вычитания с присваиванием. + void operator-=(const PIMathMatrix &sm) { assert(_V2D::rows() == sm.rows()); assert(_V2D::cols() == sm.cols()); PIMM_FOR_A _V2D::mat[i] -= sm.mat[i]; } - /** - * \brief Multiplication assignment with value "v" - * - * @param v value for the multiplication assigment - */ + //! \~english + //! \brief Multiplication assignment with value `v`. + //! \param v value for the multiplication assigment. + //! \~russian + //! \brief Умножение с присваиванием с матрицей `v`. + //! \param sm матрица для умножения с присваиванием. void operator*=(const Type &v) { PIMM_FOR_A _V2D::mat[i] *= v; } - /** - * \brief Division assignment with value "v" - * - * @param v value for the division assigment - */ + //! \~english + //! \brief Division assignment with value `v`. + //! \param v value for the division assigment. + //! \~russian + //! \brief Деление с присваиванием с матрицей `v`. + //! \param sm матрица для деления с присваиванием. void operator/=(const Type &v) { assert(piAbs(v) > PIMATHVECTOR_ZERO_CMP); PIMM_FOR_A _V2D::mat[i] /= v; } - /** - * \brief Matrix substraction - * - * @return the result of matrix substraction - */ - _CMatrix operator-() const { - _CMatrix tm(*this); + //! \~english + //! \brief Negation operation + //! \return copy of the negative matrix + //! \~russian + //! \brief Операция отрицания + //! \return копия отрицательной матрицы + PIMathMatrix operator-() const { + PIMathMatrix tm(*this); PIMM_FOR_A tm.mat[i] = -_V2D::mat[i]; return tm; } - /** - * \brief Matrix addition - * - * @param sm is matrix term - * @return the result of matrix addition - */ - _CMatrix operator+(const _CMatrix &sm) const { - _CMatrix tm(*this); + //! \~english + //! \brief Matrix addition. + //! \param sm is matrix term. + //! \return the result of matrix addition. + //! \~russian + //! \brief Матричное сложение. + //! \param sm матричное слагаемое. + //! \return результат матричного сложения. + PIMathMatrix operator+(const PIMathMatrix &sm) const { + PIMathMatrix tm(*this); assert(tm.rows() == sm.rows()); assert(tm.cols() == sm.cols()); PIMM_FOR_A tm.mat[i] += sm.mat[i]; return tm; } - /** - * \brief Matrix subtraction - * - * @param sm is matrix subtractor - * @return the result of matrix subtraction - */ - _CMatrix operator-(const _CMatrix &sm) const { - _CMatrix tm(*this); + //! \~english + //! \brief Matrix substraction. + //! \param sm is matrix subtrahend. + //! \return the result of matrix substraction. + //! \~russian + //! \brief Матричная разность. + //! \param sm матричное вычитаемое. + //! \return результат матричной разности. + PIMathMatrix operator-(const PIMathMatrix &sm) const { + PIMathMatrix tm(*this); assert(tm.rows() == sm.rows()); assert(tm.cols() == sm.cols()); PIMM_FOR_A tm.mat[i] -= sm.mat[i]; return tm; } - /** - * \brief Matrix multiplication - * - * @param v is value factor - * @return the result of matrix multiplication - */ - _CMatrix operator*(const Type &v) const { - _CMatrix tm(*this); + //! \~english + //! \brief Matrix multiplication. + //! \param v is value factor. + //! \return the result of matrix multiplication. + //! \~russian + //! \brief Матричное произведение. + //! \param v множитель. + //! \return результат произведения. + PIMathMatrix operator*(const Type &v) const { + PIMathMatrix tm(*this); PIMM_FOR_A tm.mat[i] *= v; return tm; } - /** - * \brief Matrix division - * - * @param v is value divider - * @return the result of matrix division - */ - _CMatrix operator/(const Type &v) const { + //! \~english + //! \brief Matrix division. + //! \param v is value divider. + //! \return the result of matrix division. + //! \~russian + //! \brief Матричное деление. + //! \param v делитель. + //! \return результат деления. + PIMathMatrix operator/(const Type &v) const { assert(piAbs(v) > PIMATHVECTOR_ZERO_CMP); - _CMatrix tm(*this); + PIMathMatrix tm(*this); PIMM_FOR_A tm.mat[i] /= v; return tm; } - /** - * \brief Determinant of the self matrix is ​​calculated. Works only with square matrix, nonzero matrices and invertible matrix - * - * @param ok is a parameter with which we can find out if the method worked correctly - * @return matrix determinant - */ + //! \~english + //! \brief ​Calculate Determinant of the matrix. + //! \details Works only with square matrix, nonzero matrices and invertible matrix. + //! \param ok is a parameter with which we can find out if the method worked correctly. + //! \return matrix determinant. + //! \~russian + //! \brief Вычислить определитель матрицы. + //! \details Работает только с квадратными, ненулевыми и обратимыми матрицами. + //! \param ok это параметр, с помощью которого мы можем узнать, правильно ли сработал метод. + //! \return опеределитель матрицы. Type determinant(bool *ok = 0) const { - _CMatrix m(*this); + PIMathMatrix m(*this); bool k; m.toUpperTriangular(&k); Type ret = Type(0); @@ -1001,11 +1206,14 @@ public: return ret; } - /** - * \brief Trace of the matrix is calculated. Works only with square matrix, nonzero matrices and invertible matrix - * - * @return matrix trace - */ + //! \~english + //! \brief Calculate the trace of a matrix. + //! \details Works only with square matrix matrix. + //! \return matrix trace. + //! \~russian + //! \brief Вычислить след матрицы. + //! \details Работает только с квадратными матрицами. + //! \return след матрицы. Type trace() const { assert(isSquare()); Type ret = Type(0); @@ -1015,15 +1223,19 @@ public: return ret; } - /** - * \brief Transforming matrix to upper triangular. Works only with square matrix, nonzero matrices and invertible matrix - * - * @param ok is a parameter with which we can find out if the method worked correctly - * @return copy of transformed upper triangular matrix - */ - _CMatrix &toUpperTriangular(bool *ok = 0) { + //! \~english + //! \brief Transforming matrix to upper triangular. + //! \details Works only with square matrix, nonzero matrices and invertible matrix. + //! \param ok is a parameter with which we can find out if the method worked correctly. + //! \return copy of transformed upper triangular matrix. + //! \~russian + //! \brief Преобразование матрицы в верхнетреугольную. + //! \details Работает только с квадратными, ненулевыми и обратимыми матрицами. + //! \param ok это параметр, с помощью которого мы можем узнать, правильно ли сработал метод. + //! \return копия преобразованной верхнетреугольной матрицы. + PIMathMatrix &toUpperTriangular(bool *ok = 0) { assert(isSquare()); - _CMatrix smat(*this); + PIMathMatrix smat(*this); bool ndet; uint crow; Type mul; @@ -1055,16 +1267,19 @@ public: return *this; } - /** - * \brief Matrix inversion operation. Works only with square matrix, nonzero matrices and invertible matrix - * - * @param ok is a parameter with which we can find out if the method worked correctly - * @param sv is a vector multiplier - * @return copy of inverted matrix - */ - _CMatrix &invert(bool *ok = 0, PIMathVector *sv = 0) { + //! \~english + //! \brief Matrix inversion operation. + //! \details Works only with square matrix, nonzero matrices and invertible matrix. + //! \param ok is a parameter with which we can find out if the method worked correctly. + //! \return inverted matrix. + //! \~russian + //! \brief Операция обращения матрицы. + //! \details Работает только с квадратными, ненулевыми и обратимыми матрицами. + //! \param ok это параметр, с помощью которого мы можем узнать, правильно ли сработал метод. + //! \return обратная матрица. + PIMathMatrix &invert(bool *ok = 0, PIMathVector *sv = 0) { assert(isSquare()); - _CMatrix mtmp = _CMatrix::identity(_V2D::cols_, _V2D::rows_), smat(*this); + PIMathMatrix mtmp = PIMathMatrix::identity(_V2D::cols_, _V2D::rows_), smat(*this); bool ndet; uint crow; Type mul, iddiv; @@ -1114,25 +1329,32 @@ public: return *this; } - /** - * \brief Matrix inversion operation. Works only with square matrix, nonzero matrices and invertible matrix - * - * @param ok is a parameter with which we can find out if the method worked correctly - * @return inverted matrix - */ - _CMatrix inverted(bool *ok = 0) const { - _CMatrix tm(*this); + //! \~english + //! \brief Matrix inversion operation. + //! \details Works only with square matrix, nonzero matrices and invertible matrix. + //! \param ok is a parameter with which we can find out if the method worked correctly. + //! \return copy of inverted matrix. + //! \~russian + //! \brief Операция обращения матрицы. + //! \details Работает только с квадратными, ненулевыми и обратимыми матрицами. + //! \param ok это параметр, с помощью которого мы можем узнать, правильно ли сработал метод. + //! \return копия обратной матрицы. + PIMathMatrix inverted(bool *ok = 0) const { + PIMathMatrix tm(*this); tm.invert(ok); return tm; } - /** - * \brief Matrix transposition operation - * - * @return transposed matrix - */ - _CMatrix transposed() const { - _CMatrix tm(_V2D::rows_, _V2D::cols_); + //! \~english + //! \brief Matrix transposition operation. + //! \details Works only with square matrix matrix. + //! \return copy of transposed matrix + //! \~russian + //! \brief Транспонирование матрицы. + //! \details Работает только с квадратными матрицами. + //! \return копия транспонированной матрицы. + PIMathMatrix transposed() const { + PIMathMatrix tm(_V2D::rows_, _V2D::cols_); PIMM_FOR tm.element(c, r) = _V2D::element(r, c); return tm; } @@ -1144,13 +1366,16 @@ template inline std::ostream & operator <<(std::ostream & s, const PIMathMatrix & m) {s << "{"; for (uint r = 0; r < m.rows(); ++r) { for (uint c = 0; c < m.cols(); ++c) { s << m.element(r, c); if (c < m.cols() - 1 || r < m.rows() - 1) s << ", ";} if (r < m.rows() - 1) s << std::endl << " ";} s << "}"; return s;} #endif -/** -* \brief Inline operator for outputting the matrix to the console -* -* @param s PICout type -* @param the matrix type PIMathMatrix that we print to the console -* @return PIMathMatrix printed to the console -*/ +//! \~english +//! \brief Inline operator for outputting the matrix to the console. +//! \param s \a PICout type. +//! \param the matrix type \a PIMathMatrix that we print to the console. +//! \return \a PIMathMatrix printed to the console. +//! \~russian +//! \brief Inline-оператор для вывода матрицы в консоль. +//! \param s типа \a PICout. +//! \param m типа \a PIMathMatrixT. +//! \return непечатанная в консоль \a PICout. template inline PICout operator<<(PICout s, const PIMathMatrix &m) { s << "Matrix{"; @@ -1165,26 +1390,28 @@ inline PICout operator<<(PICout s, const PIMathMatrix &m) { return s; } -/** -* \brief Inline operator for serializing a matrix into a PIByteArray -* -* @param s PIByteArray type -* @param v PIMathMatrix type -* @return PIBiteArray serialized PIMathMatrix -*/ +//! \~english +//! \brief Inline operator for serializing a matrix into a \a PIBinaryStream. +//! \param s \a PIBinaryStream type. +//! \param v \a PIMathMatrix type. +//! \~russian +//! \brief Inline-оператор для сериализации матрицы в \a PIBinaryStream. +//! \param s типа \a PIBinaryStream. +//! \param v типа \a PIMathMatrix. template inline PIBinaryStream

& operator <<(PIBinaryStream

& s, const PIMathMatrix & v) { s << (const PIVector2D &) v; return s; } -/** -* \brief Inline operator to deserialize matrix from PIByteArray -* -* @param s PIByteArray type -* @param v PIMathMatrix type -* @return PIMathMatrix deserialized from PIByteArray -*/ +//! \~english +//! \brief Inline operator to deserialize matrix from \a PIByteArray. +//! \param s \a PIBinaryStream type. +//! \param v \a PIMathMatrix type. +//! \~russian +//! \brief Inline-оператор для сериализации матрицы в \a PIByteArray. +//! \param s типа \a PIBinaryStream. +//! \param v типа \a PIMathMatrix. template inline PIBinaryStream

& operator >>(PIBinaryStream

& s, PIMathMatrix & v) { s >> (PIVector2D &) v; @@ -1192,13 +1419,18 @@ inline PIBinaryStream

& operator >>(PIBinaryStream

& s, PIMathMatrix & } -/** -* \brief Multiplying matrices by each other. If you enter an index out of the border of the matrix there will be "undefined behavior" -* -* @param fm first matrix multiplier -* @param sm second matrix multiplier -* @return matrix that is the result of multiplication -*/ +//! \~english +//! \brief Multiplying matrices by each other. +//! \details If you enter an index out of the border of the matrix there will be "undefined behavior". +//! \param fm first matrix multiplier. +//! \param sm second matrix multiplier. +//! \return matrix that is the result of multiplication. +//! \~russian +//! \brief Умножение матриц друг на друга. +//! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior"). +//! \param fm первый множитель-матрица. +//! \param sm вторая множитель-матрица. +//! \return матрица, являющаяся результатом умножения. template inline PIMathMatrix operator*(const PIMathMatrix &fm, const PIMathMatrix &sm) { @@ -1216,13 +1448,18 @@ inline PIMathMatrix operator*(const PIMathMatrix &fm, return tm; } -/** -* \brief Multiplying matrix and vector. If you enter an index out of the border of the matrix there will be "undefined behavior" -* -* @param fm first matrix multiplier -* @param sv second vector multiplier -* @return vector that is the result of multiplication -*/ +//! \~english +//! \brief Multiplying a matrix by a vector. +//! \details If you enter an index out of the border of the matrix there will be "undefined behavior". +//! \param fm first matrix multiplier +//! \param sv second vector multiplier +//! \return vector that is the result of multiplication +//! \~russian +//! \brief Умножения матрицы на вектор. +//! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior"). +//! \param fm первый множитель-матрица. +//! \param sv второй множитель-вектор. +//! \return вектор, являющийся результатом умножения. template inline PIMathVector operator*(const PIMathMatrix &fm, const PIMathVector &sv) { @@ -1238,13 +1475,18 @@ inline PIMathVector operator*(const PIMathMatrix &fm, return tv; } -/** -* \brief Multiplying vector and matrix. If you enter an index out of the border of the matrix there will be "undefined behavior" -* -* @param sv first vector multiplier -* @param fm second matrix multiplier -* @return vector that is the result of multiplication -*/ +//! \~english +//! \brief Multiplying a vector by a matrix. +//! \details If you enter an index out of the border of the matrix there will be "undefined behavior". +//! \param sv first vector multiplier +//! \param fm second matrix multiplier +//! \return vector that is the result of multiplication +//! \~russian +//! \brief Умножения вектора на матрицу. +//! \details Если вы введете индекс вне границ матрицы, то поведение не определено ("undefined behavior"). +//! \param sv второй множитель-вектор. +//! \param fm первый множитель-матрица. +//! \return вектор, являющийся результатом умножения. template inline PIMathVector operator*(const PIMathVector &sv, const PIMathMatrix &fm) { @@ -1260,13 +1502,16 @@ inline PIMathVector operator*(const PIMathVector &sv, return tv; } -/** -* \brief Multiplying value of type Type and matrix -* -* @param x first multiplier of type Type -* @param v second matrix multiplier -* @return matrix that is the result of multiplication -*/ +//! \~english +//! \brief Multiplying a value of type `Type` by a matrix. +//! \param x first multiplier of type `Type`. +//! \param v second matrix multiplier. +//! \return matrix that is the result of multiplication. +//! \~russian +//! \brief Умножение значения тип `Type` на матрицу. +//! \param x первый множитель типа `Type`. +//! \param v второй множитель-матрица. +//! \return матрица, являющаяся результатом умножения. template inline PIMathMatrix operator*(const Type &x, const PIMathMatrix &v) { return v * x; @@ -1275,12 +1520,14 @@ inline PIMathMatrix operator*(const Type &x, const PIMathMatrix &v) typedef PIMathMatrix PIMathMatrixi; typedef PIMathMatrix PIMathMatrixd; -/** -* \brief Searching hermitian matrix -* -* @param m conjugate transpose matrix -* @return result of the hermitian -*/ +//! \~english +//! \brief Searching hermitian matrix. +//! \param m conjugate transpose matrix. +//! \return result of the hermitian. +//! \~russian +//! \brief Поиск эрмитовой матрицы. +//! \param m сопряженная транспонированная матрица. +//! \return результат преобразования. template PIMathMatrix > hermitian(const PIMathMatrix > &m) { PIMathMatrix > ret(m); diff --git a/libs/main/math/pipoint.h b/libs/main/math/pipoint.h index 5ab18145..b9090050 100644 --- a/libs/main/math/pipoint.h +++ b/libs/main/math/pipoint.h @@ -27,6 +27,11 @@ //! \brief //! \~english Two-dimensional point class //! \~russian Класс двумерной точки +//! \details +//! Данный класс позволяет хранить и работать с двумерными точками. +//! Для работы с объектами реализованы операторы сложения, вычитания и проверки на ревенство и неравенство. +//! Также доступны методы для перемещения точек \a translate(), \a translated(), \a move(), \a moved() +//! и перевода из декартовой системы координат в полярную \a toPolar() и обратно \a fromPolar(). template class PIP_EXPORT PIPoint { static_assert(std::is_arithmetic::value, "Type must be arithmetic"); @@ -34,112 +39,118 @@ public: Type x; Type y; - //! + //! \~russian Создает новую точку. PIPoint() {x = y = Type();} - //! + //! \~russian Создает новую точку с заданными координатами. PIPoint(Type x_, Type y_) {set(x_, y_);} - //! + //! \~russian Задать новые координаты точке. PIPoint & set(Type x_, Type y_) { x = x_; y = y_; return *this; } - //! + //! \~russian Задать новые координаты точке. PIPoint & set(const PIPoint & p) { x = p.x; y = p.y; return *this; } - //! + //! \~russian Переместить точку. PIPoint & translate(Type x_, Type y_) { x += x_; y += y_; return *this; } - //! + //! \~russian Переместить точку. PIPoint & translate(const PIPoint & p) { x += p.x; y += p.y; return *this; } - //! + //! \~russian Создать копию точки и переместить её. PIPoint translated(Type x_, Type y_) const { PIPoint rp(*this); rp.translate(x_, y_); return rp; } - //! + //! \~russian Создать копию точки и переместить её. PIPoint translated(const PIPoint & p) const { PIPoint rp(*this); rp.translate(p); return rp; } - //! + //! \~russian Переместить точку. + //! \details Является копией метода \a translate(). PIPoint & move(Type x_, Type y_) {return translate(x_, y_);} - //! + //! \~russian Переместить точку. + //! \details Является копией метода \a translate(). PIPoint & move(const PIPoint & p) {return translate(p);} - //! + //! \~russian Создать копию точки и переместить её. + //! \details Является копией метода \a translated(). PIPoint moved(Type x_, Type y_) const { PIPoint rp(*this); rp.translate(x_, y_); return rp; } - //! + //! \~russian Создать копию точки и переместить её. + //! \details Является копией метода \a translated(). PIPoint moved(const PIPoint & p) const { PIPoint rp(*this); rp.translate(p); return rp; } - //! + //! \~russian Посчитать угол(радианы) в поолярной системе координат. double angleRad() const {return atan2(y, x);} - //! + //! \~russian Посчитать угол(градусы) в поолярной системе координат. double angleDeg() const {return toDeg(atan2(y, x));} - //! + //! \~russian Перевести копию точки в полярную систему координат. PIPoint toPolar(bool isDeg = false) const {return PIPoint(sqrt(x*x + y*y), isDeg ? angleDeg() : angleRad());} - //! + //! \~russian Перевести копию точки из полярной системы координат в декартовую. static PIPoint fromPolar(const PIPoint & p) {return PIPoint(p.y * cos(p.x), p.y * sin(p.x));} - //! + //! \~russian + //! Прибавить координаты второй точки и сохранить. + //! \details Является копией метода \a translate(). void operator +=(const PIPoint & p) {translate(p);} - //! + //! \~russian Сложить координаты двух точек. PIPoint operator +(const PIPoint & p) {return PIPoint(x + p.x, y + p.y);} - //! + //! \~russian Прибавить к координатам одинаковое значение. PIPoint operator +(const Type & p) {return PIPoint(x + p, y + p);} - //! + //! \~russian Вычесть из координат координаты второй точки - найти смещение. PIPoint operator -(const PIPoint & p) {return PIPoint(x - p.x, y - p.y);} - //! + //! \~russian Вычесть из координат одинаковое значение. PIPoint operator -(const Type & p) {return PIPoint(x - p, y - p);} - //! + //! \~russian Инвертировать координаты точки. PIPoint operator -() {return PIPoint(-x, -y);} - //! + //! \~russian Проверить равенство координат двух точек. bool operator ==(const PIPoint & p) const {return (x == p.x && y == p.y);} - //! + //! \~russian Проверить неравенство координат двух точек. bool operator !=(const PIPoint & p) const {return (x != p.x || y != p.y);} }; - +//! \~russian Перегруженный оператор для вывода координат в \a PICout. template PICout operator <<(PICout & s, const PIPoint & v) { s.setControl(0, true);