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
//! Shared-memory parallelism helpers (rayon).
//!
//! pyrucast parallelises its heavy compute loops — per-element assembly,
//! per-Gauss-point behaviour integration, element-wise field maths, VTK export
//! — across CPU cores. This module is the single import point for the rayon
//! parallel-iterator prelude, plus the project-wide grain-size policy.
//!
//! # Where parallelism lives
//!
//! It is deliberately **lifted above** the per-physics kernels: the drivers in
//! [`crate::models::kernel`] and the field/container layers call rayon here, so
//! a physics author writes only sequential point-/cell-local maths and never
//! touches a parallel iterator. See the book chapter *« Parallélisme »*.
//!
//! # Determinism
//!
//! Every parallel region either writes each output slot **exactly once**
//! (indexed / `par_chunks_mut` writes), is an **associative reduction over the
//! same values in the same grouping**, or is a **colour-driven scatter**
//! (the `add_atomic` primitive): cells are partitioned into colours that touch disjoint
//! slots, so each slot accumulates its cells in a fixed order — increasing
//! colour, then cell order within the colour — regardless of
//! `RAYON_NUM_THREADS`. The first two are bit-for-bit identical to a sequential
//! run; the colour-driven scatter is reproducible for any thread count but,
//! summed in colour order rather than cell order, is not bit-for-bit with a
//! naive sequential sum (it backs the global assembly and the nodal scatters —
//! the `Bᵀ` divergence, the internal forces and the distributed flux load). The
//! linear solver is the sole non-deterministic exception — see
//! [`crate::ops::solver`].
//!
//! # Grain size
//!
//! Splitting a tiny workload across threads costs more than it saves. Parallel
//! loops use [`MIN_PARALLEL_LEN`] via `with_min_len` / `with_max_len` so small
//! problems (a handful of cells) run effectively sequentially, with no thread
//! hand-off overhead.
pub use *;
use crateResult;
use ;
/// Minimum number of leaf items (values, cells, …) a rayon job should cover
/// before it is worth splitting further. Tuned so that single small elements
/// (e.g. one SEG2) stay on one thread, while real meshes fan out.
///
/// Apply with `.with_min_len(MIN_PARALLEL_LEN)` on an indexed parallel
/// iterator (`par_iter`, `par_chunks_mut`, …).
///
/// ```
/// # use pyrucast::parallel;
/// // Découper un travail minuscule coûte plus qu'il ne rapporte : en deçà
/// // de ce grain, une boucle parallèle tourne de fait séquentiellement.
/// assert_eq!(parallel::MIN_PARALLEL_LEN, 256);
/// // S'applique par `.with_min_len(MIN_PARALLEL_LEN)` sur un itérateur indexé.
/// ```
pub const MIN_PARALLEL_LEN: usize = 256;
/// Apply `f` to every element of `buf` **in place**, in parallel, honouring the
/// grain-size policy. Each slot is written exactly once ⇒ result is independent
/// of the thread count. The single primitive behind element-wise field maths
/// (`map_all`, the scalar `+ − × ÷` operators, …).
///
/// ```
/// # use pyrucast::parallel;
/// // Chaque case est écrite **exactement une fois** : le résultat ne
/// // dépend pas du nombre de fils. C'est l'unique primitive derrière les
/// // maths de champ élément par élément.
/// let mut v = vec![1.0, 4.0, 9.0];
/// parallel::map_inplace(&mut v, f64::sqrt);
/// assert_eq!(v, vec![1.0, 2.0, 3.0]);
/// ```
/// Apply `f` in place to component `ci` (stride `ncomp`, `ci < ncomp`) of a
/// flat component-major buffer, in parallel. Each touched slot is written once.
///
/// ```
/// # use pyrucast::parallel;
/// // Une seule composante d'un tampon entrelacé : ici la deuxième de trois.
/// let mut v = vec![1.0, 10.0, 100.0, 2.0, 20.0, 200.0];
/// parallel::map_component_inplace(&mut v, 3, 1, |x| x * 2.0);
/// assert_eq!(v, vec![1.0, 20.0, 100.0, 2.0, 40.0, 200.0]);
/// ```
/// Accumulate `v` into the f64 atomic slot `a` (the value held as its bit
/// pattern). The colour-driven scatters — the global assembly
/// ([`crate::ops::matrix`]) and the nodal scatters ([`colored_scatter`], behind
/// the `Bᵀ` divergence and the distributed flux load) — guarantee that within one
/// colour no two parallel cells touch the same slot, so this load-then-store
/// never races; colours run in sequence behind a rayon barrier, so cross-colour
/// accumulation is ordered. `Relaxed` therefore suffices — on x86 the store is a
/// plain `mov`, so a colour-disjoint scatter costs the same as a non-atomic one.
pub
/// Handle onto a colour-scatter's flat f64 accumulator (held as atomics), handed
/// to the per-cell closure of [`colored_scatter`]. Within one colour the cells
/// touch pairwise-disjoint slots, so [`Scatter::add`] never races.
///
/// ```
/// # use pyrucast::parallel;
/// // L'accumulateur d'un scatter colorié, tenu en atomiques. Dans une
/// // couleur, les mailles touchent des cases **disjointes** : `add` ne
/// // court jamais.
/// let couleurs = vec![vec![0, 1]];
/// let mut v = vec![0.0; 2];
/// parallel::colored_scatter(&mut v, &couleurs, 1, || (), |cell, _s, out| {
/// out.add(cell, 1.0);
/// Ok(())
/// })?;
/// assert_eq!(v, vec![1.0, 1.0]);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```
/// Scatter per-cell contributions into a flat accumulator of `n_slots`, in
/// parallel, **colour by colour**. `coloring` partitions the cells so that one
/// colour's cells touch pairwise-disjoint slots; that colour's cells then run
/// concurrently (grain `min_len`) without racing, the colours running in
/// sequence. `init` builds a **per-thread** scratch value reused across a
/// thread's cells (e.g. a local element buffer — pass `|| ()` when none is
/// needed); `cell(c, scratch, out)` computes cell `c`'s contributions and pushes
/// each into `out` via [`Scatter::add`].
///
/// Determinism: each slot accumulates its cells in a fixed order — increasing
/// colour, then cell order within the colour — independent of the thread count,
/// so the result is reproducible for any `RAYON_NUM_THREADS` (see the module
/// *Determinism* note). It is the shared mechanism behind the `Bᵀ` divergence
/// ([`crate::models::kernel::scatter_to_nodes`], behind the `Bᵀ` divergence,
/// the internal forces and the distributed flux load
/// [`crate::ops::node_field::flux`](fn@crate::ops::node_field::flux)). Returns the
/// accumulator as plain `f64`.
///
/// ```
/// # use pyrucast::parallel;
/// // Les mailles sont partagées en couleurs qui touchent des cases
/// // disjointes ; chaque case additionne donc ses mailles dans un ordre
/// // fixe — couleur croissante, puis ordre des mailles — quel que soit
/// // `RAYON_NUM_THREADS`.
/// let couleurs = vec![vec![0, 2], vec![1]];
/// let mut v = vec![0.0; 3];
/// parallel::colored_scatter(&mut v, &couleurs, 1, || 0usize, |cell, tampon, out| {
/// *tampon += 1; // un état par tâche, réutilisé d'une maille à l'autre
/// out.add(cell, (cell + 1) as f64);
/// Ok(())
/// })?;
/// assert_eq!(v, vec![1.0, 2.0, 3.0]);
/// # Ok::<(), pyrucast::PyrucastError>(())
/// ```