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
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
use num_complex::Complex;
use rayon::prelude::*;
use serde::Deserialize;
use serde::Serialize;

use crate::numerical::transforms::fft;
use crate::numerical::transforms::fft_slice;
use crate::numerical::transforms::ifft;
use crate::numerical::transforms::ifft_slice;

/// Transposes a 2D matrix represented as a flat Vec.
pub(crate) fn transpose<T: Clone + Default + Send + Sync>(
    data: &[T],
    width: usize,
    height: usize,
) -> Vec<T> {
    let mut transposed = vec![T::default(); width * height];

    transposed
        .par_iter_mut()
        .enumerate()
        .for_each(|(idx, val)| {
            let i = idx / height;

            let j = idx % height;

            // transposed[i * height + j] comes from data[j * width + i]
            *val = data[j * width + i].clone();
        });

    transposed
}

/// Performs a 2D FFT by applying 1D FFT along rows and then columns.
pub fn fft2d(
    data: &mut Vec<Complex<f64>>,
    width: usize,
    height: usize,
) {
    data.par_chunks_mut(width).for_each(fft_slice);

    let mut transposed = transpose(data, width, height);

    transposed.par_chunks_mut(height).for_each(fft_slice);

    *data = transpose(&transposed, height, width);
}

/// Performs a 2D IFFT.
pub fn ifft2d(
    data: &mut Vec<Complex<f64>>,
    width: usize,
    height: usize,
) {
    data.par_chunks_mut(width).for_each(ifft_slice);

    let mut transposed = transpose(data, width, height);

    transposed.par_chunks_mut(height).for_each(ifft_slice);

    *data = transpose(&transposed, height, width);
}

/// Creates a 1D wavenumber grid for FFT.
pub(crate) fn create_k_grid(
    n: usize,
    dx: f64,
) -> Vec<f64> {
    let dk = 2.0 * std::f64::consts::PI / (n as f64 * dx);

    let mut k: Vec<f64> = (0..n / 2).map(|i| i as f64 * dk).collect();

    let mut k_neg: Vec<f64> = (0..n / 2)
        .map(|i| -(n as f64 / 2.0 - i as f64) * dk)
        .collect();

    k.append(&mut k_neg);

    k
}

/// Solves the 1D advection-diffusion equation (`u_t` + c*`u_x` = D*`u_xx`) using a Fourier spectral method.
#[must_use]
pub fn solve_advection_diffusion_1d(
    initial_condition: &[f64],
    dx: f64,
    c: f64,
    d: f64,
    dt: f64,
    steps: usize,
) -> Vec<f64> {
    let n = initial_condition.len();

    let k = create_k_grid(n, dx);

    let mut u_hat: Vec<Complex<f64>> = initial_condition
        .iter()
        .map(|&v| Complex::new(v, 0.0))
        .collect();

    fft(&mut u_hat);

    for _ in 0..steps {
        u_hat.par_iter_mut().enumerate().for_each(|(i, val)| {
            let ki = k[i];

            let advection_term = Complex::new(0.0, -c * ki);

            let diffusion_term = Complex::new(-d * ki * ki, 0.0);

            let rhs = (advection_term + diffusion_term) * *val;

            *val += rhs * dt;
        });
    }

    ifft(&mut u_hat);

    u_hat.into_iter().map(|v| v.re).collect()
}

/// Example scenario for the 1D spectral solver.
#[must_use]
pub fn simulate_1d_advection_diffusion_scenario() -> Vec<f64> {
    const N: usize = 128;

    const L: f64 = 2.0 * std::f64::consts::PI;

    let dx = L / N as f64;

    let x: Vec<f64> = (0..N).map(|i| i as f64 * dx).collect();

    let initial_condition: Vec<f64> = x
        .iter()
        .map(|&v| (-(v - L / 2.0).powi(2) / 0.5).exp())
        .collect();

    solve_advection_diffusion_1d(&initial_condition, dx, 1.0, 0.01, 0.01, 200)
}

/// Configuration for 2D advection-diffusion simulation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdvectionDiffusionConfig {
    /// Number of grid points along the x-axis.
    pub width: usize,
    /// Number of grid points along the y-axis.
    pub height: usize,
    /// Grid spacing along the x-axis.
    pub dx: f64,
    /// Grid spacing along the y-axis.
    pub dy: f64,
    /// Advection velocity vector (u, v).
    pub c: (f64, f64),
    /// Diffusion coefficient.
    pub d: f64,
    /// Time step size.
    pub dt: f64,
    /// Number of simulation steps.
    pub steps: usize,
}

