Compare commits

...

22 Commits

Author SHA1 Message Date
9b80340998 Merge branch 'main' into fix 2025-10-08 21:42:20 +02:00
5b2331445c Modify code and notebook 2025-10-08 21:36:44 +03:00
e3c7b88dfb New structure 2025-10-08 21:14:13 +03:00
64cb04388a Merge pull request 'c_part' (#1) from c_part into main
Reviewed-on: https://git.tjoyspotifylastfm.tech/ParkSuMin/MemMAPR-MKE/pulls/1
2025-10-06 21:25:26 +02:00
b07c9e6cea Edit border boundaries
Edit graphics notebook
2025-10-06 22:22:02 +03:00
1585c76980 I hate GU3 2025-10-02 15:46:22 +03:00
1fc2925f8f Add C-part to local matrix for cubic element 2025-09-29 19:21:04 +03:00
8957f65064 Add C-part to local matrix for linear element 2025-09-29 18:09:58 +03:00
cac280deb1 Reformat ipynb + new rules for gitignore 2025-09-25 01:38:30 +03:00
b8bc3f705a Убрал в линейной солвере переменную C + поправил внешний вид кубического солвера 2025-09-25 01:36:55 +03:00
4fe90394ec Change names for output files
Теперь в названиях файлов фигурирует количество КЭ
2025-09-24 11:29:42 +03:00
abe142a1d6 Format 2025-09-23 18:11:48 +03:00
faa2802f8c Add errors 2025-09-23 18:10:20 +03:00
6d5ce32ca3 Add jupiter notebook for results' visualization 2025-09-23 15:05:28 +02:00
2ac0141c60 Format 2025-09-21 22:53:23 +03:00
5a74b84c1d Format 2025-09-21 22:46:34 +03:00
181e0874a6 Length of element as L variable, not dx
Уж больно это сильно мешало при чтении
2025-09-21 22:46:12 +03:00
babcf0b877 Terminal view fix 2025-09-21 22:35:20 +03:00
af1950982b Start solver with new arguments 2025-09-21 22:29:38 +03:00
5a8c3357ca Add Debug preprocessor 2025-09-21 22:29:10 +03:00
4ab15cb13b Ready linear element eval 2025-09-21 22:28:44 +03:00
dc0df855d7 Temporary way of cubic elements coordinates eval 2025-09-21 22:28:08 +03:00
12 changed files with 573 additions and 202 deletions

3
.gitignore vendored
View File

@@ -636,4 +636,7 @@ FodyWeavers.xsd
*.msix
*.msm
*.msp
*.txt
!CMakeLists.txt
*.png

View File

@@ -1,11 +0,0 @@
#include "Header.h"
#include "Solver.h"
int main() {
Solver slv(3., 2., 5., 20, 1, 6);
std::cout << "Linear element:" << std::endl;
slv.Execute_Linear(-5, -10);
std::cout << "\nCubic element:" << std::endl;
slv.Execute_Cubic(-5, -10);
return 0;
}

View File

@@ -1,18 +1,24 @@

Microsoft Visual Studio Solution File, Format Version 12.00
# Visual Studio Version 17
VisualStudioVersion = 17.14.36310.24 d17.14
VisualStudioVersion = 17.14.36310.24
MinimumVisualStudioVersion = 10.0.40219.1
Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MemMAPR-MKE", "MemMAPR-MKE.vcxproj", "{5D2C9737-E669-4AF1-9B8C-4339EF6E4EB0}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
DEBUG_THIRD|x64 = DEBUG_THIRD|x64
DEBUG_THIRD|x86 = DEBUG_THIRD|x86
Debug|x64 = Debug|x64
Debug|x86 = Debug|x86
Release|x64 = Release|x64
Release|x86 = Release|x86
EndGlobalSection
GlobalSection(ProjectConfigurationPlatforms) = postSolution
{5D2C9737-E669-4AF1-9B8C-4339EF6E4EB0}.DEBUG_THIRD|x64.ActiveCfg = DEBUG_FIRST|x64
{5D2C9737-E669-4AF1-9B8C-4339EF6E4EB0}.DEBUG_THIRD|x64.Build.0 = DEBUG_FIRST|x64
{5D2C9737-E669-4AF1-9B8C-4339EF6E4EB0}.DEBUG_THIRD|x86.ActiveCfg = DEBUG_FIRST|Win32
{5D2C9737-E669-4AF1-9B8C-4339EF6E4EB0}.DEBUG_THIRD|x86.Build.0 = DEBUG_FIRST|Win32
{5D2C9737-E669-4AF1-9B8C-4339EF6E4EB0}.Debug|x64.ActiveCfg = Debug|x64
{5D2C9737-E669-4AF1-9B8C-4339EF6E4EB0}.Debug|x64.Build.0 = Debug|x64
{5D2C9737-E669-4AF1-9B8C-4339EF6E4EB0}.Debug|x86.ActiveCfg = Debug|Win32

View File

@@ -1,6 +1,14 @@
<?xml version="1.0" encoding="utf-8"?>
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
<ItemGroup Label="ProjectConfigurations">
<ProjectConfiguration Include="DEBUG_FIRST|Win32">
<Configuration>DEBUG_FIRST</Configuration>
<Platform>Win32</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="DEBUG_FIRST|x64">
<Configuration>DEBUG_FIRST</Configuration>
<Platform>x64</Platform>
</ProjectConfiguration>
<ProjectConfiguration Include="Debug|Win32">
<Configuration>Debug</Configuration>
<Platform>Win32</Platform>
@@ -32,6 +40,12 @@
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='DEBUG_FIRST|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
@@ -45,6 +59,12 @@
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='DEBUG_FIRST|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>true</UseDebugLibraries>
<PlatformToolset>v143</PlatformToolset>
<CharacterSet>Unicode</CharacterSet>
</PropertyGroup>
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration">
<ConfigurationType>Application</ConfigurationType>
<UseDebugLibraries>false</UseDebugLibraries>
@@ -60,12 +80,18 @@
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='DEBUG_FIRST|Win32'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Condition="'$(Configuration)|$(Platform)'=='DEBUG_FIRST|x64'" Label="PropertySheets">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
<ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|x64'">
<Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" />
</ImportGroup>
@@ -82,6 +108,18 @@
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='DEBUG_FIRST|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>WIN32;_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
@@ -100,8 +138,26 @@
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>_DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<PreprocessorDefinitions>DEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>Default</LanguageStandard>
<LanguageStandard_C>Default</LanguageStandard_C>
<AdditionalIncludeDirectories>include/</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
<GenerateDebugInformation>true</GenerateDebugInformation>
</Link>
</ItemDefinitionGroup>
<ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='DEBUG_FIRST|x64'">
<ClCompile>
<WarningLevel>Level3</WarningLevel>
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>DEBUG;_CONSOLE;THIRD;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>Default</LanguageStandard>
<LanguageStandard_C>Default</LanguageStandard_C>
<AdditionalIncludeDirectories>include/</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
@@ -116,6 +172,9 @@
<SDLCheck>true</SDLCheck>
<PreprocessorDefinitions>NDEBUG;_CONSOLE;%(PreprocessorDefinitions)</PreprocessorDefinitions>
<ConformanceMode>true</ConformanceMode>
<LanguageStandard>Default</LanguageStandard>
<LanguageStandard_C>Default</LanguageStandard_C>
<AdditionalIncludeDirectories>include/</AdditionalIncludeDirectories>
</ClCompile>
<Link>
<SubSystem>Console</SubSystem>
@@ -123,15 +182,15 @@
</Link>
</ItemDefinitionGroup>
<ItemGroup>
<ClCompile Include="MemMAPR-MKE.cpp" />
<ClCompile Include="Solver.cpp" />
<ClCompile Include="src\MemMAPR-MKE.cpp" />
<ClCompile Include="src\Solver.cpp" />
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="Header.h" />
<ClInclude Include="Solver.h" />
<ClInclude Include="include\Header.h" />
<ClInclude Include="include\Solver.h" />
</ItemGroup>
<Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" />
<ImportGroup Label="ExtensionTargets">

View File

@@ -18,22 +18,22 @@
</Filter>
</ItemGroup>
<ItemGroup>
<ClCompile Include="MemMAPR-MKE.cpp">
<Filter>Исходные файлы</Filter>
</ClCompile>
<ClCompile Include="Solver.cpp">
<ClCompile Include="src\Solver.cpp">
<Filter>Solver</Filter>
</ClCompile>
<ClCompile Include="src\MemMAPR-MKE.cpp">
<Filter>Исходные файлы</Filter>
</ClCompile>
</ItemGroup>
<ItemGroup>
<None Include="packages.config" />
</ItemGroup>
<ItemGroup>
<ClInclude Include="Header.h">
<Filter>Исходные файлы</Filter>
</ClInclude>
<ClInclude Include="Solver.h">
<ClInclude Include="include\Solver.h">
<Filter>Solver</Filter>
</ClInclude>
<ClInclude Include="include\Header.h">
<Filter>Исходные файлы</Filter>
</ClInclude>
</ItemGroup>
</Project>

View File

@@ -1,167 +0,0 @@
#include "Header.h"
#include <Eigen/Dense>
using namespace Eigen;
Solver::Solver(double _A, double _B, double _C, int _N, int _l, int _u) {
A = _A, B = _B, C = _C, N = _N;
upper = _u, lower = _l;
L = upper - lower;
dx = L / N;
}
void Solver::Execute_Linear(double val1, double val2) {
MatrixXd local = MatrixXd::Zero(2, 2);
local(0, 0) = A / dx - B / 2.;
local(0, 1) = -A / dx + B / 2.;
local(1, 0) = -A / dx - B / 2.;
local(1, 1) = A / dx + B / 2.;
std::cout << "Local matrix:\n" << local << std::endl;
VectorXd local_load(2);
local_load(0) = C * dx / 2;
local_load(1) = C * dx / 2;
// Ансаблированные матрицы и вектор
MatrixXd ansamb = MatrixXd::Zero(N + 1, N + 1);
VectorXd global_load = VectorXd::Zero(N + 1);
// Ансамблирование для каждого конечного элемента
for (int elem = 0; elem < N; ++elem) {
int node_i = elem;
int node_j = elem + 1;
// Матрица жесткости
ansamb(node_i, node_i) += local(0, 0);
ansamb(node_i, node_j) += local(0, 1);
ansamb(node_j, node_i) += local(1, 0);
ansamb(node_j, node_j) += local(1, 1);
// Вектор нагрузки
global_load(node_i) += local_load(0);
global_load(node_j) += local_load(1);
}
std::cout << "Before:" << std::endl;
std::cout << "Ansamb matrix:\n" << ansamb << std::endl;
std::cout << "Ansamb load vector:\n" << global_load << std::endl;
// ГУ 1-го рода
double u_left = val1; // u(1) = 5
double u_right = val2; // u(6) = 15
// Обнуляем первую строку и столбец матрицы, устанавливаем диагональ = 1
ansamb.row(0).setZero();
ansamb.col(0).setZero();
ansamb(0, 0) = 1.0;
global_load(0) = u_left;
// Обнуляем последнюю строку и столбец матрицы, устанавливаем диагональ = 1
ansamb.row(N).setZero();
ansamb.col(N).setZero();
ansamb(N, N) = 1.0;
global_load(N) = u_right;
std::cout << "\nAfter:" << std::endl;
std::cout << "Modified matrix:\n" << ansamb << std::endl;
std::cout << "Modified load vector:\n" << global_load << std::endl;
VectorXd solution = ansamb.fullPivLu().solve(global_load);
std::cout << "\nSolution:" << std::endl;
std::cout << solution << std::endl;
std::ofstream file("matrix_2.txt");
for (int i = 0; i < N + 1; i++) {
file << solution(i) << ' ';
}
file << std::endl;
}
void Solver::Execute_Cubic(double val1, double val2) {
// Локальная матрица жесткости (4x4)
MatrixXd local = MatrixXd::Zero(4, 4);
local(0, 0) = -37. * A / (10 * dx) - B / 2.;
local(0, 1) = 189. * A / (40 * dx) + 57. * B / 80.;
local(0, 2) = -27. * A / (20 * dx) - 3. * B / 10.;
local(0, 3) = 13. * A / (40. * dx) + 7. * B / 10.;
local(1, 0) = 189. * A / (40 * dx) - 57. * B / 80.;
local(1, 1) = -54. * A / (5 * dx);
local(1, 2) = 297. * A / (40. * dx) + 81. * B / 80.;
local(1, 3) = -27 * A / (20. * dx) - 3. * B / 10.;
local(2, 0) = -27. * A / (20. * dx) + 3. * B / 10.;
local(2, 1) = 297. * A / (40. * dx) - 81. * B / 80.;
local(2, 2) = -54. * A / (5. * dx);
local(2, 3) = 189. * A / (40. * dx) + 57. * B / 80.;
local(3, 0) = 13. * A / (40. * dx) - 7. * B / 80.;
local(3, 1) = -27. * A / (20. * dx) + 3. * B / 10.;
local(3, 2) = 189. * A / (40. * dx) - 57. * B / 80.;
local(3, 3) = -37. * A / (10. * dx) + B / 2.;
// Локальный вектор нагрузки (4x1)
VectorXd local_load(4);
local_load(0) = -C * dx / 8.;
local_load(1) = -3. * C * dx / 8.;
local_load(2) = -3. * C * dx / 8.;
local_load(3) = -C * dx / 8.;
std::cout << "Local matrix:\n" << local << std::endl;
std::cout << "Local load vector:\n" << local_load << std::endl;
// Размер глобальной системы: для кубических элементов (4 узла на элемент, перекрытие по 2 узла)
int ndof = 2 * N + 2;
MatrixXd ansamb = MatrixXd::Zero(ndof, ndof);
VectorXd global_load = VectorXd::Zero(ndof);
// АНСАМБЛИРОВАНИЕ
for (int elem = 0; elem < N; ++elem) {
int node_start = 2 * elem; // Начальный индекс для текущего элемента
// Добавляем локальную матрицу
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
ansamb(node_start + i, node_start + j) += local(i, j);
}
}
// Добавляем локальный вектор нагрузки
for (int i = 0; i < 4; ++i) {
global_load(node_start + i) += local_load(i);
}
}
std::cout << "Before boundary conditions:" << std::endl;
std::cout << "Ansamb matrix:\n" << ansamb << std::endl;
std::cout << "Ansamb load vector:\n" << global_load << std::endl;
// ГРАНИЧНЫЕ УСЛОВИЯ
double u_left = val1; // u(1) = 5
double u_right = val2; // u(6) = 15
ansamb.row(0).setZero();
ansamb.col(0).setZero();
ansamb(0, 0) = 1.0;
global_load(0) = u_left;
ansamb.row(ndof - 1).setZero();
ansamb.col(ndof - 1).setZero();
ansamb(ndof - 1, ndof - 1) = 1.0;
global_load(ndof - 1) = u_right;
std::cout << "\nAfter boundary conditions:" << std::endl;
std::cout << "Modified matrix:\n" << ansamb << std::endl;
std::cout << "Modified load vector:\n" << global_load << std::endl;
// Решение системы
VectorXd solution = ansamb.fullPivLu().solve(global_load);
std::cout << "\nSolution:" << std::endl;
std::cout << solution << std::endl;
// Сохранение результатов (берем только значения функции в узлах, шаг 2)
std::ofstream file("matrix_cubic.txt");
for (int i = 0; i < ndof; i += 2) {
file << solution(i) << ' ';
}
file << std::endl;
}

