RustedSciThe 0.4.20

Rust framework for symbolic and numerical computing:BVP ( Newton-Raphson frozen/damped/with collocations ), IVP( BDF, Radau, Backward Euler, LSODE, LSODA, RK45, DoPri), nonlinear equations ( Levenberg, Gavin) and more
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
#![allow(non_camel_case_types)]
#![allow(non_snake_case)]
//! solvers of BVPs and IVPs, optization, nonlinear algeraic systems and more
/// #########################ODEs SECTION######################
///
/// SOLVER OF STIFF IVPs (initial value problems)
/// direct rewrite to Rust python code from SciPy
///
/// Example#1
/// ```
///use RustedSciThe::symbolic::symbolic_engine::Expr;
/// use RustedSciThe::symbolic::symbolic_functions::Jacobian;
/// use RustedSciThe::numerical::ODE_api::ODEsolver;
///             // set RHS of system as vector of strings
///            let RHS = vec!["-z-exp(-y)", "y"];
///            // parse RHS as symbolic expressions
///            let Equations = Expr::parse_vector_expression(RHS.clone());
///            let values = vec!["z".to_string(), "y".to_string()];
///            println!("Equations = {:?}", Equations);
///            // set argument
///            let arg = "x".to_string();
///            // set method
///            let method = "BDF".to_string();
///            // set initial conditions
///            let t0 = 0.0;
///            let y0 = vec![1.0, 1.0];
///            let t_bound = 1.0;
///            // set solver parameters (optional)
///            let first_step = None;
///            let atol = 1e-5;
///            let rtol = 1e-5;
///            let max_step = 1e-3;
///            let jac_sparsity = None;
///            let vectorized = false;
///            // create instance of ODE solver and solve the system
///            let mut ODE_instance = ODEsolver::new_complex(
///                Equations,
///                values,
///                arg,
///                method,
///                t0,
///                y0.into(),
///                t_bound,
///                max_step,
///                rtol,
///                atol,
///                jac_sparsity,
///                vectorized,
///                first_step,
///            );
///
///            ODE_instance.solve();
///            ODE_instance.plot_result();
/// ```
pub mod BDF;

/// Backward Euler method (good for stiff ODEs)
///
/// Example#1
/// ```
///         use RustedSciThe::symbolic::symbolic_engine::Expr;
///         use RustedSciThe::numerical::BE::BE;
///         use nalgebra::DVector;
///          //  Backward Euler method: slightly non-linear ODE
///          let RHS = vec!["-z-exp(-y)", "y"];
///          // parse RHS as symbolic expressions
///          let Equations = Expr::parse_vector_expression(RHS.clone());
///          let values = vec![  "z".to_string(), "y".to_string()];
///          println!("eq_system = {:?}",  Equations);
///          let y0 = DVector::from_vec(vec![1.0, 1.0]);
///          let arg = "x".to_string();
///          let tolerance = 1e-2;
///          let max_iterations = 500;
///          let h = Some(1e-3);
///          let t0 = 0.0;
///          let t_bound = 1.0;
///          let mut solver = BE::new();
///          solver.set_initial( Equations, values, arg, tolerance, max_iterations, h, t0, t_bound, y0);
///          println!("y = {:?}, initial_guess = {:?}", solver.newton.y,solver.newton.initial_guess);
///          solver.newton.eq_generate();
///          solver.solve();
///          let result = solver.get_result();
///        //  println!("\n result 0 = {:?}", result.0);
///         // println!("\n result 1 = {:?}", result.1);
///         // println!("result = {:?}", result.1.unwrap().shape());
///          solver.plot_result();
/// ```
pub mod BE;
#[cfg(test)]
pub(crate) mod ivp_test_support;
pub mod ivp_workloads;
/// Backward-Euler Newton implementation, retained at its historical path.
pub use BE::NR_for_Euler;
pub mod NR_for_ODE;