/// Solves the 2D advection-diffusion equation using a Fourier spectral method.
#[must_use]
pub fn solve_advection_diffusion_2d(
    initial_condition: &[f64],
    config: &AdvectionDiffusionConfig,
) -> Vec<f64> {
    let kx = create_k_grid(config.width, config.dx);

    let ky = create_k_grid(config.height, config.dy);

    let mut u_hat: Vec<Complex<f64>> = initial_condition
        .iter()
        .map(|&v| Complex::new(v, 0.0))
        .collect();

    fft2d(&mut u_hat, config.width, config.height);

    for _ in 0..config.steps {
        u_hat.par_iter_mut().enumerate().for_each(|(idx, val)| {
            let i = idx % config.width;

            let j = idx / config.width;

            let kxi = kx[i];

            let kyj = ky[j];

            let advection_term = Complex::new(0.0, (-config.c.0).mul_add(kxi, -(config.c.1 * kyj)));

            let diffusion_term = Complex::new(-config.d * kxi.mul_add(kxi, kyj * kyj), 0.0);

            let rhs = (advection_term + diffusion_term) * *val;

            *val += rhs * config.dt;
        });
    }

    ifft2d(&mut u_hat, config.width, config.height);

    u_hat.into_iter().map(|v| v.re).collect()
}

/// Example scenario for the 2D spectrclsal solver.
#[must_use]
pub fn simulate_2d_advection_diffusion_scenario() -> Vec<f64> {
    const WIDTH: usize = 64;

    const HEIGHT: usize = 64;

    const L: f64 = 2.0 * std::f64::consts::PI;

    const NU: f64 = 0.01;

    const U: f64 = 0.5;

    const V: f64 = 0.5;

    const DT: f64 = 0.001;

    const STEPS: usize = 100;

    let dx = L / WIDTH as f64;

    let dy = L / HEIGHT as f64;

    let config = AdvectionDiffusionConfig {
        width: WIDTH,
        height: HEIGHT,
        dx,
        dy,
        c: (U, V),
        d: NU,
        dt: DT,
        steps: STEPS,
    };

    let mut initial_condition = vec![0.0; WIDTH * HEIGHT];

    for j in 0..HEIGHT {
        for i in 0..WIDTH {
            let x = i as f64 * dx;

            let y = j as f64 * dy;

            let val = (-(y - L / 2.0).mul_add(y - L / 2.0, (x - L / 2.0).powi(2)) / 0.5).exp();

            initial_condition[j * WIDTH + i] = val;
        }
    }

    solve_advection_diffusion_2d(&initial_condition, &config)
}

/// Performs a 3D FFT.
pub fn fft3d(
    data: &mut Vec<Complex<f64>>,
    width: usize,
    height: usize,
    depth: usize,
) {
    let plane_size = width * height;

    data.par_chunks_mut(width).for_each(fft_slice);

    let mut transposed_xy = vec![Complex::default(); data.len()];

    for k in 0..depth {
        let plane_slice = &data[k * plane_size..(k + 1) * plane_size];

        let mut transposed_plane = transpose(plane_slice, width, height);

        transposed_plane.par_chunks_mut(height).for_each(fft_slice);

        let retransposed_plane = transpose(&transposed_plane, height, width);

        transposed_xy[k * plane_size..(k + 1) * plane_size].copy_from_slice(&retransposed_plane);
    }

    *data = transposed_xy;

    let transposed_z: Vec<Complex<f64>> = (0..plane_size)
        .into_par_iter()
        .flat_map(|i| {
            let mut z_col: Vec<_> = (0..depth).map(|k| data[k * plane_size + i]).collect();

            fft(&mut z_col);

            z_col
        })
        .collect();

    *data = transposed_z;
}