View File

@@ -1,10 +0,0 @@
#pragma once
class Solver {
private:
double A, B, C, L, dx;
int N, upper, lower;
public:
Solver(double _A, double _B, double _C, int _N, int _l, int _u);
void Execute_Linear(double value_1, double value_2);
void Execute_Cubic(double value_1, double value_2);
};

256
graphics.ipynb Normal file
View File

@@ -0,0 +1,256 @@
{
"cells": [
{
"cell_type": "markdown",
"id": "fda98006",
"metadata": {},
"source": [
"# Solution of second-order linear ordinary differential equation"
]
},
{
"cell_type": "markdown",
"id": "a4b21c72",
"metadata": {},
"source": [
"## Input vars"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "6653253d",
"metadata": {},
"outputs": [],
"source": [
"N = 20\n",
"linear_file = f\"matrix_linear_{N}.txt\"\n",
"cubic_file = f\"matrix_cubic_{N}.txt\""
]
},
{
"cell_type": "markdown",
"id": "781047cc",
"metadata": {},
"source": [
"## System cells"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "7fced95c",
"metadata": {},
"outputs": [],
"source": [
"def write_to_file(name: str, array):\n",
" with open(f\"{name}\", 'w') as file:\n",
" for element in array:\n",
" file.write(f\"{element} \")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d20bde93",
"metadata": {},
"outputs": [],
"source": [
"import numpy as np\n",
"import matplotlib.pyplot as plt"
]
},
{
"cell_type": "markdown",
"id": "8af07a56",
"metadata": {},
"source": [
"### Solution of $5u'' + 4u' + 1 = 0, u'(0) = u(0), u(10) = 5$"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "d0fe0703",
"metadata": {},
"outputs": [],
"source": [
"def u(x):\n",
" return (9 * np.exp(8) * (x - 30) + 155 * np.exp(8 - 4 * x / 5) - 5 * (x + 1)) / (20 - 36 * np.exp(8))"
]
},
{
"cell_type": "markdown",
"id": "efac514a",
"metadata": {},
"source": [
"### Linear element"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "18bd929b",
"metadata": {},
"outputs": [],
"source": [
"def show_plot_linear(filename: str, elements: int):\n",
" with open(filename, 'r') as file:\n",
" data_str = file.read()\n",
"\n",
" x = np.linspace(0, 10, elements + 1)\n",
" y = np.fromstring(data_str, sep=' ')\n",
" y_real = u(x)\n",
"\n",
" plt.plot(x, y, label=\"Linear element solution\", color='blue')\n",
" plt.plot(x, y_real, label=\"Numeral solution\", color='black')\n",
" plt.title(f\"Linear element, elements = {elements}\")\n",
" plt.grid(True)\n",
" plt.xlabel(\"x\")\n",
" plt.ylabel(\"u(x)\")\n",
" plt.legend()\n",
" plt.savefig(f\"linear_{elements}.png\", dpi=300)\n",
" plt.show()\n",
"\n",
" write_to_file(f\"linear_real_y_{elements}.txt\", y_real)"
]
},
{
"cell_type": "markdown",
"id": "d9a38740",
"metadata": {},
"source": [
"### Cubic element"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "73525bc7",
"metadata": {},
"outputs": [],
"source": [
"def show_plot_cubic(filename: str, elements: int):\n",
" with open(filename, 'r') as file:\n",
" data_str = file.read()\n",
"\n",
" x = np.linspace(0, 10, 3 * elements + 1)\n",
" y = np.fromstring(data_str, sep=' ')\n",
" y_real = u(x)\n",
"\n",
" plt.plot(x, y, label=\"Cubic element solution\", color=\"red\")\n",
" plt.plot(x, y_real, label=\"Numeral solution\", color='black')\n",
" plt.title(f\"Cubic element, elements = {elements} \")\n",
" plt.xlabel(\"x\")\n",
" plt.ylabel(\"u(x)\")\n",
" plt.grid(True)\n",
" plt.legend()\n",
" plt.savefig(f\"cubic_{elements}.png\", dpi=300)\n",
" plt.show()\n",
"\n",
" write_to_file(f\"cubic_real_y_{elements}.txt\", y_real)"
]
},
{
"cell_type": "markdown",
"id": "3584baa4",
"metadata": {},
"source": [
"## Main part"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "b8a772e3",
"metadata": {},
"outputs": [],
"source": [
"show_plot_linear(linear_file, N)\n",
"show_plot_cubic(cubic_file, N)"
]
},
{
"cell_type": "markdown",
"id": "22fe3de6",
"metadata": {},
"source": [
"## Errors"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "31de1104",
"metadata": {},
"outputs": [],
"source": [
"def read_data_from_file(filename):\n",
" with open(filename, 'r') as file:\n",
" content = file.read().strip()\n",
" data = np.array([float(x) for x in content.split()])\n",
" return data"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "e0e9266d",
"metadata": {},
"outputs": [],
"source": [
"def show_error(program_file: str, analytical_file: str):\n",
" # Считывание данных из файлов\n",
" real = read_data_from_file(analytical_file)\n",
" matrix = read_data_from_file(program_file)\n",
" \n",
" absolute_errors = np.abs(real - matrix)\n",
" relative_errors = absolute_errors / (np.abs(real))\n",
" relative_errors_percent = relative_errors * 100\n",
"\n",
" max_relative_error = np.max(relative_errors)\n",
" max_relative_error_percent = np.max(relative_errors_percent)\n",
" max_error_index = np.argmax(relative_errors)\n",
"\n",
" print(f\"\\nМаксимальная относительная погрешность: {max_relative_error:.6f} ({max_relative_error_percent:.2f}%)\")\n",
" print(f\"Индекс точки с максимальной погрешностью: {max_error_index}\")\n",
" print(f\"Значения в точке с максимальной погрешностью:\")\n",
" print(f\" cubic_real: {real[max_error_index]}\")\n",
" print(f\" matrix_cubic: {matrix[max_error_index]}\")\n",
" print(f\" Абсолютная разность: {absolute_errors[max_error_index]:.6f}\")"
]
},
{
"cell_type": "code",
"execution_count": null,
"id": "89918171",
"metadata": {},
"outputs": [],
"source": [
"show_error(linear_file, f\"linear_real_y_{N}.txt\")\n",
"show_error(cubic_file, f\"cubic_real_y_{N}.txt\")"
]
}
],
"metadata": {
"kernelspec": {
"display_name": "Python 3",
"language": "python",
"name": "python3"
},
"language_info": {
"codemirror_mode": {
"name": "ipython",
"version": 3
},
"file_extension": ".py",
"mimetype": "text/x-python",
"name": "python",
"nbconvert_exporter": "python",
"pygments_lexer": "ipython3",
"version": "3.12.3"
}
},
"nbformat": 4,
"nbformat_minor": 5
}

31
include/Solver.h Normal file
View File

@@ -0,0 +1,31 @@
// Особенности MSVC
#define _SILENCE_EXPERIMENTAL_FILESYSTEM_DEPRECATION_WARNING
#pragma once
#include <experimental/filesystem>
using namespace std;
using namespace std::experimental::filesystem;
class Solver {
private:
// Коэффициенты в ДУ
double A, B, C, D;
// Длина конечного элемента
double L;
// Количество конечных элементов
int N;
// Границы частного решения ДУ
int upper, lower;
public:
Solver(double _A, double _B, double _C, double _D, int _N, int _l, int _u);
void Execute_Linear(double value_1, double value_2);
void Execute_Cubic(double value_1, double value_2);
bool check_path(string path) {
return exists(path);
}
void make_path(string path) {
create_directory(path);
}
};

18
src/MemMAPR-MKE.cpp Normal file
View File

@@ -0,0 +1,18 @@
#include "Solver.h"
#include "Header.h"
#include <Eigen/Dense>
#define A 5.
#define B 4.
#define C 0.
#define D 1.
using namespace Eigen;
int main() {
std::cout << A << "u''" << " + " << B << "u'" << "+ " << C << "u + " << D << " = 0" << std::endl;
Solver slv(A, B, C, D, 20, 0, 10);
std::cout << "Linear element:";
slv.Execute_Linear(0, 5);
std::cout << "\nCubic element:";
slv.Execute_Cubic(0, 5);
return 0;
}

186
src/Solver.cpp Normal file
View File

@@ -0,0 +1,186 @@
#include "Header.h"
#include <Eigen/Dense>
using namespace Eigen;
Solver::Solver(double _A, double _B, double _C, double _D, int _N, int _l, int _u) {
if (_N < 1)
throw std::runtime_error("N CAN BE OVER THAN 1!");
A = _A, B = _B, C = _C, D = _D, N = _N;
upper = _u, lower = _l;
L = (double)(upper - lower) / N;
}
void Solver::Execute_Linear(double val1, double val2) {
// Локальная матрица жёсткости
MatrixXd local = MatrixXd::Zero(2, 2);
// Локальный вектор нагрузки
VectorXd local_load(2);
local(0, 0) = -A / L - B / 2. + C * L / 2.;
local(0, 1) = A / L + B / 2. + C * L / 2.;
local(1, 0) = A / L - B / 2. + C * L / 2.;
local(1, 1) = -A / L + B / 2. + C * L / 2.;
local_load(0) = -D * L / 2.;
local_load(1) = -D * L / 2.;
// Глобальная матрица жёсткости
MatrixXd ansamb = MatrixXd::Zero(N + 2, N + 2);
// Глобальный вектор нагрузок
VectorXd global_load = VectorXd::Zero(N + 2);
// Ансамблирование (с учётом смещения на 1)
for (int elem = 0; elem < N; ++elem) {
int node_i = elem + 1;
int node_j = elem + 2;
ansamb(node_i, node_i) += local(0, 0);
ansamb(node_i, node_j) += local(0, 1);
ansamb(node_j, node_i) += local(1, 0);
ansamb(node_j, node_j) += local(1, 1);
global_load(node_i) += local_load(0);
global_load(node_j) += local_load(1);
}
#if DEBUG
std::cout << std::endl << "Before:" << std::endl;
std::cout << "Ansamb matrix:\n" << ansamb << std::endl;
std::cout << "Ansamb load vector:\n" << global_load << std::endl;
#endif
// Boundary conditions
double u_right = val2;
// 3rd type of boundary condition
ansamb.row(0).setZero();
ansamb(0, 0) = 1;
ansamb(0, 1) = -1;
global_load(0) = 0;
ansamb(1, 1) -= A;
// 1st type of boundary condition
for (int i = 0; i < global_load.size(); ++i) {
global_load(i) = global_load(i) - u_right * ansamb(i, N + 1);
}
ansamb.row(N + 1).setZero();
ansamb.col(N + 1).setZero();
ansamb(N + 1, N + 1) = 1;
global_load(N + 1) = u_right;
#if DEBUG
std::cout << "\nAfter:" << std::endl;
std::cout << "Modified matrix:\n" << ansamb << std::endl;
std::cout << "Modified load vector:\n" << global_load << std::endl;
#endif
// Решение системы
VectorXd solution = ansamb.fullPivLu().solve(global_load);
std::cout << "\nSolution:" << std::endl;
std::cout << solution << std::endl;
std::ofstream file("matrix_linear_" + std::to_string(N) + ".txt");
for (int i = 1; i < solution.size(); i++) {
file << solution(i) << ' ';
}
file << std::endl;
}
void Solver::Execute_Cubic(double val1, double val2) {
int mat_dim = N * 3 + 2; // +2 для граничных узлов, как в линейном случае
// Локальная матрица жёсткости
MatrixXd local = MatrixXd::Zero(4, 4);
// Локальный вектор нагрузки
VectorXd local_load(4);
// Формирование локальной матрицы жёсткости
local(0, 0) = -A * 37.0 / 10.0 / L + B * (-1.0) / 2.0 + C * 8. * L / 105.;
local(0, 1) = -A * (-189.0) / 40.0 / L + B * 57.0 / 80.0 + C * 33. * L / 560.;
local(0, 2) = -A * 27.0 / 20.0 / L + B * (-3.0) / 10.0 - C * 3. * L / 140.;
local(0, 3) = -A * (-13.0) / 40.0 / L + B * 7.0 / 80.0 + C * 19. * L / 1680.;
local(1, 0) = -A * (-189.0) / 40.0 / L + B * (-57.0) / 80.0 + C * 33. * L / 560.;
local(1, 1) = -A * 54.0 / 5.0 / L + C * 27. * L / 70.;
local(1, 2) = -A * (-297.0) / 40.0 / L + B * 81.0 / 80.0 - C * 27. * L / 560.;
local(1, 3) = -A * 27.0 / 20.0 / L + B * (-3.0) / 10.0 - C * 3. * L / 140.;
local(2, 0) = -A * 27.0 / 20.0 / L + B * 3.0 / 10.0 - C * 3. * L / 140.;
local(2, 1) = -A * (-297.0) / 40.0 / L + B * (-81.0) / 80.0 - C * 27. * L / 560.;
local(2, 2) = -A * 54.0 / 5.0 / L + C * 27. * L / 70.;
local(2, 3) = -A * (-189.0) / 40.0 / L + B * 57.0 / 80.0 + C * 33. * L / 560.;
local(3, 0) = -A * (-13.0) / 40.0 / L + B * (-7.0) / 80.0 + C * 19. * L / 1680.;
local(3, 1) = -A * 27.0 / 20.0 / L + B * 3.0 / 10.0 - C * 3. * L / 140.;
local(3, 2) = -A * (-189.0) / 40.0 / L + B * (-57.0) / 80.0 + C * 33. * L / 560.;
local(3, 3) = -A * 37.0 / 10.0 / L + B * 1.0 / 2.0 + C * 8. * L / 105.;
// Локальный вектор нагрузки
local_load(0) = -D * L / 8.0;
local_load(1) = -D * 3.0 * L / 8.0;
local_load(2) = -D * 3.0 * L / 8.0;
local_load(3) = -D * L / 8.0;
// Глобальные матрицы
MatrixXd ansamb = MatrixXd::Zero(mat_dim, mat_dim);
VectorXd global_load = VectorXd::Zero(mat_dim);
// Ансамблирование (со смещением на 1, как в линейной версии)
for (int elem = 0; elem < N; ++elem) {
int node_i = 1 + elem * 3; // смещение на 1
for (int i = 0; i < 4; ++i) {
for (int j = 0; j < 4; ++j) {
ansamb(node_i + i, node_i + j) += local(i, j);
}
global_load(node_i + i) += local_load(i);
}
}
#if DEBUG
std::cout << std::endl << "Before:" << std::endl;
std::cout << "Ansamb matrix:\n" << ansamb << std::endl;
std::cout << "Ansamb load vector:\n" << global_load << std::endl;
#endif
// Граничные условия
double u_right = val2;
// 3rd type of boundary condition
ansamb.row(0).setZero();
ansamb(0, 0) = 1;
ansamb(0, 1) = -1;
global_load(0) = 0;
ansamb(1, 1) -= A;
// 1st type of boundary condition
for (int i = 0; i < global_load.size(); ++i) {
global_load(i) = global_load(i) - u_right * ansamb(i, mat_dim - 1);
}
ansamb.row(mat_dim - 1).setZero();
ansamb.col(mat_dim - 1).setZero();
ansamb(mat_dim - 1, mat_dim - 1) = 1;
global_load(mat_dim - 1) = u_right;
#if DEBUG
std::cout << "\nAfter:" << std::endl;
std::cout << "Modified matrix:\n" << ansamb << std::endl;
std::cout << "Modified load vector:\n" << global_load << std::endl;
#endif
// Решение системы
VectorXd solution = ansamb.fullPivLu().solve(global_load);
std::cout << "\nSolution:" << std::endl;
std::cout << solution << std::endl;
std::ofstream file("matrix_cubic_" + std::to_string(N) + ".txt");
for (int i = 1; i < solution.size(); i++) {
file << solution(i) << ' ';
}
file << std::endl;
}