VM2D 1.14
Vortex methods for 2D flows simulation
Loading...
Searching...
No Matches
defs.h
Go to the documentation of this file.
1/*--------------------------------*- VM2D -*-----------------*---------------*\
2| ## ## ## ## #### ##### | | Version 1.14 |
3| ## ## ### ### ## ## ## ## | VM2D: Vortex Method | 2026/03/06 |
4| ## ## ## # ## ## ## ## | for 2D Flow Simulation *----------------*
5| #### ## ## ## ## ## | Open Source Code |
6| ## ## ## ###### ##### | https://www.github.com/vortexmethods/VM2D |
7| |
8| Copyright (C) 2017-2026 I. Marchevsky, K. Sokol, E. Ryatina, A. Kolganova |
9*-----------------------------------------------------------------------------*
10| File name: defs.h |
11| Info: Source code of VM2D |
12| |
13| This file is part of VM2D. |
14| VM2D is free software: you can redistribute it and/or modify it |
15| under the terms of the GNU General Public License as published by |
16| the Free Software Foundation, either version 3 of the License, or |
17| (at your option) any later version. |
18| |
19| VM2D is distributed in the hope that it will be useful, but WITHOUT |
20| ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or |
21| FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License |
22| for more details. |
23| |
24| You should have received a copy of the GNU General Public License |
25| along with VM2D. If not, see <http://www.gnu.org/licenses/>. |
26\*---------------------------------------------------------------------------*/
27
28
41#ifndef DEFS_H
42#define DEFS_H
43
44#if defined(_WIN32)
45 #include <direct.h>
46#endif
47
48#include <fstream>
49#include <sys/stat.h>
50#include <sys/types.h>
51
52#include <ctime>
53#include <iostream>
54#include <list>
55
56#include "Eigen/Dense"
57
58#include "Gpudefs.h"
59#include "LogStream.h"
60
61#include "Vortex2D.h"
62#include "v3D.h"
63#include "PairInt.h"
64
65
67#define DYN_SCHEDULE 20
68
71
73typedef std::pair<double, double> timePeriod;
74
76const double PI = 3.1415926535897932384626433832795;
77
79const double IDPI = 0.1591549430918953357688837633725;
80
82const double DPI = 6.2831853071795864769252867665590;
83
85const double IQPI = 0.07957747154594766788444188168626;
86
88const double QPI = 12.566370614359172953850573533118;
89
93namespace defaults
94{
96 const double defaultTimeStart = 0.0;
97
99 const std::pair<std::pair<std::string, int>, std::string> defaultVelAccel = { {"RampLin", 1}, "" };
100 const double defaultTimeAccel = 0.0;
101
103 const std::pair<std::pair<std::string, int>, std::string> defaultSaveVP = { {"text", 0}, "" };
104 const int defaultSaveVPstep = 0;
105
107 const std::pair<std::pair<std::string, int>, std::string> defaultSaveVtx = { {"text", 0}, "" };
108 const int defaultSaveVtxStep = 100;
109
111 const int defaultSaveVisStress = 0;
112
114 const int defaultHistoryFrequency = 100;
115
118 const std::vector<std::string> defaultReviseParameters = { "nameLength", "timeStop", "dt", "vInf", "vRef", "coefEpsAst", "saveVtx", "saveVP" };
119
121 const int defaultNameLength = 5;
122
124 const double defaultSigma0 = 0.0; //значит, рассчитать его по длине панелей как половину средней длины панелей
125
127 const double defaultCoefEpsAst = 1.25;
128
130 const double defaultEpsCol = 0.0; //значит, рассчитать его как 2/3 eps
131
133 const double defaultDistFar = 20.0;
134
136 const double defaultDelta = 1.e-6;
137
140
142 const double defaultMaxGamma = 0.0;
143
145 const double defaultVRef = 0.0;
146
148 const size_t defaultRequiredNPanels = 0;
149
151 const std::pair<std::string, int> defaultBoundaryCondition = { "boundaryConstantLayerAver", 1 };
152
154 const std::pair<std::string, int> defaultLinearSystemSolver = { "linearSystemGauss", 0 };
155
157 const std::pair<std::string, int> defaultVelocityComputation{ "velocityBarnesHut", 1 };
158
160 //const bool defaultGeographicalAngles = false; //Для обдува ветром, когда углы считаются по компасу
161
163 const bool defaultRotateForces = false;
164
166 const bool defaultCalcCoefficients = false;
167
169 const double rotateAngleVpPoints = 0;
170
172 const std::string defaultAirfoilsDir = "../settings/airfoils/";
173 const std::string defaultBodiesDir = "../settings/bodies/";
174
176 const std::string defaultWakesDir = "../settings/wakes/";
177
179 const std::vector<std::string> defaultFileAirfoil({});
180 const std::vector<std::string> defaultFileBody({});
181
183 const std::string defaultFileWake("");
184
186 const std::string defaultFileSource("");
187
189 const std::vector<std::string> defaultAirfoil({});
190 const std::vector<std::string> defaultBody({});
191
193 const VMlib::Point2D defaultBasePoint = { 0.0, 0.0 };
194 const VMlib::v3D defaultBasePoint3D = { 0.0, 0.0, 0.0 };
195
197 const Point2D defaultScale = { 1.0, 1.0 };
198
200 const double defaultAngle = 0.0;
201
203 const double defaultChord = 0.0;
204
206 const Point2D defaultAddedMass = { 0.0, 0.0 };
207
209 const bool defaultInverse = false;
210
213 const std::string defaultMechanicalSystem = "";
214
216 const std::string defaultPspFile = "passport";
217
219 const int defaultNp = 1;
220
222 const std::string defaultCopyPath = "";
223
225 static std::ostream* defaultQueueLogStream = &std::cout;
226
228 static std::ostream* defaultWorld2DLogStream = &std::cout;
229
231 static bool defaultAddMass = false;
232 static v3D defaultAddMassVcm = { 0.0, 0.0, 0.0 };
233 static v3D defaultAddMassWcm = { 0.0, 0.0, 0.0 };
234
236 static Point2D defaultInitDisplacement = { 0.0, 0.0 };
238 static Point2D defaultInitVelocity = {0.0, 0.0};
239 static double defaultInitAngularVelocity = 0.0;
240
241} //namespace defaults
242
243
244namespace VMlib
245{
246
250 std::string CurrentDataTime();
251
252
258 void PrintLogoToStream(std::ostream& str);
259
265 void PrintUniversalLogoToStream(std::ostream& str);
266
267
275 void PrintLogoToTextFile(std::ofstream& str, const std::string& fileName, const std::string& descr);
276
277
284 void PrintHeaderToTextFile(std::ofstream& str, const std::string& header);
285
286
295 template <typename T>
296 std::ostream& operator<< (std::ostream& _stream, const std::vector<T>& _vec)
297 {
298 size_t n = _vec.size();
299 _stream << "{ ";
300 if (n > 0)
301 {
302 for (size_t j = 0; j < n - 1; ++j)
303 _stream << _vec[j] << ", ";
304 _stream << _vec[n - 1];
305 }
306 _stream << " }";
307 return _stream;
308 }//operator<<(...)
309
310
318 inline std::ostream& operator<< (std::ostream& _stream, const std::pair<std::pair<std::string, int>, std::string>& _pair)
319 {
320 _stream << "( ( " << _pair.first.first << ", " << _pair.first.second << " ), " << _pair.second << " )";
321 return _stream;
322 }//operator<<(...)
323
324
332 inline std::ostream& operator<< (std::ostream& _stream, const std::pair<std::string, int>& _pair)
333 {
334 _stream << "( " << _pair.first << ", " << _pair.second << " )";
335 return _stream;
336 }//operator<<(...)
337
338
339
346 inline bool fileExistTest(const std::string& fileName_, LogStream& info, bool exitKey = false, const std::list <std::string>& extList = {})
347 {
348 std::string fileName = fileName_;
349
350 std::list<std::string> fullExtList(extList);
351 fullExtList.insert(fullExtList.begin(), "");
352
353 for (const auto& ext : fullExtList)
354 {
355 std::string newFileName = ((ext == "") ? fileName : (fileName + "." + ext));
356 std::ifstream f(newFileName.c_str());
357 if (f.good())
358 {
359 f.close();
360 f.clear();
361
362 info('i') << "file " << newFileName << " is found" << std::endl;
363 fileName = newFileName;
364 return true;
365 }
366 }
367
368 if (exitKey)
369 {
370 info('e') << "file " << fileName << " is not found" << std::endl;
371 exit(-1);
372 }
373 else
374 info('i') << "file " << fileName << " is not found" << std::endl;
375
376 return false;
377 }
378
379
387 inline std::string fileNameStep(const std::string& name, int length, size_t number, const std::string& ext)
388 {
389 std::string fname(name);
390
391 size_t dec = 1;
392
393 for (int i = 1; i < length; ++i)
394 {
395 dec *= 10;
396 if (number < dec)
397 fname += "0";
398 }
399
400 std::ostringstream ss;
401 ss << number;
402 fname += ss.str();
403
404 if (ext.size() > 0)
405 {
406 fname += ".";
407 fname += ext;
408 }
409
410 return fname;
411 }
412
413
418 inline void copyFile(const std::string& fileNameFrom, const std::string& fileNameTo)
419 {
420 std::string buf;
421 buf.resize(BUFSIZ);
422
423 FILE *in, *out;
424 size_t n;
425
426
427#pragma warning (push)
428#pragma warning (disable: 4996)
429 in = fopen(fileNameFrom.c_str(), "rb");
430 out = fopen(fileNameTo.c_str(), "wb");
431#pragma warning (pop)
432
433 while ((n = fread((void*)buf.data(), 1, BUFSIZ, in)) != 0)
434 {
435 fwrite((void*)buf.data(), 1, n, out);
436 }
437
438 std::fclose(in);
439 std::fclose(out);
440 }//copyFile
441
442
447 inline void CreateUserDirectory(const std::string& dir, const std::string& name)
448 {
449#if defined(_WIN32)
450 _mkdir((dir + name).c_str());
451#else
452 mkdir((dir + name).c_str(), S_IRWXU | S_IRGRP | S_IROTH);
453#endif
454 }
455
456
462 template<typename T>
463 inline T sqr(T x) { return x * x; }
464
470 template<typename T>
471 inline T cubPower(T x) { return x * x * x; }
472
473
479 template <typename T>
480 inline double macos(const T x)
481 {
482 double res = abs(x) > 1.0 ? 0.5*PI*(1 - sign(x)) : acos(x);
483 return res;
484 }
485
486
492 template <typename T>
493 int sign(T x)
494 {
495 double dx = (double)x;
496 if (dx > 0) return 1;
497 if ( (dx < 0.0) || (dx < -0.0) ) return -1;
498 return 0;
499 }
500
501
502
507 void SaveToStream(const Eigen::MatrixXd& matr, std::ostream& str);
508
513 void SaveToStream(const Eigen::MatrixXcd& matr, std::ostream& str);
514
519 void SaveToStream(const Eigen::VectorXd& vec, std::ostream& str);
520
525 void SaveToStream(const std::vector<Point2D>& vec, std::ostream& str);
526
531 double M4(double t);
532
537 void ModifyE2(double* ee2, double dst2);
538
539
545 double Alpha(const Point2D& p, const Point2D& s);
546
552 double Lambda(const Point2D& p, const Point2D& s);
553
562 Point2D Omega(const Point2D& a, const Point2D& b, const Point2D& c);
563
568 template<typename T>
569 void SwapEnd(T& var)
570 {
571 char* varArray = reinterpret_cast<char*>(&var);
572 for (long i = 0; i < static_cast<long>(sizeof(var) / 2); ++i)
573 std::swap(varArray[sizeof(var) - 1 - i], varArray[i]);
574 }
575
577 inline double boundDenom(double r2, double eps2)
578 {
579#ifndef LAMBVORTEX
580 return std::max(r2, eps2);
581#else
582 if (r2 > eps2)
583 return std::max(r2, eps2);
584 else
585 return (r2 < 1e-10) ? 1e-10 : r2 / (1.0 - exp(-6.0*r2 / eps2));
586#endif
587 }
588
589}//namespace VMlib
590
591using VMlib::sqr;
592using VMlib::cubPower;
593
594#endif
Описание констант и параметров для взаимодействия с графическим ускорителем
Заголовочный файл с описанием класса LogStream.
Заголовочный файл с описанием класса pairInt.
const double QPI
Число .
Definition defs.h:88
PointType
Класс перечисления для определения типа набора точек (пелена/виртуальные вихри/точки для вычисления с...
Definition defs.h:70
std::pair< double, double > timePeriod
Тип для хранения начала и конца промежутка времени
Definition defs.h:73
const double PI
Число .
Definition defs.h:76
const double IQPI
Число .
Definition defs.h:85
const double IDPI
Число .
Definition defs.h:79
const double DPI
Число .
Definition defs.h:82
Заголовочный файл с описанием класса Vortex2D.
Класс, определяющий работу с потоком логов
Definition LogStream.h:57
Класс, опеделяющий двумерный вектор
Definition v3D.h:60
bool fileExistTest(const std::string &fileName_, LogStream &info, bool exitKey=false, const std::list< std::string > &extList={})
Проверка существования файла
Definition defs.h:346
void PrintHeaderToTextFile(std::ofstream &str, const std::string &header)
Формирование подзаголовка в текстовом файле вывода программы VM2D/VM3D.
Definition defs.cpp:175
double M4(double t)
Ядро сглаживания (Монагана)
Definition defs.cpp:227
void PrintLogoToStream(std::ostream &str)
Передача в поток вывода шапки программы VM2D/VM3D.
Definition defs.cpp:108
void CreateUserDirectory(const std::string &dir, const std::string &name)
Создание каталога
Definition defs.h:447
void PrintUniversalLogoToStream(std::ostream &str)
Передача в поток вывода универсальной шапки программы VM2D/VM3D.
Definition defs.cpp:92
double macos(const T x)
Усовершенствованный аркосинус
Definition defs.h:480
void ModifyE2(double *ee2, double dst2)
Модифицирует массив квадратов расстояний до ближайших вихрей из wake.
Definition defs.cpp:236
void SaveToStream(const Eigen::MatrixXd &matr, std::ostream &str)
Сохранение матрицы в поток
Definition defs.cpp:185
double Lambda(const Point2D &p, const Point2D &s)
Вспомогательная функция вычисления логарифма отношения норм векторов
Definition defs.cpp:268
void PrintLogoToTextFile(std::ofstream &str, const std::string &fileName, const std::string &descr)
Формирование заголовка файла программы VM2D/VM3D.
Definition defs.cpp:139
std::string fileNameStep(const std::string &name, int length, size_t number, const std::string &ext)
Формирование имени файла
Definition defs.h:387
T cubPower(T x)
Возведение числа в куб
Definition defs.h:471
T sqr(T x)
Возведение числа в квадрат
Definition defs.h:463
double boundDenom(double r2, double eps2)
Способ сглаживания скорости вихря (вихрь Рэнкина или вихрь Ламба)
Definition defs.h:577
void copyFile(const std::string &fileNameFrom, const std::string &fileNameTo)
Копирование файла
Definition defs.h:418
double Alpha(const Point2D &p, const Point2D &s)
Вспомогательная функция вычисления угла между векторами
Definition defs.cpp:262
std::string CurrentDataTime()
Формирование строки с текущем временем и датой
Definition defs.cpp:47
int sign(T x)
Усовершенствованный сигнум
Definition defs.h:493
void SwapEnd(T &var)
Вспомогательная функция перестановки байт местами (нужно для сохранения бинарных VTK)
Definition defs.h:569
std::ostream & operator<<(std::ostream &_stream, const std::vector< T > &_vec)
Переопределение оператора "<<" для вывода в поток вектора std::vector.
Definition defs.h:296
Point2D Omega(const Point2D &a, const Point2D &b, const Point2D &c)
Вспомогательная функция вычисления величины .
Definition defs.cpp:274
Глобальные параметры по умолчанию
Definition defs.h:94
const int defaultRevisePassportStep
Шаг обновления паспорта и перечень перечитываемых параметров
Definition defs.h:117
const VMlib::Point2D defaultBasePoint
Базовое смещение профиля
Definition defs.h:193
const double defaultDistFar
Радиус убивания дальнего следа
Definition defs.h:133
const int defaultMechanicalSystemType
Тип механической системы
Definition defs.h:212
const bool defaultCalcCoefficients
Признак расчета безразмерных коэффициентов вместо сил
Definition defs.h:166
static std::ostream * defaultQueueLogStream
Поток вывода логов и ошибок очереди
Definition defs.h:225
static v3D defaultAddMassVcm
Definition defs.h:232
const std::string defaultWakesDir
Каталог с файлами вихревых следов
Definition defs.h:176
const std::vector< std::string > defaultFileBody({})
const std::vector< std::string > defaultBody({})
const int defaultSaveVisStress
Шаг подсчета поля скорости и давления
Definition defs.h:111
const size_t defaultRequiredNPanels
Желаемое число панелей для разбиения геометрии
Definition defs.h:148
const double defaultVRef
Референсная скорость, равная нулю, что означает ее равенство скорости набегающего потока
Definition defs.h:145
const Point2D defaultScale
Коэффициент масштабирования профиля
Definition defs.h:197
const double defaultDelta
Расстояние, на которое рождаемый вихрь отодвигается от профиля
Definition defs.h:136
const bool defaultRotateForces
Признак работы в "географической" системе координат
Definition defs.h:163
const Point2D defaultAddedMass
Присоединенная масса
Definition defs.h:206
static Point2D defaultInitVelocity
Definition defs.h:238
const bool defaultInverse
Признак разворота нормалей (для расчета внутреннего течения)
Definition defs.h:209
const int defaultSaveVPstep
Definition defs.h:104
static double defaultInitAngularVelocity
Definition defs.h:239
const double defaultEpsCol
Радиус вихря по умолчанию
Definition defs.h:130
const double defaultTimeAccel
Definition defs.h:100
static v3D defaultAddMassWcm
Definition defs.h:233
const double defaultChord
Хорда
Definition defs.h:203
const int defaultHistoryFrequency
Шаг сохранения буферов истории скорости и давления к контрольных точках в файл
Definition defs.h:114
const std::pair< std::string, int > defaultVelocityComputation
Способ вычисления скоростей вихрей
Definition defs.h:157
static double defaultInitAngularDisplacement
Definition defs.h:237
const int defaultNp
Необходимое число процессоров для решения задачи
Definition defs.h:219
const std::string defaultFileSource("")
Файл с источниками
const std::vector< std::string > defaultAirfoil({})
Список профилей
const double defaultAngle
Угол атаки
Definition defs.h:200
const std::string defaultCopyPath
Путь к каталогу с задачей для копирования в новые каталоги
Definition defs.h:222
const double defaultMaxGamma
Число вихрей, рождаемых на одной панели
Definition defs.h:142
const int defaultVortexPerPanel
Число вихрей, рождаемых на одной панели
Definition defs.h:139
const int defaultNameLength
Число разрядов в имени файла
Definition defs.h:121
const double rotateAngleVpPoints
Угол поворота точек VP.
Definition defs.h:169
const std::string defaultAirfoilsDir
Каталог с файлами профилей
Definition defs.h:172
const std::pair< std::pair< std::string, int >, std::string > defaultSaveVtx
Шаг подсчета поля скорости и давления
Definition defs.h:107
const std::pair< std::pair< std::string, int >, std::string > defaultVelAccel
Время разгона
Definition defs.h:99
const double defaultTimeStart
Начало расчета
Definition defs.h:96
const std::string defaultMechanicalSystem
Definition defs.h:213
static std::ostream * defaultWorld2DLogStream
Поток вывода логов и ошибок задачи
Definition defs.h:228
const VMlib::v3D defaultBasePoint3D
Definition defs.h:194
const std::vector< std::string > defaultReviseParameters
Definition defs.h:118
const int defaultSaveVtxStep
Definition defs.h:108
const std::vector< std::string > defaultFileAirfoil({})
Список профилей
const std::string defaultBodiesDir
Definition defs.h:173
const double defaultCoefEpsAst
Коэффициент при вычислении eps_ast по умолчанию
Definition defs.h:127
const std::pair< std::string, int > defaultBoundaryCondition
Способ удовлетворения граничного условия
Definition defs.h:151
const std::string defaultPspFile
Имя файла с паспортом задачи
Definition defs.h:216
const std::pair< std::string, int > defaultLinearSystemSolver
Способ решения линейной системы
Definition defs.h:154
const double defaultSigma0
Радиус вихря по умолчанию
Definition defs.h:124
static bool defaultAddMass
Расчет присоединенной массы
Definition defs.h:231
const std::pair< std::pair< std::string, int >, std::string > defaultSaveVP
Шаг подсчета поля скорости и давления
Definition defs.h:103
const std::string defaultFileWake("")
Файл со следом
static Point2D defaultInitDisplacement
Для профиля на упругих связях - начальные отклонения и скорости
Definition defs.h:236
Заголовочный файл с описанием класса v3D.