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
65const int multipoleOrder = 12;
66//const int multipoleOrderGMRES = 12;
67
68const double multipoleTheta = 1.2;
69
70
71
73#define DYN_SCHEDULE 20
74
77
79typedef std::pair<double, double> timePeriod;
80
82const double PI = 3.1415926535897932384626433832795;
83
85const double IDPI = 0.1591549430918953357688837633725;
86
88const double DPI = 6.2831853071795864769252867665590;
89
91const double IQPI = 0.07957747154594766788444188168626;
92
94const double QPI = 12.566370614359172953850573533118;
95
99namespace defaults
100{
102 const double defaultTimeStart = 0.0;
103
105 const std::pair<std::pair<std::string, int>, std::string> defaultVelAccel = { {"RampLin", 1}, "" };
106 const double defaultTimeAccel = 0.0;
107
109 const std::pair<std::pair<std::string, int>, std::string> defaultSaveVP = { {"text", 0}, "" };
110 const int defaultSaveVPstep = 0;
111
113 const std::pair<std::pair<std::string, int>, std::string> defaultSaveVtx = { {"text", 0}, "" };
114 const int defaultSaveVtxStep = 100;
115
117 const int defaultSaveVisStress = 0;
118
120 const int defaultNameLength = 5;
121
123 const double defaultEps = 0.0; //значит, рассчитать его по длине панелей как половину средней длины панелей
124
126 const double defaultEpsCol = 0.0; //значит, рассчитать его как 2/3 eps
127
129 const double defaultDistFar = 20.0;
130
132 const double defaultDelta = 1.e-6;
133
136
138 const double defaultMaxGamma = 0.0;
139
141 const double defaultVRef = 0.0;
142
144 const size_t defaultRequiredNPanels = 0;
145
147 const std::pair<std::string, int> defaultBoundaryCondition = { "boundaryConstantLayerAver", 1 };
148
150 const std::pair<std::string, int> defaultLinearSystemSolver = { "linearSystemGauss", 0 };
151
153 const std::pair<std::string, int> defaultVelocityComputation{ "velocityBarnesHut", 1 };
154
156 //const bool defaultGeographicalAngles = false; //Для обдува ветром, когда углы считаются по компасу
157
159 const bool defaultRotateForces = false;
160
162 const bool defaultCalcCoefficients = false;
163
165 const double rotateAngleVpPoints = 0;
166
168 const std::string defaultAirfoilsDir = "../settings/airfoils/";
169 const std::string defaultBodiesDir = "../settings/bodies/";
170
172 const std::string defaultWakesDir = "../settings/wakes/";
173
175 const std::vector<std::string> defaultFileAirfoil({});
176 const std::vector<std::string> defaultFileBody({});
177
179 const std::string defaultFileWake("");
180
182 const std::string defaultFileSource("");
183
185 const std::vector<std::string> defaultAirfoil({});
186 const std::vector<std::string> defaultBody({});
187
189 const VMlib::Point2D defaultBasePoint = { 0.0, 0.0 };
190 const VMlib::v3D defaultBasePoint3D = { 0.0, 0.0, 0.0 };
191
193 const Point2D defaultScale = { 1.0, 1.0 };
194
196 const double defaultAngle = 0.0;
197
199 const double defaultChord = 0.0;
200
202 const Point2D defaultAddedMass = { 0.0, 0.0 };
203
205 const bool defaultInverse = false;
206
209 const std::string defaultMechanicalSystem = "";
210
212 const std::string defaultPspFile = "passport";
213
215 const int defaultNp = 1;
216
218 const std::string defaultCopyPath = "";
219
221 static std::ostream* defaultQueueLogStream = &std::cout;
222
224 static std::ostream* defaultWorld2DLogStream = &std::cout;
225
227 static bool defaultAddMass = false;
228 static v3D defaultAddMassVcm = { 0.0, 0.0, 0.0 };
229 static v3D defaultAddMassWcm = { 0.0, 0.0, 0.0 };
230
232 static Point2D defaultInitDisplacement = { 0.0, 0.0 };
234 static Point2D defaultInitVelocity = {0.0, 0.0};
235 static double defaultInitAngularVelocity = 0.0;
236
237} //namespace defaults
238
239
240namespace VMlib
241{
242
246 std::string CurrentDataTime();
247
248
254 void PrintLogoToStream(std::ostream& str);
255
261 void PrintUniversalLogoToStream(std::ostream& str);
262
263
271 void PrintLogoToTextFile(std::ofstream& str, const std::string& fileName, const std::string& descr);
272
273
280 void PrintHeaderToTextFile(std::ofstream& str, const std::string& header);
281
282
291 template <typename T>
292 std::ostream& operator<< (std::ostream& _stream, const std::vector<T>& _vec)
293 {
294 size_t n = _vec.size();
295 _stream << "{ ";
296 if (n > 0)
297 {
298 for (size_t j = 0; j < n - 1; ++j)
299 _stream << _vec[j] << ", ";
300 _stream << _vec[n - 1];
301 }
302 _stream << " }";
303 return _stream;
304 }//operator<<(...)
305
306
314 inline std::ostream& operator<< (std::ostream& _stream, const std::pair<std::pair<std::string, int>, std::string>& _pair)
315 {
316 _stream << "( ( " << _pair.first.first << ", " << _pair.first.second << " ), " << _pair.second << " )";
317 return _stream;
318 }//operator<<(...)
319
320
328 inline std::ostream& operator<< (std::ostream& _stream, const std::pair<std::string, int>& _pair)
329 {
330 _stream << "( " << _pair.first << ", " << _pair.second << " )";
331 return _stream;
332 }//operator<<(...)
333
334
335
342 inline bool fileExistTest(std::string& fileName, LogStream& info, bool exitKey = false, const std::list <std::string>& extList = {})
343 {
344 std::list<std::string> fullExtList(extList);
345 fullExtList.insert(fullExtList.begin(), "");
346
347 for (const auto& ext : fullExtList)
348 {
349 std::string newFileName = ((ext == "") ? fileName : (fileName + "." + ext));
350 std::ifstream f(newFileName.c_str());
351 if (f.good())
352 {
353 f.close();
354 f.clear();
355
356 info('i') << "file " << newFileName << " is found" << std::endl;
357 fileName = newFileName;
358 return true;
359 }
360 }
361
362 if (exitKey)
363 {
364 info('e') << "file " << fileName << " is not found" << std::endl;
365 exit(-1);
366 }
367 else
368 info('i') << "file " << fileName << " is not found" << std::endl;
369
370 return false;
371 }
372
373
381 inline std::string fileNameStep(const std::string& name, int length, size_t number, const std::string& ext)
382 {
383 std::string fname(name);
384
385 size_t dec = 1;
386
387 for (int i = 1; i < length; ++i)
388 {
389 dec *= 10;
390 if (number < dec)
391 fname += "0";
392 }
393
394 std::ostringstream ss;
395 ss << number;
396 fname += ss.str();
397
398 if (ext.size() > 0)
399 {
400 fname += ".";
401 fname += ext;
402 }
403
404 return fname;
405 }
406
407
412 inline void copyFile(const std::string& fileNameFrom, const std::string& fileNameTo)
413 {
414 std::string buf;
415 buf.resize(BUFSIZ);
416
417 FILE *in, *out;
418 size_t n;
419
420
421#pragma warning (push)
422#pragma warning (disable: 4996)
423 in = fopen(fileNameFrom.c_str(), "rb");
424 out = fopen(fileNameTo.c_str(), "wb");
425#pragma warning (pop)
426
427 while ((n = fread((void*)buf.data(), 1, BUFSIZ, in)) != 0)
428 {
429 fwrite((void*)buf.data(), 1, n, out);
430 }
431
432 std::fclose(in);
433 std::fclose(out);
434 }//copyFile
435
436
441 inline void CreateDirectory(const std::string& dir, const std::string& name)
442 {
443#if defined(_WIN32)
444 _mkdir((dir + name).c_str());
445#else
446 mkdir((dir + name).c_str(), S_IRWXU | S_IRGRP | S_IROTH);
447#endif
448 }
449
450
456 template<typename T>
457 inline T sqr(T x) { return x * x; }
458
459
465 template <typename T>
466 inline double macos(const T x)
467 {
468 double res = abs(x) > 1.0 ? 0.5*PI*(1 - sign(x)) : acos(x);
469 return res;
470 }
471
472
478 template <typename T>
479 int sign(T x)
480 {
481 double dx = (double)x;
482 if (dx > 0) return 1;
483 if ( (dx < 0.0) || (dx < -0.0) ) return -1;
484 return 0;
485 }
486
487
488
493 void SaveToStream(const Eigen::MatrixXd& matr, std::ostream& str);
494
499 void SaveToStream(const Eigen::MatrixXcd& matr, std::ostream& str);
500
505 void SaveToStream(const Eigen::VectorXd& vec, std::ostream& str);
506
511 void SaveToStream(const std::vector<Point2D>& vec, std::ostream& str);
512
517 double M4(double t);
518
523 void ModifyE2(double* ee2, double dst2);
524
525
531 double Alpha(const Point2D& p, const Point2D& s);
532
538 double Lambda(const Point2D& p, const Point2D& s);
539
548 Point2D Omega(const Point2D& a, const Point2D& b, const Point2D& c);
549
554 template<typename T>
555 void SwapEnd(T& var)
556 {
557 char* varArray = reinterpret_cast<char*>(&var);
558 for (long i = 0; i < static_cast<long>(sizeof(var) / 2); ++i)
559 std::swap(varArray[sizeof(var) - 1 - i], varArray[i]);
560 }
561
563 inline double boundDenom(double r2, double eps2)
564 {
565#ifndef LAMBVORTEX
566 return std::max(r2, eps2);
567#else
568 if (r2 > eps2)
569 return std::max(r2, eps2);
570 else
571 return (r2 < 1e-10) ? 1e-10 : r2 / (1.0 - exp(-6.0*r2 / eps2));
572#endif
573 }
574
575}//namespace VMlib
576
577using VMlib::sqr;
578
579#endif
Описание констант и параметров для взаимодействия с графическим ускорителем
Заголовочный файл с описанием класса LogStream.
Заголовочный файл с описанием класса pairInt.
Заголовочный файл с описанием класса Vortex2D.
Класс, определяющий работу с потоком логов
Definition LogStream.h:57
Класс, опеделяющий двумерный вектор
Definition v3D.h:60
const double QPI
Число .
Definition defs.h:94
PointType
Класс перечисления для определения типа набора точек (пелена/виртуальные вихри/точки для вычисления с...
Definition defs.h:76
std::pair< double, double > timePeriod
Тип для хранения начала и конца промежутка времени
Definition defs.h:79
const double PI
Число .
Definition defs.h:82
const double IQPI
Число .
Definition defs.h:91
const double IDPI
Число .
Definition defs.h:85
const int multipoleOrder
Definition defs.h:65
const double multipoleTheta
Definition defs.h:68
const double DPI
Число .
Definition defs.h:88
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 PrintUniversalLogoToStream(std::ostream &str)
Передача в поток вывода универсальной шапки программы VM2D/VM3D.
Definition defs.cpp:92
double macos(const T x)
Усовершенствованный аркосинус
Definition defs.h:466
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:381
bool fileExistTest(std::string &fileName, LogStream &info, bool exitKey=false, const std::list< std::string > &extList={})
Проверка существования файла
Definition defs.h:342
void CreateDirectory(const std::string &dir, const std::string &name)
Создание каталога
Definition defs.h:441
T sqr(T x)
Возведение числа в квадрат
Definition defs.h:457
double boundDenom(double r2, double eps2)
Способ сглаживания скорости вихря (вихрь Рэнкина или вихрь Ламба)
Definition defs.h:563
void copyFile(const std::string &fileNameFrom, const std::string &fileNameTo)
Копирование файла
Definition defs.h:412
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:479
void SwapEnd(T &var)
Вспомогательная функция перестановки байт местами (нужно для сохранения бинарных VTK)
Definition defs.h:555
std::ostream & operator<<(std::ostream &_stream, const std::vector< T > &_vec)
Переопределение оператора "<<" для вывода в поток вектора std::vector.
Definition defs.h:292
Point2D Omega(const Point2D &a, const Point2D &b, const Point2D &c)
Вспомогательная функция вычисления величины .
Definition defs.cpp:274
Глобальные параметры по умолчанию
Definition defs.h:100
const VMlib::Point2D defaultBasePoint
Базовое смещение профиля
Definition defs.h:189
const double defaultDistFar
Радиус убивания дальнего следа
Definition defs.h:129
const int defaultMechanicalSystemType
Тип механической системы
Definition defs.h:208
const bool defaultCalcCoefficients
Признак расчета безразмерных коэффициентов вместо сил
Definition defs.h:162
static std::ostream * defaultQueueLogStream
Поток вывода логов и ошибок очереди
Definition defs.h:221
static v3D defaultAddMassVcm
Definition defs.h:228
const std::string defaultWakesDir
Каталог с файлами вихревых следов
Definition defs.h:172
const std::vector< std::string > defaultFileBody({})
const std::vector< std::string > defaultBody({})
const int defaultSaveVisStress
Шаг подсчета поля скорости и давления
Definition defs.h:117
const size_t defaultRequiredNPanels
Желаемое число панелей для разбиения геометрии
Definition defs.h:144
const double defaultVRef
Референсная скорость, равная нулю, что означает ее равенство скорости набегающего потока
Definition defs.h:141
const Point2D defaultScale
Коэффициент масштабирования профиля
Definition defs.h:193
const double defaultDelta
Расстояние, на которое рождаемый вихрь отодвигается от профиля
Definition defs.h:132
const bool defaultRotateForces
Признак работы в "географической" системе координат
Definition defs.h:159
const Point2D defaultAddedMass
Присоединенная масса
Definition defs.h:202
static Point2D defaultInitVelocity
Definition defs.h:234
const bool defaultInverse
Признак разворота нормалей (для расчета внутреннего течения)
Definition defs.h:205
const int defaultSaveVPstep
Definition defs.h:110
static double defaultInitAngularVelocity
Definition defs.h:235
const double defaultEpsCol
Радиус вихря по умолчанию
Definition defs.h:126
const double defaultTimeAccel
Definition defs.h:106
static v3D defaultAddMassWcm
Definition defs.h:229
const double defaultChord
Хорда
Definition defs.h:199
const std::pair< std::string, int > defaultVelocityComputation
Способ вычисления скоростей вихрей
Definition defs.h:153
static double defaultInitAngularDisplacement
Definition defs.h:233
const int defaultNp
Необходимое число процессоров для решения задачи
Definition defs.h:215
const std::string defaultFileSource("")
Файл с источниками
const std::vector< std::string > defaultAirfoil({})
Список профилей
const double defaultAngle
Угол атаки
Definition defs.h:196
const std::string defaultCopyPath
Путь к каталогу с задачей для копирования в новые каталоги
Definition defs.h:218
const double defaultMaxGamma
Число вихрей, рождаемых на одной панели
Definition defs.h:138
const int defaultVortexPerPanel
Число вихрей, рождаемых на одной панели
Definition defs.h:135
const int defaultNameLength
Число разрядов в имени файла
Definition defs.h:120
const double rotateAngleVpPoints
Угол поворота точек VP.
Definition defs.h:165
const std::string defaultAirfoilsDir
Каталог с файлами профилей
Definition defs.h:168
const std::pair< std::pair< std::string, int >, std::string > defaultSaveVtx
Шаг подсчета поля скорости и давления
Definition defs.h:113
const std::pair< std::pair< std::string, int >, std::string > defaultVelAccel
Время разгона
Definition defs.h:105
const double defaultTimeStart
Начало расчета
Definition defs.h:102
const std::string defaultMechanicalSystem
Definition defs.h:209
static std::ostream * defaultWorld2DLogStream
Поток вывода логов и ошибок задачи
Definition defs.h:224
const VMlib::v3D defaultBasePoint3D
Definition defs.h:190
const int defaultSaveVtxStep
Definition defs.h:114
const std::vector< std::string > defaultFileAirfoil({})
Список профилей
const std::string defaultBodiesDir
Definition defs.h:169
const std::pair< std::string, int > defaultBoundaryCondition
Способ удовлетворения граничного условия
Definition defs.h:147
const double defaultEps
Радиус вихря по умолчанию
Definition defs.h:123
const std::string defaultPspFile
Имя файла с паспортом задачи
Definition defs.h:212
const std::pair< std::string, int > defaultLinearSystemSolver
Способ решения линейной системы
Definition defs.h:150
static bool defaultAddMass
Расчет присоединенной массы
Definition defs.h:227
const std::pair< std::pair< std::string, int >, std::string > defaultSaveVP
Шаг подсчета поля скорости и давления
Definition defs.h:109
const std::string defaultFileWake("")
Файл со следом
static Point2D defaultInitDisplacement
Для профиля на упругих связях - начальные отклонения и скорости
Definition defs.h:232
Заголовочный файл с описанием класса v3D.