/// Boundary value problems solvers for stiff nonlinear ODEs
///
/// solver NR_Damp_solver_frozen implements NR method with damping
/// but without adaptive grid.
/// Frozen jacobian strategy - recalculating jacobian on condition:
/// Description of strategy                                                                 key of strategy        value user must provude for strategy
/// 1. only first time:                                                                      "Frozen_naive"                   None
/// 2. every m-th time, where m is a parameter of the strategy:                                "every_m"                    m
/// 3. every time when the solution norm greater than a certain threshold A:                   "at_high_norm".               A
/// 4. when norm of (i-1) iter multiplied by certain value B(<1) is lower than norm of i-th iter : "at_low_speed".            B
/// 5. complex - combined strategies 2,3,4                                                         "complex"              vec of  parameters [m, A, B]
///
///
/// Example#1
/// ```
///      use nalgebra::DMatrix;
///      use nalgebra::DVector;
///      use std::collections::HashMap;
///     use  RustedSciThe::symbolic::symbolic_engine::Expr;
///      use RustedSciThe::numerical::BVP_Damp::NR_Damp_solver_frozen::NRBVP;
///    let eq1 = Expr::parse_expression("y-z");
///        let eq2 = Expr::parse_expression("-z^2");
///        let eq_system = vec![eq1, eq2];

///
///        let values = vec!["z".to_string(), "y".to_string()];
///        let arg = "x".to_string();
///        let tolerance = 1e-5;
///        let max_iterations = 1500;
///       
///        let t0 = 0.0;
///        let t_end = 1.0;
///        let n_steps = 100; // Dense: 200 -300ms, 400 - 2s, 800 - 22s, 1600 - 2 min,
///        let strategy =   "Frozen".to_string();//
///        let  strategy_params = Some(HashMap::from([("complex".to_string(),
///       Some(Vec::from( [2f64, 5.0, 1e-1, ]  ))
///      )]));
/// //
///  // or
/// // Some(HashMap::from([("Frozen_naive".to_string(), None)]));
/// //  or
/// //  Some(HashMap::from([("every_m".to_string(),
/// //        Some(Vec::from( [ 5 as f64]  ))
/// //        )]));
/// //  or
/// //  Some(HashMap::from([("at_high_morm".to_string(),
/// // Some(Vec::from( [ 5 as f64]  ))
/// //)]));
/// //or
/// //Some(HashMap::from([("at_low_speed".to_string(),
/// // Some(Vec::from( [ 1e-2]  ))
/// //)]));
/// //or
/// // Some(HashMap::from([("complex".to_string(),
/// // Some(Vec::from( [ 2.0, 5.0, 1e-, ]  ))
/// //)]));
/// //  */
///        let method =   "Sparse".to_string();// or  "Dense"
///        let linear_sys_method = None;
///        let ones = vec![0.0; values.len()*n_steps];
///        let initial_guess: DMatrix<f64> = DMatrix::from_column_slice(values.len(), n_steps, DVector::from_vec(ones).as_slice());
///        let mut BorderConditions = HashMap::new();
///        BorderConditions.insert("z".to_string(), vec![(0usize, 1.0f64)]);
///        BorderConditions.insert("y".to_string(), vec![(1usize, 1.0f64)]);
///        assert_eq!(&eq_system.len(), &2);
///        let mut nr =  NRBVP::new(eq_system,
///             initial_guess,
///             values,
///             arg,
///             BorderConditions, t0, t_end, n_steps,strategy, strategy_params, linear_sys_method, method, tolerance, max_iterations);

///        println!("solving system");
///        #[allow(unused_variables)]
///        let solution = nr.solve().unwrap();
///       // println!("result = {:?}", solution);
///        nr.plot_result();
///    ```
///
/// NR_Damp_solver_damped solver implements
/// Modified Newton method or Damped Newton method with adaptive grid for solving Boundary value problems for systems of nonlinear ordinary differential equations.
///
/// The code mostly inspired by sources listed below:
/// Cantera MultiNewton solver (MultiNewton.cpp )
/// TWOPNT fortran solver (see "The Twopnt Program for Boundary Value Problems" by J. F. Grcar and Chemkin Theory Manual p.261)
///

