DiffEq - Modern C++ ODE Integration Library 1.0.0
High-performance C++ library for solving ODEs with async signal processing
Loading...
Searching...
No Matches
parallelism_usage_demo.cpp
1#include <diffeq.hpp>
2#include <vector>
3#include <iostream>
4#include <chrono>
5#include <random>
6#include <thread>
7#include <future>
8#include <algorithm>
9#include <execution>
10#include <ranges>
11#include <numeric>
12
19void modern_parallel_integration_example() {
20 std::cout << "\n=== Modern Parallel Integration Example ===" << std::endl;
21
22 // Example: Parallel ODE integration for multiple initial conditions
23 std::vector<std::vector<double>> initial_conditions;
24 for (int i = 0; i < 100; ++i) {
25 initial_conditions.push_back({static_cast<double>(i), 0.0});
26 }
27
28 // Simple exponential decay: dy/dt = -0.1 * y
29 auto system = [](double t, const std::vector<double>& y, std::vector<double>& dydt) {
30 dydt[0] = -0.1 * y[0];
31 dydt[1] = -0.2 * y[1];
32 };
33
34 std::cout << "Integrating " << initial_conditions.size() << " initial conditions in parallel..." << std::endl;
35
36 auto start_time = std::chrono::high_resolution_clock::now();
37
38 // Use standard C++20 parallel execution
39 std::for_each(std::execution::par, initial_conditions.begin(), initial_conditions.end(),
40 [&](std::vector<double>& state) {
41 auto integrator = std::make_unique<diffeq::RK45Integrator<std::vector<double>>>(system);
42 integrator->step(state, 0.01); // Single integration step
43 });
44
45 auto end_time = std::chrono::high_resolution_clock::now();
46 auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time);
47
48 std::cout << "[PASS] Parallel integration completed in " << duration.count() << " us!" << std::endl;
49 std::cout << "Result for initial condition 10: [" << initial_conditions[10][0]
50 << ", " << initial_conditions[10][1] << "]" << std::endl;
51}
52
60
61// Robot arm dynamics (simplified)
63 double mass = 1.0;
64 double length = 0.5;
65 double damping = 0.1;
66 double gravity = 9.81;
67
68 void operator()(double t, const std::vector<double>& state, std::vector<double>& derivative) {
69 // state = [angle, angular_velocity]
70 // Simple pendulum with control input
71 double angle = state[0];
72 double angular_vel = state[1];
73
74 // Control input (placeholder - would come from feedback controller)
75 double control_torque = -2.0 * angle - 0.5 * angular_vel; // PD controller
76
77 derivative[0] = angular_vel;
78 derivative[1] = -(gravity / length) * std::sin(angle) -
79 (damping / (mass * length * length)) * angular_vel +
80 control_torque / (mass * length * length);
81 }
82};
83
84void demonstrate_realtime_control() {
85 std::cout << "\n=== Robotics Control System with Modern Async ===" << std::endl;
86
87 // Setup multiple control systems (e.g., different robot joints)
88 std::vector<std::vector<double>> joint_states;
89 for (int i = 0; i < 6; ++i) { // 6-DOF robot arm
90 joint_states.push_back({0.1 * i, 0.0}); // [angle, angular_velocity]
91 }
92
93 auto start_time = std::chrono::high_resolution_clock::now();
94
95 // Parallel control loop using standard C++ parallelism
96 std::for_each(std::execution::par, joint_states.begin(), joint_states.end(),
97 [](std::vector<double>& state) {
98 RobotArmSystem system;
99 auto integrator = std::make_unique<diffeq::RK45Integrator<std::vector<double>>>(system);
100 integrator->step(state, 0.001); // 1ms control timestep
101 });
102
103 auto end_time = std::chrono::high_resolution_clock::now();
104 auto duration = std::chrono::duration_cast<std::chrono::microseconds>(end_time - start_time);
105
106 std::cout << "Parallel control completed in " << duration.count() << " us" << std::endl;
107 std::cout << "Average per joint: " << duration.count() / joint_states.size() << " us" << std::endl;
108
109 // Advanced async approach using diffeq async capabilities
110 std::cout << "\n--- Advanced Async Approach ---" << std::endl;
111
112 // Create integrator for robot dynamics
113 auto robot_system = RobotArmSystem{};
114 auto integrator = std::make_unique<diffeq::RK45Integrator<std::vector<double>>>(robot_system);
115
116 // Initial state: [angle=0.1 rad, angular_velocity=0]
117 std::vector<double> state = {0.1, 0.0};
118 double dt = 0.001; // 1ms timestep for 1kHz control
119 double simulation_time = 1.0;
120
121 std::cout << "Running real-time robot control simulation..." << std::endl;
122 std::cout << "Target frequency: 1kHz (1ms timestep)" << std::endl;
123
124 auto advanced_start_time = std::chrono::high_resolution_clock::now();
125
126 // Simulate real-time control loop with async execution
127 std::vector<std::future<void>> control_futures;
128
129 for (double t = 0.0; t < simulation_time; t += dt) {
130 // Execute control step asynchronously
131 auto control_future = std::async(std::launch::async, [&, t]() {
132 integrator->step(state, dt);
133 });
134
135 // Simulate sensor reading (parallel)
136 auto sensor_future = std::async(std::launch::async, [&]() {
137 // Placeholder for sensor data processing
138 std::this_thread::sleep_for(std::chrono::microseconds(50));
139 return state[0]; // Return angle measurement
140 });
141
142 // Wait for both to complete
143 control_future.wait();
144 double measured_angle = sensor_future.get();
145
146 // Output every 100ms
147 if (static_cast<int>(t * 1000) % 100 == 0) {
148 std::cout << "t=" << t << "s, angle=" << state[0]
149 << " rad, measured=" << measured_angle << " rad" << std::endl;
150 }
151 }
152
153 auto advanced_end_time = std::chrono::high_resolution_clock::now();
154 auto advanced_duration = std::chrono::duration_cast<std::chrono::milliseconds>(advanced_end_time - advanced_start_time);
155
156 std::cout << "Simulation completed in " << advanced_duration.count() << "ms" << std::endl;
157 std::cout << "Average loop time: " << advanced_duration.count() / (simulation_time / dt) << "ms" << std::endl;
158 std::cout << "Final robot state: angle=" << state[0] << " rad, velocity=" << state[1] << " rad/s" << std::endl;
159}
160
161} // namespace robotics_control
162
169
170// Geometric Brownian Motion for financial modeling
172 double mu = 0.05; // drift
173 double sigma = 0.2; // volatility
174
175 void operator()(double t, const std::vector<double>& state, std::vector<double>& derivative) {
176 derivative[0] = mu * state[0]; // deterministic part
177 }
178
179 void diffusion(double t, const std::vector<double>& state, std::vector<double>& noise_coeff) {
180 noise_coeff[0] = sigma * state[0]; // stochastic part
181 }
182};
183
184void demonstrate_monte_carlo_simulation() {
185 std::cout << "\n=== Stochastic Process Research with Modern Parallelism ===" << std::endl;
186
187 const int num_simulations = 10000;
188 const double initial_price = 100.0;
189 const double dt = 0.01;
190 const double t_final = 1.0;
191
192 std::cout << "Running " << num_simulations << " Monte Carlo simulations..." << std::endl;
193
194 auto start_time = std::chrono::high_resolution_clock::now();
195
196 // Use standard C++20 parallel execution for Monte Carlo
197 std::vector<double> final_prices(num_simulations);
198
199 std::for_each(std::execution::par,
200 std::views::iota(0, num_simulations).begin(),
201 std::views::iota(0, num_simulations).end(),
202 [&](int i) {
203 std::mt19937 rng(i); // Seed with simulation index
204 std::normal_distribution<double> normal(0.0, 1.0);
205
206 // Define SDE parameters
207 const double mu = 0.05; // drift coefficient
208 const double sigma = 0.2; // volatility coefficient
209
210 // Simple Euler-Maruyama implementation
211 std::vector<double> state = {initial_price};
212 for (double t = 0.0; t < t_final; t += dt) {
213 double dW = normal(rng) * std::sqrt(dt);
214 state[0] += mu * state[0] * dt + sigma * state[0] * dW;
215 }
216
217 final_prices[i] = state[0];
218 });
219
220 auto end_time = std::chrono::high_resolution_clock::now();
221 auto duration = std::chrono::duration_cast<std::chrono::milliseconds>(end_time - start_time);
222
223 // Calculate statistics
224 double mean_price = std::reduce(final_prices.begin(), final_prices.end()) / num_simulations;
225 double variance = 0.0;
226 for (double price : final_prices) {
227 variance += (price - mean_price) * (price - mean_price);
228 }
229 variance /= num_simulations;
230 double std_dev = std::sqrt(variance);
231
232 std::cout << "Monte Carlo simulation completed in " << duration.count() << "ms" << std::endl;
233 std::cout << "Mean final price: " << mean_price << std::endl;
234 std::cout << "Standard deviation: " << std_dev << std::endl;
235 std::cout << "Theoretical mean: " << initial_price * std::exp(0.05) << std::endl;
236}
237
238} // namespace stochastic_research
239
246
248 double k = 1.0;
249
250 void operator()(double t, const std::vector<double>& state, std::vector<double>& derivative) {
251 derivative[0] = -k * state[0];
252 }
253};
254
255void benchmark_hardware_targets() {
256 std::cout << "\n=== Hardware Performance Benchmarking ===" << std::endl;
257
258 const int num_integrations = 1000; // Reduced from 10000 to 1000 for faster execution
259 const double dt = 0.01;
260 const double t_final = 1.0;
261
262 auto system = ExponentialDecay{};
263 auto integrator = std::make_unique<diffeq::RK45Integrator<std::vector<double>>>(system);
264 std::vector<double> initial_state = {1.0};
265
266 // Sequential execution
267 auto seq_start = std::chrono::high_resolution_clock::now();
268 std::vector<std::vector<double>> seq_states(num_integrations, initial_state);
269 for (int i = 0; i < num_integrations; ++i) {
270 integrator->integrate(seq_states[i], dt, t_final);
271 }
272 auto seq_end = std::chrono::high_resolution_clock::now();
273 auto seq_duration = std::chrono::duration_cast<std::chrono::milliseconds>(seq_end - seq_start);
274
275 // Parallel execution
276 auto par_start = std::chrono::high_resolution_clock::now();
277 std::vector<std::vector<double>> par_states(num_integrations, initial_state);
278 std::for_each(std::execution::par, par_states.begin(), par_states.end(),
279 [&](std::vector<double>& state) {
280 auto local_integrator = std::make_unique<diffeq::RK45Integrator<std::vector<double>>>(system);
281 local_integrator->integrate(state, dt, t_final);
282 });
283 auto par_end = std::chrono::high_resolution_clock::now();
284 auto par_duration = std::chrono::duration_cast<std::chrono::milliseconds>(par_end - par_start);
285
286 std::cout << "Sequential execution: " << seq_duration.count() << "ms" << std::endl;
287 std::cout << "Parallel execution: " << par_duration.count() << "ms" << std::endl;
288 std::cout << "Speedup: " << static_cast<double>(seq_duration.count()) / par_duration.count() << "x" << std::endl;
289 std::cout << "Hardware concurrency: " << std::thread::hardware_concurrency() << " threads" << std::endl;
290}
291
292} // namespace hardware_benchmark
293
294void demonstrate_all_parallelism_features() {
295 std::cout << "\n=== Complete Parallelism Feature Demonstration ===" << std::endl;
296
297 modern_parallel_integration_example();
298 robotics_control::demonstrate_realtime_control();
299 stochastic_research::demonstrate_monte_carlo_simulation();
300 hardware_benchmark::benchmark_hardware_targets();
301
302 std::cout << "\n=== All Examples Completed Successfully! ===" << std::endl;
303}
304
305int main() {
306 std::cout << "Modern DiffeQ Parallelism Examples" << std::endl;
307 std::cout << "===================================" << std::endl;
308
309 demonstrate_all_parallelism_features();
310
311 return 0;
312}
Modern C++ ODE Integration Library with Real-time Signal Processing.
Hardware Benchmarking Example.
Robotics Control Systems Example.
Stochastic Process Research Example.