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
115 const std::vector<std::string> defaultReviseParameters = { "nameLength", "timeStop", "dt", "vInf", "vRef", "saveVtx", "saveVP" };
116
118 const int defaultNameLength = 5;
119
121 const double defaultSigma0 = 0.0; //значит, рассчитать его по длине панелей как половину средней длины панелей
122
124 const double defaultEpsCol = 0.0; //значит, рассчитать его как 2/3 eps
125
127 const double defaultDistFar = 20.0;
128
130 const double defaultDelta = 1.e-6;
131
134
136 const double defaultMaxGamma = 0.0;
137
139 const double defaultVRef = 0.0;
140
142 const size_t defaultRequiredNPanels = 0;
143
145 const std::pair<std::string, int> defaultBoundaryCondition = { "boundaryConstantLayerAver", 1 };
146
148 const std::pair<std::string, int> defaultLinearSystemSolver = { "linearSystemGauss", 0 };
149
151 const std::pair<std::string, int> defaultVelocityComputation{ "velocityBarnesHut", 1 };
152
154 //const bool defaultGeographicalAngles = false; //Для обдува ветром, когда углы считаются по компасу
155
157 const bool defaultRotateForces = false;
158
160 const bool defaultCalcCoefficients = false;
161
163 const double rotateAngleVpPoints = 0;
164
166 const std::string defaultAirfoilsDir = "../settings/airfoils/";
167 const std::string defaultBodiesDir = "../settings/bodies/";
168
170 const std::string defaultWakesDir = "../settings/wakes/";
171
173 const std::vector<std::string> defaultFileAirfoil({});
174 const std::vector<std::string> defaultFileBody({});
175
177 const std::string defaultFileWake("");
178
180 const std::string defaultFileSource("");
181
183 const std::vector<std::string> defaultAirfoil({});
184 const std::vector<std::string> defaultBody({});
185
187 const VMlib::Point2D defaultBasePoint = { 0.0, 0.0 };
188 const VMlib::v3D defaultBasePoint3D = { 0.0, 0.0, 0.0 };
189
191 const Point2D defaultScale = { 1.0, 1.0 };
192
194 const double defaultAngle = 0.0;
195
197 const double defaultChord = 0.0;
198
200 const Point2D defaultAddedMass = { 0.0, 0.0 };
201
203 const bool defaultInverse = false;
204
207 const std::string defaultMechanicalSystem = "";
208
210 const std::string defaultPspFile = "passport";
211
213 const int defaultNp = 1;
214
216 const std::string defaultCopyPath = "";
217
219 static std::ostream* defaultQueueLogStream = &std::cout;
220
222 static std::ostream* defaultWorld2DLogStream = &std::cout;
223
225 static bool defaultAddMass = false;
226 static v3D defaultAddMassVcm = { 0.0, 0.0, 0.0 };
227 static v3D defaultAddMassWcm = { 0.0, 0.0, 0.0 };
228
230 static Point2D defaultInitDisplacement = { 0.0, 0.0 };
232 static Point2D defaultInitVelocity = {0.0, 0.0};
233 static double defaultInitAngularVelocity = 0.0;
234
235} //namespace defaults
236
237
238namespace VMlib
239{
240
244 std::string CurrentDataTime();
245
246
252 void PrintLogoToStream(std::ostream& str);
253
259 void PrintUniversalLogoToStream(std::ostream& str);
260
261
269 void PrintLogoToTextFile(std::ofstream& str, const std::string& fileName, const std::string& descr);
270
271
278 void PrintHeaderToTextFile(std::ofstream& str, const std::string& header);
279
280
289 template <typename T>
290 std::ostream& operator<< (std::ostream& _stream, const std::vector<T>& _vec)
291 {
292 size_t n = _vec.size();
293 _stream << "{ ";
294 if (n > 0)
295 {
296 for (size_t j = 0; j < n - 1; ++j)
297 _stream << _vec[j] << ", ";
298 _stream << _vec[n - 1];
299 }
300 _stream << " }";
301 return _stream;
302 }//operator<<(...)
303
304
312 inline std::ostream& operator<< (std::ostream& _stream, const std::pair<std::pair<std::string, int>, std::string>& _pair)
313 {
314 _stream << "( ( " << _pair.first.first << ", " << _pair.first.second << " ), " << _pair.second << " )";
315 return _stream;
316 }//operator<<(...)
317
318
326 inline std::ostream& operator<< (std::ostream& _stream, const std::pair<std::string, int>& _pair)
327 {
328 _stream << "( " << _pair.first << ", " << _pair.second << " )";
329 return _stream;
330 }//operator<<(...)
331
332
333
340 inline bool fileExistTest(std::string& fileName, LogStream& info, bool exitKey = false, const std::list <std::string>& extList = {})
341 {
342 std::list<std::string> fullExtList(extList);
343 fullExtList.insert(fullExtList.begin(), "");
344
345 for (const auto& ext : fullExtList)
346 {
347 std::string newFileName = ((ext == "") ? fileName : (fileName + "." + ext));
348 std::ifstream f(newFileName.c_str());
349 if (f.good())
350 {
351 f.close();
352 f.clear();
353
354 info('i') << "file " << newFileName << " is found" << std::endl;
355 fileName = newFileName;
356 return true;
357 }
358 }
359
360 if (exitKey)
361 {
362 info('e') << "file " << fileName << " is not found" << std::endl;
363 exit(-1);
364 }
365 else
366 info('i') << "file " << fileName << " is not found" << std::endl;
367
368 return false;
369 }
370
371
379 inline std::string fileNameStep(const std::string& name, int length, size_t number, const std::string& ext)
380 {
381 std::string fname(name);
382
383 size_t dec = 1;
384
385 for (int i = 1; i < length; ++i)
386 {
387 dec *= 10;
388 if (number < dec)
389 fname += "0";
390 }
391
392 std::ostringstream ss;
393 ss << number;
394 fname += ss.str();
395
396 if (ext.size() > 0)
397 {
398 fname += ".";
399 fname += ext;
400 }
401
402 return fname;
403 }
404
405
410 inline void copyFile(const std::string& fileNameFrom, const std::string& fileNameTo)
411 {
412 std::string buf;
413 buf.resize(BUFSIZ);
414
415 FILE *in, *out;
416 size_t n;
417
418
419#pragma warning (push)
420#pragma warning (disable: 4996)
421 in = fopen(fileNameFrom.c_str(), "rb");
422 out = fopen(fileNameTo.c_str(), "wb");
423#pragma warning (pop)
424
425 while ((n = fread((void*)buf.data(), 1, BUFSIZ, in)) != 0)
426 {
427 fwrite((void*)buf.data(), 1, n, out);
428 }
429
430 std::fclose(in);
431 std::fclose(out);
432 }//copyFile
433
434
439 inline void CreateUserDirectory(const std::string& dir, const std::string& name)
440 {
441#if defined(_WIN32)
442 _mkdir((dir + name).c_str());
443#else
444 mkdir((dir + name).c_str(), S_IRWXU | S_IRGRP | S_IROTH);
445#endif
446 }
447
448
454 template<typename T>
455 inline T sqr(T x) { return x * x; }
456
462 template<typename T>
463 inline T cubPower(T x) { return x * x * x; }
464
465
471 template <typename T>
472 inline double macos(const T x)
473 {
474 double res = abs(x) > 1.0 ? 0.5*PI*(1 - sign(x)) : acos(x);
475 return res;
476 }
477
478
484 template <typename T>
485 int sign(T x)
486 {
487 double dx = (double)x;
488 if (dx > 0) return 1;
489 if ( (dx < 0.0) || (dx < -0.0) ) return -1;
490 return 0;
491 }
492
493
494
499 void SaveToStream(const Eigen::MatrixXd& matr, std::ostream& str);
500
505 void SaveToStream(const Eigen::MatrixXcd& matr, std::ostream& str);
506
511 void SaveToStream(const Eigen::VectorXd& vec, std::ostream& str);
512
517 void SaveToStream(const std::vector<Point2D>& vec, std::ostream& str);
518
523 double M4(double t);
524
529 void ModifyE2(double* ee2, double dst2);
530
531
537 double Alpha(const Point2D& p, const Point2D& s);
538
544 double Lambda(const Point2D& p, const Point2D& s);
545
554 Point2D Omega(const Point2D& a, const Point2D& b, const Point2D& c);
555
560 template<typename T>
561 void SwapEnd(T& var)
562 {
563 char* varArray = reinterpret_cast<char*>(&var);
564 for (long i = 0; i < static_cast<long>(sizeof(var) / 2); ++i)
565 std::swap(varArray[sizeof(var) - 1 - i], varArray[i]);
566 }
567
569 inline double boundDenom(double r2, double eps2)
570 {
571#ifndef LAMBVORTEX
572 return std::max(r2, eps2);
573#else
574 if (r2 > eps2)
575 return std::max(r2, eps2);
576 else
577 return (r2 < 1e-10) ? 1e-10 : r2 / (1.0 - exp(-6.0*r2 / eps2));
578#endif
579 }
580
581}//namespace VMlib
582
583using VMlib::sqr;
584using VMlib::cubPower;
585
586#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
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:439
void PrintUniversalLogoToStream(std::ostream &str)
Передача в поток вывода универсальной шапки программы VM2D/VM3D.
Definition defs.cpp:92
double macos(const T x)
Усовершенствованный аркосинус
Definition defs.h:472
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:379
bool fileExistTest(std::string &fileName, LogStream &info, bool exitKey=false, const std::list< std::string > &extList={})
Проверка существования файла
Definition defs.h:340
T cubPower(T x)
Возведение числа в куб
Definition defs.h:463
T sqr(T x)
Возведение числа в квадрат
Definition defs.h:455
double boundDenom(double r2, double eps2)
Способ сглаживания скорости вихря (вихрь Рэнкина или вихрь Ламба)
Definition defs.h:569
void copyFile(const std::string &fileNameFrom, const std::string &fileNameTo)
Копирование файла
Definition defs.h:410
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:485
void SwapEnd(T &var)
Вспомогательная функция перестановки байт местами (нужно для сохранения бинарных VTK)
Definition defs.h:561
std::ostream & operator<<(std::ostream &_stream, const std::vector< T > &_vec)
Переопределение оператора "<<" для вывода в поток вектора std::vector.
Definition defs.h:290
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:114
const VMlib::Point2D defaultBasePoint
Базовое смещение профиля
Definition defs.h:187
const double defaultDistFar
Радиус убивания дальнего следа
Definition defs.h:127
const int defaultMechanicalSystemType
Тип механической системы
Definition defs.h:206
const bool defaultCalcCoefficients
Признак расчета безразмерных коэффициентов вместо сил
Definition defs.h:160
static std::ostream * defaultQueueLogStream
Поток вывода логов и ошибок очереди
Definition defs.h:219
static v3D defaultAddMassVcm
Definition defs.h:226
const std::string defaultWakesDir
Каталог с файлами вихревых следов
Definition defs.h:170
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:142
const double defaultVRef
Референсная скорость, равная нулю, что означает ее равенство скорости набегающего потока
Definition defs.h:139
const Point2D defaultScale
Коэффициент масштабирования профиля
Definition defs.h:191
const double defaultDelta
Расстояние, на которое рождаемый вихрь отодвигается от профиля
Definition defs.h:130
const bool defaultRotateForces
Признак работы в "географической" системе координат
Definition defs.h:157
const Point2D defaultAddedMass
Присоединенная масса
Definition defs.h:200
static Point2D defaultInitVelocity
Definition defs.h:232
const bool defaultInverse
Признак разворота нормалей (для расчета внутреннего течения)
Definition defs.h:203
const int defaultSaveVPstep
Definition defs.h:104
static double defaultInitAngularVelocity
Definition defs.h:233
const double defaultEpsCol
Радиус вихря по умолчанию
Definition defs.h:124
const double defaultTimeAccel
Definition defs.h:100
static v3D defaultAddMassWcm
Definition defs.h:227
const double defaultChord
Хорда
Definition defs.h:197
const std::pair< std::string, int > defaultVelocityComputation
Способ вычисления скоростей вихрей
Definition defs.h:151
static double defaultInitAngularDisplacement
Definition defs.h:231
const int defaultNp
Необходимое число процессоров для решения задачи
Definition defs.h:213
const std::string defaultFileSource("")
Файл с источниками
const std::vector< std::string > defaultAirfoil({})
Список профилей
const double defaultAngle
Угол атаки
Definition defs.h:194
const std::string defaultCopyPath
Путь к каталогу с задачей для копирования в новые каталоги
Definition defs.h:216
const double defaultMaxGamma
Число вихрей, рождаемых на одной панели
Definition defs.h:136
const int defaultVortexPerPanel
Число вихрей, рождаемых на одной панели
Definition defs.h:133
const int defaultNameLength
Число разрядов в имени файла
Definition defs.h:118
const double rotateAngleVpPoints
Угол поворота точек VP.
Definition defs.h:163
const std::string defaultAirfoilsDir
Каталог с файлами профилей
Definition defs.h:166
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:207
static std::ostream * defaultWorld2DLogStream
Поток вывода логов и ошибок задачи
Definition defs.h:222
const VMlib::v3D defaultBasePoint3D
Definition defs.h:188
const std::vector< std::string > defaultReviseParameters
Definition defs.h:115
const int defaultSaveVtxStep
Definition defs.h:108
const std::vector< std::string > defaultFileAirfoil({})
Список профилей
const std::string defaultBodiesDir
Definition defs.h:167
const std::pair< std::string, int > defaultBoundaryCondition
Способ удовлетворения граничного условия
Definition defs.h:145
const std::string defaultPspFile
Имя файла с паспортом задачи
Definition defs.h:210
const std::pair< std::string, int > defaultLinearSystemSolver
Способ решения линейной системы
Definition defs.h:148
const double defaultSigma0
Радиус вихря по умолчанию
Definition defs.h:121
static bool defaultAddMass
Расчет присоединенной массы
Definition defs.h:225
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:230
Заголовочный файл с описанием класса v3D.