/// Example#2
/// ```
/// use nalgebra::DMatrix;
///  use nalgebra::DVector;
///      use std::collections::HashMap;
///     use  RustedSciThe::symbolic::symbolic_engine::Expr;
/// use RustedSciThe::numerical::BVP_Damp::NR_Damp_solver_damped::SolverParams;
///     use  RustedSciThe::numerical::BVP_Damp::NR_Damp_solver_damped::NRBVP as NRBDVPd;
///     let eq1 = Expr::parse_expression("y-z");
///        let eq2 = Expr::parse_expression("-z^3");
///        let eq_system = vec![eq1, eq2];
///        let values = vec!["z".to_string(), "y".to_string()];
///        let arg = "x".to_string();
///        let tolerance = 1e-5;
///        let max_iterations = 20;
///        let t0 = 0.0;
///        let t_end = 1.0;
///        let n_steps = 50; // Dense: 200 -300ms, 400 - 2s, 800 - 22s, 1600 - 2 min,
///        let strategy =   "Damped".to_string();//
///        let  strategy_params = SolverParams::default();
/// let scheme = "forward".to_string();
///        let method =   "Sparse".to_string();// or  "Dense"
///        let linear_sys_method = None;
///        let ones = vec![0.0; values.len()*n_steps];
///        let initial_guess: DMatrix<f64> = DMatrix::from_column_slice(values.len(), n_steps, DVector::from_vec(ones).as_slice());
///        let mut BorderConditions = HashMap::new();
///        BorderConditions.insert("z".to_string(), vec![(0usize, 1.0f64)]);
///        BorderConditions.insert("y".to_string(), vec![(1usize, 1.0f64)]);
///        let Bounds = HashMap::from([  ("z".to_string(), (-10.0, 10.0),    ), ("y".to_string(), (-7.0, 7.0),    ) ]);
///        let rel_tolerance =  HashMap::from([  ("z".to_string(), 1e-4    ), ("y".to_string(), 1e-4,    ) ]);
///        assert_eq!(&eq_system.len(), &2);
///        let mut nr =  NRBDVPd::new(eq_system,
///             initial_guess,
///             values,
///             arg,
///             BorderConditions, t0, t_end, n_steps,scheme, strategy, Some(strategy_params), linear_sys_method, method, tolerance, Some(rel_tolerance), max_iterations,  Some(Bounds),None);

///        println!("solving system");
///        #[allow(unused_variables)]
///        let solution = nr.solve().unwrap();
///       // println!("result = {:?}", solution);
///        nr.plot_result();
///    ```
/// API for both solvers
/// Example#3
/// ```
///  use nalgebra::DMatrix;
///  use nalgebra::DVector;
///      use std::collections::HashMap;
/// use RustedSciThe::numerical::BVP_api::BVP;
///     use  RustedSciThe::symbolic::symbolic_engine::Expr;
///     let eq1 = Expr::parse_expression("y-z");
///  let eq2 = Expr::parse_expression("-z^3");
/// let eq_system = vec![eq1, eq2];
///
///
/// let values = vec!["z".to_string(), "y".to_string()];
/// let arg = "x".to_string();
/// let tolerance = 1e-5;
/// let max_iterations = 20;
///
/// let t0 = 0.0;
/// let t_end = 1.0;
/// let n_steps = 50; // Dense: 200 -300ms, 400 - 2s, 800 - 22s, 1600 - 2 min,
///  let strategy =   "Damped".to_string();//
///
/// let  strategy_params =
/// match strategy.as_str() {
///     "Naive" => None,
///     "Damped"=> Some(HashMap::from([("max_jac".to_string(),
///     None,    ), ("maxDampIter".to_string(),
///    None,    ), ("DampFacor".to_string(),
///     None,    )   , ("adaptive".to_string(),
///           None,    )
///
///    ])),
///    "Frozen" => Some(HashMap::from([("every_m".to_string(),
///   Some(Vec::from( [ 5 as f64]  ))
///    )])),
///     &_=>panic!("Invalid strategy!")
///
///
/// };
/// let scheme = "forward".to_string();
/// let method =   "Sparse".to_string();// or  "Dense"
/// let linear_sys_method = None;
/// let ones = vec![0.0; values.len()*n_steps];
/// let initial_guess: DMatrix<f64> = DMatrix::from_column_slice(values.len(), n_steps, DVector::from_vec(ones).as_slice());
/// let mut BorderConditions = HashMap::new();
/// BorderConditions.insert("z".to_string(), vec![(0usize, 1.0f64)]);
/// BorderConditions.insert("y".to_string(), vec![(1usize, 1.0f64)]);
/// let Bounds = HashMap::from([  ("z".to_string(), (-10.0, 10.0),    ), ("y".to_string(), (-7.0, 7.0),    ) ]);
/// let rel_tolerance =  HashMap::from([  ("z".to_string(), 1e-4    ), ("y".to_string(), 1e-4,    ) ]);
/// assert_eq!(&eq_system.len(), &2);
/// let mut nr =  BVP::new(eq_system,
///      initial_guess,
///      values,
///      arg,
///      BorderConditions, t0, t_end, n_steps, scheme, strategy, strategy_params, linear_sys_method, method, tolerance,
///        max_iterations,  Some(rel_tolerance),Some(Bounds), None);
///
/// println!("solving system");
/// nr.solve();
/// nr.plot_result();
/// nr.save_to_file(None);
///    ```
pub mod BVP_Damp;
//
pub mod BVP_api;
/// Typed solver-discovery facade. Prefer this for quick cross-solver
/// experiments; use the solver-specific modules for detailed configuration.
pub use BVP_api::{
    BvpApiError, BvpBoundaryCondition, BvpBoundarySide, BvpMatrixBackend, BvpProblem,
    BvpSolution, BvpSolver, BvpSolverBuilder, BvpSolverKind, BvpSolverOptions,
};
/// BVP solver with collocation method
/// rewritten in Rust from Python code from SciPy
pub mod BVP_sci;
///  a collection of test examples of exect solutions of BVPs for testing purposes
pub mod Examples_and_utils;