/// Performs a 3D IFFT.
pub fn ifft3d(
    data: &mut Vec<Complex<f64>>,
    width: usize,
    height: usize,
    depth: usize,
) {
    let plane_size = width * height;

    let transposed_z: Vec<Complex<f64>> = (0..plane_size)
        .into_par_iter()
        .flat_map(|i| {
            let mut z_col: Vec<_> = (0..depth).map(|k| data[k * plane_size + i]).collect();

            ifft(&mut z_col);

            z_col
        })
        .collect();

    *data = transposed_z;

    let mut transposed_xy = vec![Complex::default(); data.len()];

    for k in 0..depth {
        let plane_slice = &data[k * plane_size..(k + 1) * plane_size];

        let mut transposed_plane = transpose(plane_slice, width, height);

        transposed_plane.par_chunks_mut(height).for_each(ifft_slice);

        let retransposed_plane = transpose(&transposed_plane, height, width);

        transposed_xy[k * plane_size..(k + 1) * plane_size].copy_from_slice(&retransposed_plane);
    }

    *data = transposed_xy;

    data.par_chunks_mut(width).for_each(ifft_slice);
}

/// Configuration for 3D advection-diffusion simulation.
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct AdvectionDiffusionConfig3d {
    /// Number of grid points along the x-axis.
    pub width: usize,
    /// Number of grid points along the y-axis.
    pub height: usize,
    /// Number of grid points along the z-axis.
    pub depth: usize,
    /// Grid spacing along the x-axis.
    pub dx: f64,
    /// Grid spacing along the y-axis.
    pub dy: f64,
    /// Grid spacing along the z-axis.
    pub dz: f64,
    /// Advection velocity vector (u, v, w).
    pub c: (f64, f64, f64),
    /// Diffusion coefficient.
    pub d: f64,
    /// Time step size.
    pub dt: f64,
    /// Number of simulation steps.
    pub steps: usize,
}

/// Solves the 3D advection-diffusion equation.
#[must_use]
pub fn solve_advection_diffusion_3d(
    initial_condition: &[f64],
    config: &AdvectionDiffusionConfig3d,
) -> Vec<f64> {
    let kx = create_k_grid(config.width, config.dx);

    let ky = create_k_grid(config.height, config.dy);

    let kz = create_k_grid(config.depth, config.dz);

    let mut u_hat: Vec<Complex<f64>> = initial_condition
        .iter()
        .map(|&v| Complex::new(v, 0.0))
        .collect();

    fft3d(&mut u_hat, config.width, config.height, config.depth);

    let plane_size = config.width * config.height;

    for _ in 0..config.steps {
        u_hat.par_iter_mut().enumerate().for_each(|(idx, val)| {
            let i = idx % config.width;

            let j = (idx / config.width) % config.height;

            let k = idx / plane_size;

            let kxi = kx[i];

            let kyj = ky[j];

            let kzk = kz[k];

            let advection = Complex::new(
                0.0,
                config
                    .c
                    .2
                    .mul_add(-kzk, (-config.c.0).mul_add(kxi, -(config.c.1 * kyj))),
            );

            let diffusion = Complex::new(
                -config.d * kzk.mul_add(kzk, kyj.mul_add(kyj, kxi.powi(2))),
                0.0,
            );

            let rhs = (advection + diffusion) * *val;

            *val += rhs * config.dt;
        });
    }

    ifft3d(&mut u_hat, config.width, config.height, config.depth);

    u_hat.into_iter().map(|v| v.re).collect()
}

/// Example scenario for the 3D spectral solver.
#[must_use]
pub fn simulate_3d_advection_diffusion_scenario() -> Vec<f64> {
    const N: usize = 16;

    const L: f64 = 2.0 * std::f64::consts::PI;

    let d = L / N as f64;

    let config = AdvectionDiffusionConfig3d {
        width: N,
        height: N,
        depth: N,
        dx: d,
        dy: d,
        dz: d,
        c: (1.0, 0.5, 0.2),
        d: 0.01,
        dt: 0.005,
        steps: 200,
    };

    let mut initial_condition = vec![0.0; N * N * N];

    for k in 0..N {
        for j in 0..N {
            for i in 0..N {
                let x = i as f64 * d;

                let y = j as f64 * d;

                let z = k as f64 * d;

                let val = (-(z - L / 2.0).mul_add(
                    z - L / 2.0,
                    (y - L / 2.0).mul_add(y - L / 2.0, (x - L / 2.0).powi(2)),
                ) / 0.5)
                    .exp();

                initial_condition[(k * N + j) * N + i] = val;
            }
        }
    }

    solve_advection_diffusion_3d(&initial_condition, &config)
}