rssn 0.2.9

A comprehensive scientific computing library for Rust, aiming for feature parity with NumPy and SymPy.
Documentation
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
use std::ops::Add;
use std::ops::Mul;
use std::ops::Sub;

use rayon::prelude::*;
use serde::Deserialize;
use serde::Serialize;

use crate::numerical::matrix::Matrix;
use crate::numerical::solve::LinearSolution;
use crate::numerical::solve::solve_linear_system;

/// A 2D vector.
#[derive(Clone, Copy, Default, Debug, Serialize, Deserialize)]
pub struct Vector2D {
    /// The x component of the vector.
    pub x: f64,
    /// The y component of the vector.
    pub y: f64,
}

impl Vector2D {
    /// Creates a new 2D vector.
    #[must_use]
    pub const fn new(
        x: f64,
        y: f64,
    ) -> Self {
        Self { x, y }
    }

    /// Calculates the norm of the vector.
    #[must_use]
    pub fn norm(&self) -> f64 {
        self.x.hypot(self.y)
    }
}

impl Add for Vector2D {
    type Output = Self;

    fn add(
        self,
        rhs: Self,
    ) -> Self {
        Self {
            x: self.x + rhs.x,
            y: self.y + rhs.y,
        }
    }
}

impl Mul<f64> for Vector2D {
    type Output = Self;

    fn mul(
        self,
        rhs: f64,
    ) -> Self {
        Self {
            x: self.x * rhs,
            y: self.y * rhs,
        }
    }
}

impl Sub for Vector2D {
    type Output = Self;

    fn sub(
        self,
        rhs: Self,
    ) -> Self {
        Self {
            x: self.x - rhs.x,
            y: self.y - rhs.y,
        }
    }
}

/// A 3D vector.
#[derive(Clone, Copy, Default, Debug, Serialize, Deserialize)]
pub struct Vector3D {
    /// The x component of the vector.
    pub x: f64,
    /// The y component of the vector.
    pub y: f64,
    /// The z component of the vector.
    pub z: f64,
}

impl Vector3D {
    /// Creates a new 3D vector.
    #[allow(dead_code)]
    #[must_use]
    pub const fn new(
        x: f64,
        y: f64,
        z: f64,
    ) -> Self {
        Self { x, y, z }
    }

    /// Calculates the norm of the vector.
    #[allow(dead_code)]
    #[must_use]
    pub fn norm(&self) -> f64 {
        self.z
            .mul_add(self.z, self.x.mul_add(self.x, self.y * self.y))
            .sqrt()
    }
}

impl Sub for Vector3D {
    type Output = Self;

    fn sub(
        self,
        rhs: Self,
    ) -> Self {
        Self {
            x: self.x - rhs.x,
            y: self.y - rhs.y,
            z: self.z - rhs.z,
        }
    }
}

/// Specifies the type of boundary condition on an element.
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub enum BoundaryCondition<T> {
    /// A known potential value.
    Potential(T),
    /// A known flux value.
    Flux(T),
}

/// A 2D boundary element.
#[allow(dead_code)]
#[derive(Clone, Copy, Debug, Serialize, Deserialize)]
pub struct Element2D {
    /// The first point of the element.
    pub p1: Vector2D,
    /// The second point of the element.
    pub p2: Vector2D,
    /// The midpoint of the element.
    pub midpoint: Vector2D,
    /// The length of the element.
    pub length: f64,
    /// The normal vector of the element.
    pub normal: Vector2D,
}

impl Element2D {
    /// Creates a new 2D boundary element.
    #[must_use]
    pub fn new(
        p1: Vector2D,
        p2: Vector2D,
    ) -> Self {
        let diff = p2 - p1;

        let length = diff.norm();

        let normal = Vector2D::new(diff.y / length, -diff.x / length);

        let midpoint = Vector2D::new(f64::midpoint(p1.x, p2.x), f64::midpoint(p1.y, p2.y));

        Self {
            p1,
            p2,
            midpoint,
            length,
            normal,
        }
    }
}