pub mod LSODE2;
/// RK45 and Dormand-Prince methods
pub mod NonStiff_api;
/// solvers of nonlinear algebraic equations
pub mod Nonlinear_systems;
///  general api for ODE solvers  (BDF, RK4, etc.)
///
/// Example#1
/// ```
///use RustedSciThe::symbolic::symbolic_engine::Expr;
/// use RustedSciThe::symbolic::symbolic_functions::Jacobian;
/// use RustedSciThe::numerical::ODE_api::ODEsolver;
///
///       //create instance of structure for symbolic equation system and Jacobian
/// let mut Jacobian_instance = Jacobian::new();
// define argument andunknown variables
/// let x = Expr::Var("x".to_string()); // argument
/// let y = Expr::Var("y".to_string());
/// let z:Expr = Expr::Var("z".to_string());
//define equation system
///  let eq1:Expr = Expr::Const(-1.0 as f64)*z.clone() - (Expr::Const(-1.0 as f64)*y.clone() ).exp();
/// let eq2:Expr = y;
/// let eq_system = vec![eq1, eq2];
// set unkown variables
/// let values = vec![  "z".to_string(), "y".to_string()];
// set argument
/// let arg = "x".to_string();
// set method
/// let method = "BDF".to_string();
// set initial conditions
/// let t0 = 0.0;
/// let y0 = vec![1.0, 1.0];
/// let t_bound = 1.0;
/// // set solver parameters (optional)
/// let first_step = None;
/// let atol = 1e-5;
/// let rtol = 1e-5;
/// let max_step = 1e-3;
/// let jac_sparsity = None;
/// let vectorized = false;
// create instance of ODE solver and solve the system
///let mut ODE_instance = ODEsolver::new_complex(
///    eq_system,
///    values,
///    arg,
///    method,
///    t0,
///    y0.into(),
///    t_bound,
///    max_step,
///    rtol,
///    atol,
///    jac_sparsity,
///    vectorized,
///   first_step);
/// ODE_instance.solve();
/// // plot the solution
/// ODE_instance.plot_result();
/// ODE_instance.save_result();
/// ```
/// Non-stiff equations: use ODE general api ODEsolver
/// RK45 and Dormand-Prince methods are available
/// Example#2
/// ```
/// use RustedSciThe::symbolic::symbolic_engine::Expr;
///  use RustedSciThe::numerical::ODE_api::ODEsolver;
///          //Example 2 the laziest way to solve ODE
///    // set RHS of system as vector of strings
///    let RHS = vec!["-z-exp(-y)", "y"];
///    // parse RHS as symbolic expressions
///    let Equations = Expr::parse_vector_expression(RHS.clone());
///    let values = vec![  "z".to_string(), "y".to_string()];
///    println!("Equations = {:?}", Equations);   
///    // set argument
///    let arg = "x".to_string();
///      // set method
///      let method = "BDF".to_string();
///      // set initial conditions
///      let t0 = 0.0;
///      let y0 = vec![1.0, 1.0];
///      let t_bound = 1.0;
///      // set solver parameters (optional)
///      let first_step = None;
///      let atol = 1e-5;
///      let rtol = 1e-5;
///      let max_step = 1e-3;
///      let jac_sparsity = None;
///      let vectorized = false;
///      // create instance of ODE solver and solve the system
///      let mut ODE_instance = ODEsolver::new_complex(
///        Equations,
///        values,
///        arg,
///        method,
///        t0,
///        y0.into(),
///        t_bound,
///        max_step,
///        rtol,
///        atol,   
///        jac_sparsity,
///        vectorized,
///        first_step
///    );
///    ODE_instance.solve();
///    ODE_instance.plot_result();
///    ODE_instance.save_result();
///  ```
/// Example#3
/// ```
/// use RustedSciThe::symbolic::symbolic_engine::Expr;
///  use RustedSciThe::numerical::ODE_api::ODEsolver;
///   let RHS = vec!["-z-y", "y"];
// parse RHS as symbolic expressions
///   let Equations = Expr::parse_vector_expression(RHS.clone());
///   let values = vec![  "z".to_string(), "y".to_string()];
///   println!("Equations = {:?}", Equations);   
///   // set argument
///   let arg = "x".to_string();
///     // set method
///     let method = "DOPRI".to_string();
///     // set initial conditions
///     let t0 = 0.0;
///     let y0 = vec![1.0, 1.0];
///    let t_bound = 1.0;
///    // set solver parameters (optional)
///
///     let max_step = 1e-3;
///
///     // create instance of ODE solver and solve the system
///     let mut ODE_instance = ODEsolver::new_easy(
///       Equations,
///       values,
///       arg,
///       method,
///       t0,
///       y0.into(),
///       t_bound,
///       max_step,
///  );
///   ODE_instance.solve();
///   ODE_instance.plot_result();
///  ```
pub mod ODE_api;
/// Universal API for the legacy non-Radau IVP solvers.
///
/// The production Radau entry point is `numerical::Radau::RadauSolver`.
/// The archived Radau selector is intentionally not constructed by this
/// compatibility facade; use the dedicated Radau API and examples instead.
pub mod ODE_api2;
/// Radau solver for nonlinear and stiff ODEs.
///
/// The stable entry point is `RadauSolver`; the archived `Radau_main` module
/// is not part of the public API. See `examples/radau_public_api_guide.rs`.
///
/// ```
/// use RustedSciThe::numerical::Radau::{
///     RadauConfig, RadauFrontend, RadauProblem, RadauSolver,
/// };
/// use RustedSciThe::symbolic::symbolic_engine::Expr;
///
/// let problem = RadauProblem::new(
///     vec![Expr::parse_expression("-y")],
///     vec!["y".to_owned()],
///     "t",
/// );
/// let config = RadauConfig {
///     frontend: RadauFrontend::ExprLegacy,
///     t_bound: 1.0,
///     ..RadauConfig::default()
/// };
/// let mut solver = RadauSolver::prepare(problem, config)?;
/// let solution = solver.solve(&[1.0])?;
/// assert!((solution.y[0] - (-1.0f64).exp()).abs() < 1e-5);
/// # Ok::<(), Box<dyn std::error::Error>>(())
/// ```
pub mod Radau;
pub mod Rosenbrock;
/// shooting method for solving BVP
pub mod ShootingBVP;
pub mod data_processing;
/// Shared interpolation and extrapolation algorithms.
pub mod interpolation;
/// collection of optimization algorithms
pub mod optimization;