commit 8400abab18a33a7884fa6f973e36751e6fee88ab Author: ParkSuMin Date: Sat Sep 19 14:59:56 2026 +0300 Initial commit diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..1ff0c42 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,63 @@ +############################################################################### +# Set default behavior to automatically normalize line endings. +############################################################################### +* text=auto + +############################################################################### +# Set default behavior for command prompt diff. +# +# This is need for earlier builds of msysgit that does not have it on by +# default for csharp files. +# Note: This is only used by command line +############################################################################### +#*.cs diff=csharp + +############################################################################### +# Set the merge driver for project and solution files +# +# Merging from the command prompt will add diff markers to the files if there +# are conflicts (Merging from VS is not affected by the settings below, in VS +# the diff markers are never inserted). Diff markers may cause the following +# file extensions to fail to load in VS. An alternative would be to treat +# these files as binary and thus will always conflict and require user +# intervention with every merge. To do so, just uncomment the entries below +############################################################################### +#*.sln merge=binary +#*.csproj merge=binary +#*.vbproj merge=binary +#*.vcxproj merge=binary +#*.vcproj merge=binary +#*.dbproj merge=binary +#*.fsproj merge=binary +#*.lsproj merge=binary +#*.wixproj merge=binary +#*.modelproj merge=binary +#*.sqlproj merge=binary +#*.wwaproj merge=binary + +############################################################################### +# behavior for image files +# +# image files are treated as binary by default. +############################################################################### +#*.jpg binary +#*.png binary +#*.gif binary + +############################################################################### +# diff behavior for common document formats +# +# Convert binary document formats to text before diffing them. This feature +# is only available from the command line. Turn it on by uncommenting the +# entries below. +############################################################################### +#*.doc diff=astextplain +#*.DOC diff=astextplain +#*.docx diff=astextplain +#*.DOCX diff=astextplain +#*.dot diff=astextplain +#*.DOT diff=astextplain +#*.pdf diff=astextplain +#*.PDF diff=astextplain +#*.rtf diff=astextplain +#*.RTF diff=astextplain diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..1dfec36 --- /dev/null +++ b/.gitignore @@ -0,0 +1,369 @@ +## Ignore Visual Studio temporary files, build results, and +## files generated by popular Visual Studio add-ons. +## +## Get latest from https://github.com/github/gitignore/blob/master/VisualStudio.gitignore + +# User-specific files +*.rsuser +*.suo +*.user +*.userosscache +*.sln.docstates + +# User-specific files (MonoDevelop/Xamarin Studio) +*.userprefs + +# Mono auto generated files +mono_crash.* + +# Build results +[Dd]ebug/ +[Dd]ebugPublic/ +[Rr]elease/ +[Rr]eleases/ +x64/ +x86/ +[Ww][Ii][Nn]32/ +[Aa][Rr][Mm]/ +[Aa][Rr][Mm]64/ +bld/ +[Bb]in/ +[Oo]bj/ +[Oo]ut/ +[Ll]og/ +[Ll]ogs/ + +# Visual Studio 2015/2017 cache/options directory +.vs/ +# Uncomment if you have tasks that create the project's static files in wwwroot +#wwwroot/ + +# Visual Studio 2017 auto generated files +Generated\ Files/ + +# MSTest test Results +[Tt]est[Rr]esult*/ +[Bb]uild[Ll]og.* + +# NUnit +*.VisualState.xml +TestResult.xml +nunit-*.xml + +# Build Results of an ATL Project +[Dd]ebugPS/ +[Rr]eleasePS/ +dlldata.c + +# Benchmark Results +BenchmarkDotNet.Artifacts/ + +# .NET Core +project.lock.json +project.fragment.lock.json +artifacts/ + +# ASP.NET Scaffolding +ScaffoldingReadMe.txt + +# StyleCop +StyleCopReport.xml + +# Files built by Visual Studio +*_i.c +*_p.c +*_h.h +*.ilk +*.meta +*.obj +*.iobj +*.pch +*.pdb +*.ipdb +*.pgc +*.pgd +*.rsp +*.sbr +*.tlb +*.tli +*.tlh +*.tmp +*.tmp_proj +*_wpftmp.csproj +*.log +*.vspscc +*.vssscc +.builds +*.pidb +*.svclog +*.scc + +# Chutzpah Test files +_Chutzpah* + +# Visual C++ cache files +ipch/ +*.aps +*.ncb +*.opendb +*.opensdf +*.sdf +*.cachefile +*.VC.db +*.VC.VC.opendb + +# Visual Studio profiler +*.psess +*.vsp +*.vspx +*.sap + +# Visual Studio Trace Files +*.e2e + +# TFS 2012 Local Workspace +$tf/ + +# Guidance Automation Toolkit +*.gpState + +# ReSharper is a .NET coding add-in +_ReSharper*/ +*.[Rr]e[Ss]harper +*.DotSettings.user + +# TeamCity is a build add-in +_TeamCity* + +# DotCover is a Code Coverage Tool +*.dotCover + +# AxoCover is a Code Coverage Tool +.axoCover/* +!.axoCover/settings.json + +# Coverlet is a free, cross platform Code Coverage Tool +coverage*.json +coverage*.xml +coverage*.info + +# Visual Studio code coverage results +*.coverage +*.coveragexml + +# NCrunch +_NCrunch_* +.*crunch*.local.xml +nCrunchTemp_* + +# MightyMoose +*.mm.* +AutoTest.Net/ + +# Web workbench (sass) +.sass-cache/ + +# Installshield output folder +[Ee]xpress/ + +# DocProject is a documentation generator add-in +DocProject/buildhelp/ +DocProject/Help/*.HxT +DocProject/Help/*.HxC +DocProject/Help/*.hhc +DocProject/Help/*.hhk +DocProject/Help/*.hhp +DocProject/Help/Html2 +DocProject/Help/html + +# Click-Once directory +publish/ + +# Publish Web Output +*.[Pp]ublish.xml +*.azurePubxml +# Note: Comment the next line if you want to checkin your web deploy settings, +# but database connection strings (with potential passwords) will be unencrypted +*.pubxml +*.publishproj + +# Microsoft Azure Web App publish settings. Comment the next line if you want to +# checkin your Azure Web App publish settings, but sensitive information contained +# in these scripts will be unencrypted +PublishScripts/ + +# NuGet Packages +*.nupkg +# NuGet Symbol Packages +*.snupkg +# The packages folder can be ignored because of Package Restore +**/[Pp]ackages/* +# except build/, which is used as an MSBuild target. +!**/[Pp]ackages/build/ +# Uncomment if necessary however generally it will be regenerated when needed +#!**/[Pp]ackages/repositories.config +# NuGet v3's project.json files produces more ignorable files +*.nuget.props +*.nuget.targets + +# Microsoft Azure Build Output +csx/ +*.build.csdef + +# Microsoft Azure Emulator +ecf/ +rcf/ + +# Windows Store app package directories and files +AppPackages/ +BundleArtifacts/ +Package.StoreAssociation.xml +_pkginfo.txt +*.appx +*.appxbundle +*.appxupload + +# Visual Studio cache files +# files ending in .cache can be ignored +*.[Cc]ache +# but keep track of directories ending in .cache +!?*.[Cc]ache/ + +# Others +ClientBin/ +~$* +*~ +*.dbmdl +*.dbproj.schemaview +*.jfm +*.pfx +*.publishsettings +orleans.codegen.cs + +# Including strong name files can present a security risk +# (https://github.com/github/gitignore/pull/2483#issue-259490424) +#*.snk + +# Since there are multiple workflows, uncomment next line to ignore bower_components +# (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) +#bower_components/ + +# RIA/Silverlight projects +Generated_Code/ + +# Backup & report files from converting an old project file +# to a newer Visual Studio version. Backup files are not needed, +# because we have git ;-) +_UpgradeReport_Files/ +Backup*/ +UpgradeLog*.XML +UpgradeLog*.htm +ServiceFabricBackup/ +*.rptproj.bak + +# SQL Server files +*.mdf +*.ldf +*.ndf + +# Business Intelligence projects +*.rdl.data +*.bim.layout +*.bim_*.settings +*.rptproj.rsuser +*- [Bb]ackup.rdl +*- [Bb]ackup ([0-9]).rdl +*- [Bb]ackup ([0-9][0-9]).rdl + +# Microsoft Fakes +FakesAssemblies/ + +# GhostDoc plugin setting file +*.GhostDoc.xml + +# Node.js Tools for Visual Studio +.ntvs_analysis.dat +node_modules/ + +# Visual Studio 6 build log +*.plg + +# Visual Studio 6 workspace options file +*.opt + +# Visual Studio 6 auto-generated workspace file (contains which files were open etc.) +*.vbw + +# Visual Studio LightSwitch build output +**/*.HTMLClient/GeneratedArtifacts +**/*.DesktopClient/GeneratedArtifacts +**/*.DesktopClient/ModelManifest.xml +**/*.Server/GeneratedArtifacts +**/*.Server/ModelManifest.xml +_Pvt_Extensions + +# Paket dependency manager +.paket/paket.exe +paket-files/ + +# FAKE - F# Make +.fake/ + +# CodeRush personal settings +.cr/personal + +# Python Tools for Visual Studio (PTVS) +__pycache__/ +*.pyc + +# Cake - Uncomment if you are using it +# tools/** +# !tools/packages.config + +# Tabs Studio +*.tss + +# Telerik's JustMock configuration file +*.jmconfig + +# BizTalk build output +*.btp.cs +*.btm.cs +*.odx.cs +*.xsd.cs + +# OpenCover UI analysis results +OpenCover/ + +# Azure Stream Analytics local run output +ASALocalRun/ + +# MSBuild Binary and Structured Log +*.binlog + +# NVidia Nsight GPU debugger configuration file +*.nvuser + +# MFractors (Xamarin productivity tool) working folder +.mfractor/ + +# Local History for Visual Studio +.localhistory/ + +# BeatPulse healthcheck temp database +healthchecksdb + +# Backup folder for Package Reference Convert tool in Visual Studio 2017 +MigrationBackup/ + +# Ionide (cross platform F# VS Code tools) working folder +.ionide/ + +# Fody - auto-generated XML schema +FodyWeavers.xsd + +# CMake +build/ + +# Custom +results/ \ No newline at end of file diff --git a/CMakeLists.txt b/CMakeLists.txt new file mode 100644 index 0000000..54b4b8d --- /dev/null +++ b/CMakeLists.txt @@ -0,0 +1,88 @@ +# Требуем CMake не старее версии 3.20. +cmake_minimum_required(VERSION 3.20) + +# Создаём проект на языке C++. +project(mmps_homework_1 LANGUAGES CXX) + +# Используем стандарт C++17. Он нужен хосту для std::filesystem. +set(CMAKE_CXX_STANDARD 17) +# Запрещаем CMake использовать более старый стандарт. +set(CMAKE_CXX_STANDARD_REQUIRED ON) +# Отключаем нестандартные расширения конкретного компилятора. +set(CMAKE_CXX_EXTENSIONS OFF) + +# Создаём основную программу. Она ищет и загружает плагины во время выполнения. +add_executable(mmps_host src/main.cpp) + +# Позволяем подключать общий интерфейс как #include "api.hpp". +target_include_directories(mmps_host PRIVATE include) + +# В Linux функции dlopen, dlsym и dlclose могут требовать библиотеку libdl. +# В Windows LoadLibraryW/GetProcAddress предоставляются системой, поэтому +# дополнительная библиотека для компоновки не нужна. +if(UNIX AND NOT APPLE) + target_link_libraries(mmps_host PRIVATE ${CMAKE_DL_LIBS}) +endif() + +# Складываем исполняемый файл в build/bin. +set_target_properties(mmps_host PROPERTIES + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/bin" +) + +# Функция создаёт один плагин-решатель из переданного исходного файла. +function(add_mmps_solver_plugin target source) + # MODULE означает динамически загружаемый модуль: + # DLL в Windows, SO в Linux и DYLIB в macOS. + add_library(${target} MODULE ${source}) + + # Плагину доступны общие структуры, типы функций и имена символов из api.hpp, + # а также вспомогательные функции численных методов из state.hpp. + target_include_directories(${target} PRIVATE include) + + # PLUGIN_BUILD включает __declspec(dllexport) при сборке DLL в Windows. + # Определение PRIVATE и потому не передаётся другим целям. + target_compile_definitions(${target} PRIVATE PLUGIN_BUILD) + + # PREFIX "" убирает стандартный префикс lib у имени плагина. + # Все плагины складываются в общий каталог build/plugins. + set_target_properties(${target} PROPERTIES + PREFIX "" + LIBRARY_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/plugins" + RUNTIME_OUTPUT_DIRECTORY "${CMAKE_BINARY_DIR}/plugins" + ) +endfunction() + +# Каждый метод собирается в отдельную динамическую библиотеку. +add_mmps_solver_plugin( + runge_kutta_plugin + plugins/runge_kutta_plugin.cpp +) + +add_mmps_solver_plugin( + adams_bashforth_plugin + plugins/adams_bashforth_plugin.cpp +) + + +# ЧТО ПРОИСХОДИТ ПРИ СБОРКЕ +# src/main.cpp -> mmps_host.exe +# plugins/runge_kutta_plugin.cpp -> runge_kutta_plugin.dll +# plugins/adams_bashforth_plugin.cpp -> adams_bashforth_plugin.dll +# +# Хост и плагины собираются независимо. Здесь намеренно нет команд: +# target_link_libraries(mmps_host PRIVATE runge_kutta_plugin) +# target_link_libraries(mmps_host PRIVATE adams_bashforth_plugin) +# +# Поэтому в mmps_host не записываются обязательные зависимости от конкретных +# решателей. При запуске хост просматривает заданный каталог, загружает каждый +# подходящий файл через LoadLibraryW/dlopen и ищет функции по контракту api.hpp. +# Добавление ещё одного совместимого решателя не требует изменения main.cpp. +# +# ПРИМЕР СБОРКИ +# cmake -S . -B build +# cmake --build build --config Release +# +# ПРИМЕР ЗАПУСКА ИЗ КАТАЛОГА build +# bin/Release/mmps_host.exe (Visual Studio) +# bin/mmps_host (Linux/Makefiles) +# Каталог плагинов и значения k1, k2, h программа запросит через std::cin. diff --git a/include/api.hpp b/include/api.hpp new file mode 100644 index 0000000..9b36712 --- /dev/null +++ b/include/api.hpp @@ -0,0 +1,45 @@ +#pragma once + +#include +#include + +struct SolverParameters{ + double k1; + double k2; + double t_begin; + double t_end; + double step; +}; + +struct SolutionPoint{ + double t; + double x1; + double x2; + double x3; +}; + +inline constexpr std::uint32_t PLUGIN_API_VERSION = 1; + +#if defined(_WIN32) && defined(PLUGIN_BUILD) +#define PLUGIN_EXPORT extern "C" __declspec(dllexport) +#elif defined(_WIN32) +#define PLUGIN_EXPORT extern "C" +#else +#define PLUGIN_EXPORT extern "C" __attribute__((visibility("default"))) +#endif + +using plugin_api_version_fn = std::uint32_t (*)(); +using plugin_text_fn = const char* (*)(); +using function_run_fn = void (*)( + const SolverParameters*, + SolutionPoint*, + std::size_t +); + +inline constexpr const char* SYMBOL_API_VERSION = + "plugin_api_version"; +inline constexpr const char* SYMBOL_NAME = "plugin_name"; +inline constexpr const char* SYMBOL_DESCRIPTION = + "plugin_description"; +inline constexpr const char* SYMBOL_FUNCTION = "func"; + diff --git a/include/state.hpp b/include/state.hpp new file mode 100644 index 0000000..cc03d84 --- /dev/null +++ b/include/state.hpp @@ -0,0 +1,52 @@ +#pragma once + +#include "api.hpp" + +struct State +{ + double x1; + double x2; + double x3; +}; + +inline State add_scaled(const State& left, const State& right, double scale){ + return { + left.x1 + scale * right.x1, + left.x2 + scale * right.x2, + left.x3 + scale * right.x3, + }; +} + +// СОДУ +inline State derivative(const State& state, + const SolverParameters& parameters){ + return { + -parameters.k1 * state.x1, + parameters.k1 * state.x1 - parameters.k2 * state.x2, + parameters.k2 * state.x2 + }; +} + +inline State runge_kutta_step(const State& state, + const SolverParameters& parameters){ + double h = parameters.step; + + State k1 = derivative(state, parameters); + State k2 = derivative(add_scaled(state, k1, h / 2), parameters); + State k3 = derivative(add_scaled(state, k2, h / 2), parameters); + State k4 = derivative(add_scaled(state, k3, h), parameters); + + return { + state.x1 + h / 6.0 * (k1.x1 + 2 * k2.x1 + 2 * k3.x1 + k4.x1), + state.x2 + h / 6.0 * (k1.x2 + 2 * k2.x2 + 2 * k3.x2 + k4.x2), + state.x3 + h / 6.0 * (k1.x3 + 2 * k2.x3 + 2 * k3.x3 + k4.x3) + }; +} + +inline State state_from_point(const SolutionPoint& point){ + return { point.x1, point.x2, point.x3 }; +} + +inline SolutionPoint make_step(double t, const State& state){ + return { t, state.x1, state.x2, state.x3 }; +} diff --git a/plugins/adams_bashforth_plugin.cpp b/plugins/adams_bashforth_plugin.cpp new file mode 100644 index 0000000..5b02df7 --- /dev/null +++ b/plugins/adams_bashforth_plugin.cpp @@ -0,0 +1,53 @@ +#include "api.hpp" +#include "state.hpp" + +#include + +PLUGIN_EXPORT std::uint32_t plugin_api_version(){ + return PLUGIN_API_VERSION; +} + +PLUGIN_EXPORT const char* plugin_name(){ + return "Adams-Bashforth 2"; +} + +PLUGIN_EXPORT const char* plugin_description(){ + return "Explicit second-order Adams-Bashforth method with an RK4 start"; +} + +PLUGIN_EXPORT void func(const SolverParameters* parameters, + SolutionPoint* output, + std::size_t output_size){ + if (parameters == nullptr || output == nullptr || output_size == 0) + return; + + const State initial_state{1.0, 0.0, 0.0}; + output[0] = make_step(parameters->t_begin, initial_state); + + if (output_size == 1) + return; + + State first_state = runge_kutta_step(initial_state, *parameters); + output[1] = make_step(parameters->t_begin + parameters->step, first_state); + + for (std::size_t index = 1; index + 1 < output_size; ++index){ + State current = state_from_point(output[index]); + State previous = state_from_point(output[index - 1]); + State current_derivative = derivative(current, *parameters); + State previous_derivative = derivative(previous, *parameters); + double h = parameters->step; + + State next{ + current.x1 + h * (1.5 * current_derivative.x1 - + 0.5 * previous_derivative.x1), + current.x2 + h * (1.5 * current_derivative.x2 - + 0.5 * previous_derivative.x2), + current.x3 + h * (1.5 * current_derivative.x3 - + 0.5 * previous_derivative.x3), + }; + + const double next_time = parameters->t_begin + + static_cast(index + 1) * h; + output[index + 1] = make_step(next_time, next); + } +} diff --git a/plugins/runge_kutta_plugin.cpp b/plugins/runge_kutta_plugin.cpp new file mode 100644 index 0000000..4877898 --- /dev/null +++ b/plugins/runge_kutta_plugin.cpp @@ -0,0 +1,33 @@ +#include "api.hpp" +#include "state.hpp" + +#include + +PLUGIN_EXPORT std::uint32_t plugin_api_version(){ + return PLUGIN_API_VERSION; +} + +PLUGIN_EXPORT const char* plugin_name(){ + return "Runge-Kutta 4"; +} + +PLUGIN_EXPORT const char* plugin_description(){ + return "Explicit fourth-order Runge-Kutta method"; +} + +PLUGIN_EXPORT void func(const SolverParameters* parameters, + SolutionPoint* output, + std::size_t output_size){ + if (parameters == nullptr || output == nullptr || output_size == 0) + return; + + State state{1, 0, 0}; + output[0] = make_step(parameters->t_begin, state); + + for (std::size_t index = 1; index < output_size; ++index){ + state = runge_kutta_step(state, *parameters); + const double t = parameters->t_begin + + static_cast(index) * parameters->step; + output[index] = make_step(t, state); + } +} diff --git a/src/main.cpp b/src/main.cpp new file mode 100644 index 0000000..1e8aed9 --- /dev/null +++ b/src/main.cpp @@ -0,0 +1,276 @@ +#include "api.hpp" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#if defined(_WIN32) +#include +#else +#include +#endif + +namespace fs = std::filesystem; + +std::string path_text(const fs::path& path){ + return path.u8string(); +} + +class SharedLibrary +{ +public: + explicit SharedLibrary(const fs::path& path) + { +#if defined(_WIN32) + handle_ = LoadLibraryW(path.c_str()); + if (handle_ == nullptr){ + throw std::runtime_error( + "LoadLibraryW failed with error " + + std::to_string(GetLastError())); + } +#else + handle_ = dlopen(path.c_str(), RTLD_NOW | RTLD_LOCAL); + if (handle_ == nullptr) + { + const char* error = dlerror(); + throw std::runtime_error(error == nullptr ? "dlopen failed" : error); + } +#endif + } + + SharedLibrary(const SharedLibrary&) = delete; + SharedLibrary& operator=(const SharedLibrary&) = delete; + + ~SharedLibrary() + { +#if defined(_WIN32) + if (handle_ != nullptr) + FreeLibrary(handle_); +#else + if (handle_ != nullptr) + dlclose(handle_); +#endif + } + + template + FunctionPointer require(const char* symbol_name) const + { +#if defined(_WIN32) + const auto address = GetProcAddress(handle_, symbol_name); + if (address == nullptr) + throw std::runtime_error(std::string("missing symbol: ") + symbol_name); +#else + dlerror(); + void* address = dlsym(handle_, symbol_name); + const char* error = dlerror(); + if (error != nullptr) + { + throw std::runtime_error( + std::string("missing symbol: ") + symbol_name + " (" + error + ")"); + } +#endif + return reinterpret_cast(address); + } + +private: +#if defined(_WIN32) + HMODULE handle_ = nullptr; +#else + void* handle_ = nullptr; +#endif +}; + +bool is_library_candidate(const fs::path& path) +{ + std::string extension = path.extension().string(); + std::transform(extension.begin(), extension.end(), extension.begin(), + [](unsigned char character) { + return static_cast(std::tolower(character)); + }); + +#if defined(_WIN32) + return extension == ".dll"; +#elif defined(__APPLE__) + return extension == ".dylib" || extension == ".so"; +#else + return extension == ".so"; +#endif +} + +std::vector find_candidates(const fs::path& directory){ + std::vector candidates; + + if (!fs::exists(directory) || !fs::is_directory(directory)) + return candidates; + + for (const auto& entry : fs::directory_iterator(directory)){ + if (entry.is_regular_file() && is_library_candidate(entry.path())) + candidates.push_back(fs::absolute(entry.path())); + } + + std::sort(candidates.begin(), candidates.end()); + return candidates; +} + +size_t calculate_point_count(const SolverParameters& parameters){ + const size_t max_point_count = 1000000; + double interval = parameters.t_end - parameters.t_begin; + double step_count = std::floor(interval / parameters.step + 1e-12); + + if (!std::isfinite(step_count) || step_count > static_cast(max_point_count - 1)) + throw std::runtime_error("the selected h creates too many solution points"); + + return static_cast(step_count) + 1; +} + +void validate_solution(const std::vector& solution, + const SolverParameters& parameters) +{ + for (size_t index = 0; index < solution.size(); ++index) + { + const SolutionPoint& point = solution[index]; + if (!std::isfinite(point.t) || !std::isfinite(point.x1) || + !std::isfinite(point.x2) || !std::isfinite(point.x3)) + throw std::runtime_error("solver returned a non-finite value"); + + const double expected_time = parameters.t_begin + + static_cast(index) * parameters.step; + const double tolerance = + 1e-10 * (std::max)(1.0, std::abs(expected_time)); + if (std::abs(point.t - expected_time) > tolerance) + throw std::runtime_error("solver returned an invalid time grid"); + } +} + +void write_csv(const fs::path& path, const std::vector& solution){ + std::ofstream stream(path); + if (!stream) + throw std::runtime_error("cannot create CSV file: " + path_text(path)); + + stream << std::setprecision(4); + stream << "t,x1,x2,x3\n"; + + for (const SolutionPoint& point : solution){ + stream << point.t << ',' << point.x1 << ',' + << point.x2 << ',' << point.x3 << '\n'; + } +} + +void inspect_and_run(const fs::path& library_path, + const SolverParameters& parameters, + size_t point_count, + const fs::path& result_directory){ + SharedLibrary library(library_path); + + const auto api_version = library.require(SYMBOL_API_VERSION); + if (api_version() != PLUGIN_API_VERSION) + throw std::runtime_error("unsupported API version " + std::to_string(api_version())); + + const auto name = library.require(SYMBOL_NAME); + const auto description = library.require(SYMBOL_DESCRIPTION); + const auto function = library.require(SYMBOL_FUNCTION); + + const char* plugin_name = name(); + const char* plugin_description = description(); + if (plugin_name == nullptr || plugin_description == nullptr) + throw std::runtime_error("plugin returned null metadata"); + + std::vector solution(point_count, SolutionPoint{0, 0, 0, 0}); + + function(¶meters, solution.data(), solution.size()); + validate_solution(solution, parameters); + + fs::path csv_filename = library_path.stem(); + csv_filename += ".csv"; + const fs::path csv_path = result_directory / csv_filename; + write_csv(csv_path, solution); + + std::cout << "[accepted] " << path_text(library_path.filename()) << '\n' + << " name: " << plugin_name << '\n' + << " description: " << plugin_description << '\n' + << " points: " << solution.size() << '\n' + << " CSV: " << path_text(csv_path) << '\n'; +} + +int main() +{ + SolverParameters parameters{}; + std::string plugin_directory_text; + parameters.t_begin = 0.0; + parameters.t_end = 10.0; + + try { + std::cout << "Enter plugin directory: "; + if (!std::getline(std::cin, plugin_directory_text) || plugin_directory_text.empty()) + throw std::runtime_error("failed to read plugin directory"); + + const fs::path plugin_directory = fs::path(plugin_directory_text); + + std::cout << "Enter k1 [1e-5, 1e2], k2 [1e-2, 1] and h: "; + + if (!(std::cin >> parameters.k1 >> parameters.k2 >> parameters.step)) + throw std::runtime_error("failed to read k1, k2 and h"); + + if (parameters.k1 < 1e-5 || parameters.k1 > 1e2) + throw std::runtime_error("k1 must be in [1e-5, 1e2]"); + if (parameters.k2 < 1e-2 || parameters.k2 > 1.0) + throw std::runtime_error("k2 must be in [1e-2, 1]"); + + if (parameters.step <= 0.0) + throw std::runtime_error("h must be a positive finite number"); + if (parameters.step > parameters.t_end - parameters.t_begin) + throw std::runtime_error("h must not exceed the calculation interval"); + + const size_t point_count = calculate_point_count(parameters); + + std::cout << "Plugin directory: " << path_text(plugin_directory) << '\n' + << "Parameters: k1=" << parameters.k1 + << ", k2=" << parameters.k2 + << ", h=" << parameters.step << '\n'; + + const auto candidates = find_candidates(plugin_directory); + if (candidates.empty()){ + std::cout << "No plugin candidates found. Calculation is impossible.\n"; + return 0; + } + + const fs::path result_directory = fs::current_path() / "results"; + fs::create_directories(result_directory); + + size_t accepted = 0; + for (const fs::path& candidate : candidates){ + try { + inspect_and_run(candidate, parameters, point_count, + result_directory); + accepted++; + } + catch (const std::exception& error){ + std::cerr << "[rejected] " << path_text(candidate.filename()) + << ": " << error.what() << '\n'; + } + } + + std::cout << "Accepted solver plugins: " << accepted << " of " << candidates.size() << '\n'; + + if (accepted == 0){ + std::cout << "No available solver methods. Calculation is impossible.\n"; + return 0; + } + + return 0; + } + catch (const std::exception& error){ + std::cerr << "Error: " << error.what() << '\n'; + return 1; + } +}