/// Solves a 2D Laplace problem (e.g., potential flow, steady-state heat conduction)
/// using the Boundary Element Method (BEM) with constant elements.
///
/// This function discretizes the boundary of the domain into elements and applies
/// boundary conditions to solve for unknown potentials or fluxes on the boundary.
///
/// # Arguments
/// * `points` - A `Vec` of `(x, y)` tuples defining the vertices of the boundary polygon.
/// * `bcs` - A `Vec` of `BoundaryCondition` for each element, specifying known potential or flux.
///
/// # Returns
/// A `Result` containing a tuple `(u, q)`, where `u` is a `Vec<f64>` of potentials
/// and `q` is a `Vec<f64>` of normal fluxes on each element. Returns an `Err` string
/// if the system is ill-posed or has no unique solution.
///
/// # Errors
///
/// This function will return an error if the number of points and boundary conditions
/// do not match, or if the BEM system has no unique solution.
pub fn solve_laplace_bem_2d(
    points: &[(f64, f64)],
    bcs: &[BoundaryCondition<f64>],
) -> Result<(Vec<f64>, Vec<f64>), String> {
    let n = points.len();

    if n != bcs.len() {
        return Err("Number of points and \
             boundary conditions must \
             match."
            .to_string());
    }

    let elements: Vec<_> = (0..n)
        .map(|i| {
            Element2D::new(
                Vector2D::new(points[i].0, points[i].1),
                Vector2D::new(points[(i + 1) % n].0, points[(i + 1) % n].1),
            )
        })
        .collect();

    let mut h_mat = Matrix::zeros(n, n);

    let mut g_mat = Matrix::zeros(n, n);

    // Parallel matrix assembly
    let matrices_data: Vec<Vec<(usize, usize, f64, f64)>> = (0..n)
        .into_par_iter()
        .map(|i| {
            let mut row = Vec::with_capacity(n);

            for j in 0..n {
                if i == j {
                    let g_ii = elements[i].length / (2.0 * std::f64::consts::PI)
                        * (1.0 - (elements[i].length / 2.0).ln());

                    row.push((i, j, 0.0, g_ii)); // Diagonal H will be set later via rigid body motion trick
                } else {
                    let r_vec = elements[j].midpoint - elements[i].midpoint;

                    let r = r_vec.norm();

                    let dot = r_vec
                        .x
                        .mul_add(elements[j].normal.x, r_vec.y * elements[j].normal.y);

                    let h_ij = -dot / (2.0 * std::f64::consts::PI * r * r);

                    let g_ij = -1.0 / (2.0 * std::f64::consts::PI) * r.ln();

                    row.push((i, j, h_ij * elements[j].length, g_ij * elements[j].length));
                }
            }

            row
        })
        .collect();

    for row in matrices_data {
        for (i, j, h, g) in row {
            *h_mat.get_mut(i, j) = h;

            *g_mat.get_mut(i, j) = g;
        }
    }

    // Rigid body motion trick: sum of row H_ij = 0
    // So H_ii = -sum_{j!=i} H_ij
    for i in 0..n {
        let mut row_sum = 0.0;

        for j in 0..n {
            if i != j {
                row_sum += *h_mat.get(i, j);
            }
        }

        *h_mat.get_mut(i, i) = -row_sum;
    }

    let mut a_mat = Matrix::zeros(n, n);

    let mut b_vec = vec![0.0; n];

    for (i, b_val) in b_vec.iter_mut().enumerate() {
        for (j, bc) in bcs.iter().enumerate() {
            match bc {
                // Unknown depends on element j's BC type
                | BoundaryCondition::Potential(u_val) => {
                    // Unknown is flux q_j. Equation side: -G_ij * q_j
                    *a_mat.get_mut(i, j) = -*g_mat.get(i, j);

                    // Known contribution from H_ij * u_j goes to RHS with minus
                    *b_val -= *h_mat.get(i, j) * u_val;
                },
                | BoundaryCondition::Flux(q_val) => {
                    // Unknown is potential u_j. Equation side: H_ij * u_j
                    *a_mat.get_mut(i, j) = *h_mat.get(i, j);

                    // Known contribution from G_ij * q_j goes to RHS
                    *b_val += *g_mat.get(i, j) * q_val;
                },
            }
        }
    }

    let solution = match solve_linear_system(&a_mat, &b_vec)? {
        | LinearSolution::Unique(sol) => sol,
        | _ => return Err("BEM system has no unique solution.".to_string()),
    };

    let mut u = vec![0.0; n];

    let mut q = vec![0.0; n];

    let mut sol_idx = 0;

    for i in 0..n {
        match bcs[i] {
            | BoundaryCondition::Potential(u_val) => {
                u[i] = u_val;

                q[i] = solution[sol_idx];

                sol_idx += 1;
            },
            | BoundaryCondition::Flux(q_val) => {
                q[i] = q_val;

                u[i] = solution[sol_idx];

                sol_idx += 1;
            },
        }
    }

    Ok((u, q))
}

/// Scenario for 2D BEM: Simulates potential flow around a cylinder.
///
/// This function sets up a circular boundary and applies boundary conditions
/// corresponding to a uniform flow in the x-direction. It then uses the BEM solver
/// to calculate the potential and flux on the cylinder's surface.
///
/// # Returns
/// A `Result` containing a tuple `(u, q)` of potentials and fluxes on the cylinder surface,
/// or an error string if the BEM system cannot be solved.
///
/// # Errors
///
/// This function will return an error if the underlying `solve_laplace_bem_2d`
/// function encounters an error.
pub fn simulate_2d_cylinder_scenario() -> Result<(Vec<f64>, Vec<f64>), String> {
    let n_points = 40;

    let radius = 1.0;

    let mut points = Vec::new();

    let mut bcs = Vec::new();

    for i in 0..n_points {
        let angle = 2.0 * std::f64::consts::PI * (f64::from(i)) / (f64::from(n_points));

        let (x, y) = (radius * angle.cos(), radius * angle.sin());

        points.push((x, y));

        bcs.push(BoundaryCondition::Potential(1.0 * x));
    }

    solve_laplace_bem_2d(&points, &bcs)
}

/// Evaluates the potential at an internal point in the domain after solving the boundary.
///
/// # Arguments
/// * `point` - The `(x, y)` coordinate of the internal point.
/// * `elements` - The boundary elements.
/// * `u` - The solved boundary potentials.
/// * `q` - The solved boundary fluxes.
#[must_use]
pub fn evaluate_potential_2d(
    point: (f64, f64),
    elements: &[Element2D],
    u: &[f64],
    q: &[f64],
) -> f64 {
    let p = Vector2D::new(point.0, point.1);

    let mut result = 0.0;

    for i in 0..elements.len() {
        let r_vec = elements[i].midpoint - p;

        let r = r_vec.norm();

        let dot = r_vec
            .x
            .mul_add(elements[i].normal.x, r_vec.y * elements[i].normal.y);

        let h_ij = -dot / (2.0 * std::f64::consts::PI * r * r);

        let g_ij = -1.0 / (2.0 * std::f64::consts::PI) * r.ln();

        result += (g_ij * elements[i].length).mul_add(q[i], -(h_ij * elements[i].length * u[i]));
    }

    result
}

/// Solves a 3D Laplace problem on a cubic domain using a simplified BEM approach.
///
/// # Errors
///
/// This is currently a placeholder function and will always succeed, but in a full
/// implementation, it would return an error if the 3D BEM system cannot be solved.
pub fn solve_laplace_bem_3d() -> Result<(), String> {
    println!(
        "3D BEM is a complex topic \
         requiring a dedicated \
         library. This is a \
         placeholder."
    );

    Ok(())
}