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
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
// SPDX-License-Identifier: GPL-3.0-only
// Copyright (C) 2026 OUTRAM PARK contributors
// Derived from OpenFOAM (www.openfoam.com)
// src/OpenFOAM/fields/Fields/Field/Field.C
// src/OpenFOAM/fields/GeometricFields/GeometricField/GeometricFieldFunctions.C
// Copyright (C) 2004-2023 OpenFOAM Foundation
// Copyright (C) 2016-2023 OpenCFD Ltd.
//
// This file is part of OUTRAM PARK.
//
// OUTRAM PARK is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License as published by the
// Free Software Foundation, either version 3 of the License, or (at your
// option) any later version.
//
// OUTRAM PARK is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with OUTRAM PARK. If not, see <https://www.gnu.org/licenses/>.
//! Backend-dispatched kernels for the element-wise field algebra.
//!
//! # What this module is for
//!
//! A finite-volume solver spends most of a timestep doing *element-wise*
//! arithmetic on fields that carry one value per mesh cell or per mesh face:
//! adding an explicit source to a residual, scaling by a relaxation factor,
//! forming `rho*U`, advancing `phi += dt*ddt(phi)`, and taking a norm to decide
//! whether the outer loop has converged. Each of those touches every cell,
//! several times per timestep, so on a large mesh they are the operations worth
//! spreading across CPU cores.
//!
//! **The arithmetic is identical to the serial operators** in
//! [`crate::fields::field`], [`crate::fields::vol_field`] and
//! [`crate::fields::surface_field`]. Only the execution strategy differs — and,
//! for the *reductions* only, the order in which floating-point values are
//! summed (see "Reduction determinism" below).
//!
//! # One entry point per operation
//!
//! Hybrid execution here means **dispatch, not two APIs**. There is exactly one
//! public function per operation and the backend is a parameter:
//!
//! ```rust
//! use outram_foam_basic_lib::compute::ComputeBackend;
//! use outram_foam_basic_lib::fields::field::Field;
//! use outram_foam_basic_lib::fields::parallel;
//!
//! let a = Field::uniform(1_000, 2.0_f64);
//! let b = Field::uniform(1_000, 3.0_f64);
//!
//! // Same function, different backend — no `add_parallel` twin exists.
//! let c_ref = parallel::add(ComputeBackend::Serial, &a, &b);
//! let c_mt = parallel::add(ComputeBackend::CpuMulti, &a, &b);
//! assert_eq!(c_ref.as_slice(), c_mt.as_slice());
//! ```
//!
//! The size threshold that decides whether [`ComputeBackend::CpuMulti`] actually
//! spreads the work is **one named, documented function** —
//! [`should_parallelise`], reading [`field_parallel_crossover`] — never an
//! `if n > …` scattered through the operators. Retuning the policy is a
//! one-place edit.
//!
//! # Cargo features
//!
//! Multi-threading lives behind the crate's **`parallel`** feature (rayon),
//! which is **off by default** so the default build stays dependency-light and
//! Android-clean. The public API in this module is the *same either way*: with
//! the feature off, [`ComputeBackend::CpuMulti`] and [`ComputeBackend::Gpu`]
//! transparently run the serial path and every result is unchanged. Nothing
//! here is target-gated — rayon is pure Rust, so with `--features parallel` this
//! module builds and runs on Android/Termux (`target_os = "android"`) too;
//! [`std::thread::available_parallelism`] works there and a phone simply
//! reports fewer cores.
//!
//! # The `Gpu` backend
//!
//! There is **no GPU kernel for field algebra yet**. [`ComputeBackend::Gpu`] is
//! accepted and routed to the best available CPU path (multi-threaded when the
//! `parallel` feature is on, serial otherwise). This is stated rather than
//! silently pretended; when a GPU field kernel exists it is wired in here and
//! nothing about the call sites changes.
//!
//! # Which thread pool
//!
//! The kernels use rayon's **global** pool. A caller that wants a dedicated,
//! explicitly sized pool does not need a second API — bind one with
//! `rayon::ThreadPool::install` and every call inside routes to it:
//!
//! ```text
//! // Sketch — requires the `parallel` feature, so it is shown rather than run
//! // as a doctest (rayon is not a dependency of the default build at all).
//! let pool = rayon::ThreadPoolBuilder::new().num_threads(8).build().unwrap();
//! pool.install(|| parallel::axpy_assign(ComputeBackend::CpuMulti, &mut y, dt, &ddt));
//! ```
//!
//! The `vv_reduction_is_independent_of_thread_count` test in this module does
//! exactly this and asserts the answer is unchanged.
//!
//! The reductions are written so that the answer does **not** depend on which
//! pool or how many threads it has — see below.
//!
//! # Units
//!
//! This layer is deliberately **unit-agnostic**, exactly like the serial field
//! layer it mirrors (see the [`crate::fields`] module docs): a [`Field`] carries
//! bare `f64` / [`Vector3`] / [`Tensor`](crate::primitives::Tensor) /
//! [`SymmTensor`](crate::primitives::SymmTensor) values in whatever SI units the
//! caller assigned them. No `uom` quantity is stripped here because none is
//! present at this layer — this crate's `uom` discipline lives in the
//! thermophysics layer and nothing in this module weakens it. Each function's
//! doc states the units it implies. The one place a physical unit is
//! unavoidable is [`vol_integral`], which multiplies by the mesh's cell volumes
//! in `m^3` and therefore returns `[phi]*m^3`.
//!
//! # Field `name` strings never grow here
//!
//! Every operation that returns a [`VolField`] or [`SurfaceField`] copies the
//! **left operand's** `name` verbatim and never composes a new one. This is not
//! a style preference. A solver that reassigns a persistent field from an
//! expression containing itself (`rho = rho + div(phi)`) would double the `name`
//! string every timestep under compositional naming — `2^step` growth, invisible
//! in the field data. That exact bug once drove this crate's
//! `compressible_lid_cavity` test to 24 GB and a SIGTERM. See the crate
//! `CLAUDE.md` "Critical translation gotcha", the matching notes in
//! [`crate::fields::vol_field`], and the `name_does_not_grow_*` regression tests
//! in this module, which reassign a field from an expression containing itself
//! 64 times and assert the name length is unchanged.
//!
//! # Reduction determinism
//!
//! The reductions ([`sum`], [`l2_norm`], [`dot`], [`vol_integral`], …) use a
//! **fixed-chunk tree reduction**: the slice is cut into consecutive chunks of
//! exactly [`REDUCTION_CHUNK`] elements, each chunk is summed sequentially in
//! index order, and the per-chunk partial sums are then combined sequentially in
//! index order on the calling thread.
//!
//! That buys a strong and deliberate guarantee:
//!
//! - the parallel reduction depends **only** on the data and on the
//! compile-time constant [`REDUCTION_CHUNK`];
//! - it is therefore **bit-reproducible run to run** and **identical for any
//! thread count** — unlike a work-stealing `par_iter().sum()`, whose
//! accumulation tree depends on how rayon happened to split the work that
//! run;
//! - it is **not** bit-identical to the serial left-to-right sum, because
//! floating-point addition is not associative. The two differ in the last
//! bits; the measured worst-case deviation is recorded in the V&V test
//! `vv_parallel_sum_matches_serial_within_tolerance`.
//!
//! [`min`] and [`max`] *are* bit-identical to the serial fold, because `min` and
//! `max` are associative.
//!
//! [`ComputeBackend::Serial`](crate::compute::ComputeBackend::Serial) is the **deterministic trusted reference** — the
//! oracle every parallel result in this module is checked against, matching the
//! convention in `outram-mc-libs` (`src/physics/compute.rs`) and `boon-lay`
//! (`src/compute.rs`).
//!
//! # Crossover: parallel is *slower* on small fields
//!
//! Handing a 50-element addition to four threads loses — the dispatch costs more
//! than the arithmetic. [`should_parallelise`] therefore falls back to the
//! serial path below [`field_parallel_crossover`], whose value was **measured on
//! real hardware**, not guessed; see [`FIELD_PARALLEL_CROSSOVER`] for the table.
use ;
use *;
use crateComputeBackend;
use cratePatchField;
use crateField;
use crateSurfaceField;
use crate;
use crateVector3;
// ── Dispatch policy — the single place the threshold lives ───────────────────
/// Number of consecutive elements summed sequentially inside one chunk of a
/// parallel reduction.
///
/// The reductions cut the field into chunks of exactly this many elements, sum
/// each chunk in index order, then combine the partial sums in index order.
/// Fixing this at a compile-time constant — rather than deriving it from the
/// thread count — is what makes the parallel reduction **bit-reproducible and
/// thread-count independent** (see the module-level "Reduction determinism"
/// section).
///
/// Value: `4096` elements, i.e. 32 KiB of `f64`, which sits comfortably inside a
/// typical L1/L2 data cache so a chunk is summed without cache misses. The final
/// chunk is shorter when the length is not a multiple of 4096; that does not
/// affect reproducibility because the split is still a pure function of the
/// length.
pub const REDUCTION_CHUNK: usize = 4096;
/// Element count at or above which [`ComputeBackend::CpuMulti`] actually spreads
/// the work across threads. Below it, every operation runs on the calling
/// thread.
///
/// # Why a crossover exists at all
///
/// Element-wise field arithmetic is memory-bandwidth bound and rayon's dispatch
/// costs on the order of microseconds. Below some size the dispatch dominates
/// and the parallel path is strictly *slower*.
///
/// # Measured basis (not a guess)
///
/// Measured 2026-08-12, `--release --features parallel`, `f64` fields, **4
/// logical cores** reported by [`std::thread::available_parallelism`]; operation
/// `c = a + b` (out-of-place add), best of 9 repeats after two warm-ups, by the
/// `#[ignore]`d `measure_crossover_add` test in this module, run in isolation
/// (`--test-threads=1`). Absolute wall-clock per call, from the least-contended
/// of nine sweeps:
///
/// | n | serial | CpuMulti (4 threads) | speedup |
/// |---|---|---|---|
/// | 1 024 | 0.43 us | 7.59 us | 0.06x |
/// | 4 096 | 1.89 us | 11.07 us | 0.17x |
/// | 16 384 | 5.99 us | 23.11 us | 0.26x |
/// | 65 536 | 56.27 us | 30.39 us | 1.85x |
/// | 131 072 | 117.77 us | 49.87 us | 2.36x |
/// | 262 144 | 239.65 us | 89.52 us | 2.68x |
/// | 1 048 576 | 2001.64 us | 437.34 us | 4.58x |
///
/// # The crossover is a band, not a point — read this before trusting it
///
/// The measurement machine is a shared virtualised sandbox. The **serial** column
/// is highly repeatable (spread under 5% across ten sweeps); the **parallel**
/// column is not, varying by up to 4x run to run because it competes for cores
/// with whatever else the host is doing. Counting how often the parallel path
/// won, over ten independent sweeps:
///
/// | n | sweeps won |
/// |---|---|
/// | 1 024 / 4 096 / 16 384 | 0 of 10 — never |
/// | 65 536 | 4 of 10 |
/// | 131 072 | 6 of 10 |
/// | 262 144 | 9 of 10 |
/// | 1 048 576 | 10 of 10 (1.48x-4.58x) |
///
/// So the honest statement is: **the crossover lies between 65 536 and 262 144
/// elements on this hardware, and the measurement is not precise enough to pin it
/// further.** This constant is set to `131_072`, the smallest size that won a
/// majority of sweeps. The asymmetry justifies erring low: in the sweeps where
/// 131 072 lost, it lost by 3%-27% of ~120 us (tens of microseconds), whereas
/// setting the threshold at 262 144 would forfeit a measured 1.3x-2.4x on
/// mid-sized meshes.
///
/// **Re-measure on the target machine.** More cores or more memory bandwidth move
/// the crossover down; a phone moves it up. Run
/// `cargo test -p outram-foam-basic-lib --lib --release --features parallel --
/// --ignored --nocapture --test-threads=1 measure_crossover_add`.
///
/// # Relationship to [`crate::compute::CPU_MULTI_MIN_WORK_ITEMS`]
///
/// The workspace-level threshold is `4_096` work items and its own documentation
/// states it is **a placeholder awaiting measurement**, adding that "each kernel
/// that measures its own crossover should say so in its docs and may override
/// this". This constant is that override for the field-algebra kernels, and the
/// measurement says the placeholder is far too low for them: at `n = 4 096` the
/// parallel path measured **0.17x** — about six times *slower* than serial — and
/// it did not win a single one of nine sweeps at any size below 65 536. These
/// kernels are memory-bandwidth bound with only one or two flops per element, so
/// they need far more elements to amortise dispatch than a compute-dense kernel
/// would. The measurement here is offered as input to bead `op-yvj.4.7`.
pub const FIELD_PARALLEL_CROSSOVER: usize = 131_072;
/// The element count at or above which multi-threading is worth its overhead for
/// the field-algebra kernels.
///
/// Returns [`FIELD_PARALLEL_CROSSOVER`] — the **measured** field-kernel
/// crossover, deliberately overriding the documented placeholder
/// [`crate::compute::CPU_MULTI_MIN_WORK_ITEMS`] (see that constant's docs for
/// why the override exists and the numbers behind it).
///
/// It is a *function*, not a bare constant, so the policy can later consult a
/// runtime-configured value without touching a single operator.
///
/// **Units:** a count of field elements — cells for a volume field, internal
/// faces for a surface field. Dimensionless.
/// The one place that decides Serial vs multi-threaded execution for an
/// element-wise field operation over `n` elements.
///
/// Every operator in this module routes through this function; none of them
/// contains its own size test. It returns `true` only when **all** of:
///
/// - `backend` is [`ComputeBackend::CpuMulti`] or [`ComputeBackend::Gpu`]
/// (there is no GPU field kernel yet, so `Gpu` asks for the best CPU path);
/// - [`ComputeBackend::resolve`] confirms `CpuMulti` is actually available, i.e.
/// the crate was built with the **`parallel`** feature — availability is asked
/// of [`crate::compute`], never re-implemented here;
/// - `n >= field_parallel_crossover()`.
///
/// `n` is counted in field elements — cells for a volume field, internal faces
/// for a surface field. Dimensionless.
///
/// # Relationship to [`crate::compute::select_backend`]
///
/// `select_backend` answers "which backend should I ask for?" from a work-item
/// count; this function answers "given the backend I was asked for, is this
/// particular field big enough to be worth threading?" using the **measured**
/// field-kernel crossover rather than the workspace placeholder. A caller may use
/// either; passing `select_backend(n)` straight in works and is safe, because
/// this function re-checks the size against the measured threshold.
///
/// ```rust
/// use outram_foam_basic_lib::compute::ComputeBackend;
/// use outram_foam_basic_lib::fields::parallel::{field_parallel_crossover, should_parallelise};
///
/// // Serial never parallelises, whatever the size.
/// assert!(!should_parallelise(ComputeBackend::Serial, 100_000_000));
/// // Nor does any backend on a tiny field.
/// assert!(!should_parallelise(ComputeBackend::CpuMulti, 8));
/// // Above the crossover it depends only on whether `parallel` is enabled.
/// assert_eq!(
/// should_parallelise(ComputeBackend::CpuMulti, field_parallel_crossover()),
/// cfg!(feature = "parallel"),
/// );
/// ```
// ── Private execution helpers ────────────────────────────────────────────────
//
// Each helper has two bodies selected by the `parallel` feature, with IDENTICAL
// signatures and bounds, so the public API is byte-for-byte the same in both
// builds. The `Send + Sync` bounds are kept in the serial build too, precisely
// so enabling the feature can never change a public signature.
/// Fixed-chunk tree sum of `f(x[i])` — see the module "Reduction determinism"
/// section. Deterministic and thread-count independent by construction.
/// Fixed-chunk tree sum of `f(x[i], y[i])`. Same determinism guarantee.
/// Fixed-chunk extremum fold. `min`/`max` are associative, so this is
/// bit-identical to the serial fold.
// ── Element-wise kernels on `Field<T>` ───────────────────────────────────────
/// Element-wise sum `c[i] = a[i] + b[i]`, returning a new field.
///
/// Generic over the element type: works for `Field<f64>`, `Field<Vector3>`,
/// `Field<Tensor>` and `Field<SymmTensor>`, all of which are `Copy`.
///
/// **Units:** both operands must carry the same physical quantity (this layer
/// stores bare numbers and cannot check that); the result carries it too.
///
/// Every output element is computed by the same expression as the serial
/// [`std::ops::Add`] impl on [`Field`], so the result is **bit-identical** to
/// [`ComputeBackend::Serial`](crate::compute::ComputeBackend::Serial) on any backend and any thread count.
///
/// # Panics
///
/// Panics if `a.len() != b.len()`, matching the serial operator.
///
/// ```rust
/// use outram_foam_basic_lib::compute::ComputeBackend;
/// use outram_foam_basic_lib::fields::field::Field;
/// use outram_foam_basic_lib::fields::parallel;
///
/// let a = Field::new(vec![1.0, 2.0, 3.0]);
/// let b = Field::new(vec![10.0, 20.0, 30.0]);
/// let c = parallel::add(ComputeBackend::CpuMulti, &a, &b);
/// assert_eq!(c.as_slice(), &[11.0, 22.0, 33.0]);
/// ```
/// Element-wise difference `c[i] = a[i] - b[i]`, returning a new field.
///
/// **Units:** as for [`add`] — both operands are the same physical quantity.
/// Bit-identical to the serial [`std::ops::Sub`] impl on [`Field`].
///
/// # Panics
///
/// Panics if `a.len() != b.len()`.
/// Uniform scaling `c[i] = a[i] * s`, returning a new field.
///
/// Used for under-relaxation (`s = alpha`, dimensionless), for `1/dt` weighting
/// (`s` in `s^-1`), and for negation (`s = -1.0`).
///
/// **Units:** the result carries `[a] * [s]`; this layer treats `s` as a bare
/// number and cannot check it. Bit-identical to the serial
/// [`std::ops::Mul<f64>`] impl on [`Field`].
/// Fused combination `c[i] = y[i] + a * x[i]` ("axpy"), returning a new field.
///
/// This is the single most common shape in a solver timestep — adding a scaled
/// explicit source, applying an under-relaxed correction, or advancing an
/// explicit Euler update `phi_new = phi + dt * ddt(phi)`. It is one fused pass,
/// so the fields are traversed once instead of twice; that matters because these
/// kernels are memory-bandwidth bound.
///
/// **Units:** `y` and `a*x` must be the same physical quantity.
///
/// # Panics
///
/// Panics if `y.len() != x.len()`.
///
/// ```rust
/// use outram_foam_basic_lib::compute::ComputeBackend;
/// use outram_foam_basic_lib::fields::field::Field;
/// use outram_foam_basic_lib::fields::parallel;
///
/// let y = Field::new(vec![1.0, 1.0]);
/// let x = Field::new(vec![4.0, 6.0]);
/// let c = parallel::axpy(ComputeBackend::Serial, &y, 0.5, &x);
/// assert_eq!(c.as_slice(), &[3.0, 4.0]);
/// ```
/// In-place accumulation `y[i] += x[i]`.
///
/// Allocation-free — the preferred form inside a timestep loop, where the
/// out-of-place [`add`] allocates a fresh `Vec` every call.
///
/// **Units:** `y` and `x` are the same physical quantity.
///
/// # Panics
///
/// Panics if `y.len() != x.len()`.
/// In-place subtraction `y[i] -= x[i]`. Allocation-free.
///
/// **Units:** `y` and `x` are the same physical quantity.
///
/// # Panics
///
/// Panics if `y.len() != x.len()`.
/// In-place uniform scaling `y[i] *= s`. Allocation-free.
///
/// **Units:** the field becomes `[y] * [s]`; `s` is a bare number here.
/// In-place fused combination `y[i] += a * x[i]` ("axpy"). Allocation-free.
///
/// The hot-loop form of [`axpy`]: one traversal, no allocation. This is the
/// shape an explicit transient update takes every timestep.
///
/// **Units:** `y` and `a*x` are the same physical quantity.
///
/// # Panics
///
/// Panics if `y.len() != x.len()`.
///
/// ```rust
/// use outram_foam_basic_lib::compute::ComputeBackend;
/// use outram_foam_basic_lib::fields::field::Field;
/// use outram_foam_basic_lib::fields::parallel;
/// use outram_foam_basic_lib::primitives::Vector3;
///
/// let mut u = Field::uniform(3, Vector3::new(1.0, 0.0, 0.0)); // [m/s]
/// let du = Field::uniform(3, Vector3::new(0.0, 2.0, 0.0)); // [m/s^2]
/// parallel::axpy_assign(ComputeBackend::CpuMulti, &mut u, 0.5, &du); // dt = 0.5 s
/// assert_eq!(u[0], Vector3::new(1.0, 1.0, 0.0));
/// ```
/// Element-wise product of two **scalar** fields, `c[i] = a[i] * b[i]`.
///
/// The workhorse behind `rho*h`, and behind any coefficient-times-field
/// assembly. **Units multiply:** the result carries `[a]*[b]`.
///
/// Bit-identical to [`Field::pointwise_mul`].
///
/// # Panics
///
/// Panics if `a.len() != b.len()`.
/// Element-wise quotient of two **scalar** fields, `c[i] = a[i] / b[i]`.
///
/// **Units divide:** the result carries `[a]/[b]`. Division by zero yields
/// `+/-inf` or `NaN` exactly as `f64` division does — no guard is applied,
/// matching [`Field::pointwise_div`].
///
/// # Panics
///
/// Panics if `a.len() != b.len()`.
/// Scale a vector/tensor field by a per-element scalar field:
/// `c[i] = v[i] * s[i]`.
///
/// This is `rho*U` (density field times velocity field) and every other
/// "coefficient field times ranked field" product. **Units multiply:**
/// `[v]*[s]`.
///
/// Bit-identical to [`Field::scale`] for `Field<Vector3>`.
///
/// # Panics
///
/// Panics if `v.len() != s.len()`.
///
/// ```rust
/// use outram_foam_basic_lib::compute::ComputeBackend;
/// use outram_foam_basic_lib::fields::field::Field;
/// use outram_foam_basic_lib::fields::parallel;
/// use outram_foam_basic_lib::primitives::Vector3;
///
/// let u = Field::uniform(2, Vector3::new(1.0, 2.0, 3.0)); // [m/s]
/// let rho = Field::new(vec![2.0, 0.5]); // [kg/m^3]
/// let rho_u = parallel::scale_by_field(ComputeBackend::CpuMulti, &u, &rho); // [kg/(m^2 s)]
/// assert_eq!(rho_u[0], Vector3::new(2.0, 4.0, 6.0));
/// assert_eq!(rho_u[1], Vector3::new(0.5, 1.0, 1.5));
/// ```
/// Element-wise dot product of two vector fields → scalar field:
/// `c[i] = a[i] . b[i]`.
///
/// **Units multiply:** `[a]*[b]`. Bit-identical to [`Field::dot_field`].
///
/// # Panics
///
/// Panics if `a.len() != b.len()`.
// ── Reductions on `Field<f64>` ───────────────────────────────────────────────
/// Sum of all elements, `sum_i x[i]`.
///
/// **Units:** the field's own units. An empty field sums to `0.0`.
///
/// # Determinism
///
/// Reproducible run to run and independent of thread count, but **not**
/// bit-identical to the serial [`Field::sum`] — the summation order differs. See
/// the module-level "Reduction determinism" section for the measured deviation.
///
/// ```rust
/// use outram_foam_basic_lib::compute::ComputeBackend;
/// use outram_foam_basic_lib::fields::field::Field;
/// use outram_foam_basic_lib::fields::parallel;
///
/// assert_eq!(parallel::sum(ComputeBackend::Serial, &Field::new(vec![1.0, 2.0, 3.0])), 6.0);
/// assert_eq!(parallel::sum(ComputeBackend::CpuMulti, &Field::<f64>::new(vec![])), 0.0);
/// ```
/// Arithmetic mean of all elements; returns `0.0` for an empty field, matching
/// [`Field::mean`].
///
/// **Units:** the field's own units.
/// Smallest element. Returns `+inf` for an empty field, matching [`Field::min`].
///
/// **Units:** the field's own units. **Bit-identical** to the serial fold on
/// every backend, because `min` is associative.
/// Largest element. Returns `-inf` for an empty field, matching [`Field::max`].
///
/// **Units:** the field's own units. **Bit-identical** to the serial fold on
/// every backend, because `max` is associative.
/// Euclidean (L2) norm, `sqrt(sum_i x[i]^2)`.
///
/// This is the convergence measure a solver evaluates on the residual field
/// every outer iteration. **Units:** the field's own units. An empty field gives
/// `0.0`.
///
/// # Determinism
///
/// Same guarantee as [`sum`]: reproducible and thread-count independent, not
/// bit-identical to [`Field::l2_norm`].
/// Inner product of two scalar fields, `sum_i a[i]*b[i]`.
///
/// The Krylov-solver inner product, and — with cell volumes as `b` — the
/// volume-weighted integral. **Units multiply:** `[a]*[b]`.
///
/// # Panics
///
/// Panics if `a.len() != b.len()`.
///
/// # Determinism
///
/// Same guarantee as [`sum`].
// ── `VolField` / `SurfaceField` wrappers ─────────────────────────────────────
//
// Every one of these copies the LEFT operand's `name` verbatim. Never compose a
// name here — see the module docs and the crate `CLAUDE.md`.
/// Apply `op` to each patch pair, keeping the left patch's boundary condition.
/// Apply `op` to each patch, keeping the boundary condition.
/// Sum of two volume fields — internal field **and** every boundary patch.
///
/// The result takes `a`'s `name`, `a`'s mesh, and `a`'s per-patch boundary
/// conditions, exactly like the serial [`std::ops::Add`] impl on [`VolField`].
///
/// **The name is copied, never composed.** See the module docs: composing names
/// here produces `2^step` string growth in a solver loop.
///
/// **Units:** both operands are the same physical quantity.
///
/// # Panics
///
/// Panics if the internal fields or any patch pair differ in length.
///
/// ```rust
/// use std::sync::Arc;
/// use outram_foam_basic_lib::compute::ComputeBackend;
/// use outram_foam_basic_lib::fields::parallel;
/// use outram_foam_basic_lib::fields::vol_field::VolScalarField;
/// use outram_foam_basic_lib::mesh::fv_mesh::FvMesh;
///
/// let mesh = Arc::new(FvMesh::periodic_1d(8, 1.0, 1.0));
/// let a = VolScalarField::uniform("rho", mesh.clone(), 1.0);
/// let b = VolScalarField::uniform("drho", mesh, 0.25);
/// let c = parallel::add_vol(ComputeBackend::CpuMulti, &a, &b);
/// assert_eq!(c.name, "rho"); // NOT "(rho + drho)"
/// assert!((c.internal[0] - 1.25).abs() < 1e-15);
/// ```
/// Difference of two volume fields — internal field and every boundary patch.
///
/// Name, mesh, and boundary conditions come from `a`; the name is copied, never
/// composed. **Units:** both operands are the same physical quantity.
///
/// # Panics
///
/// Panics if the internal fields or any patch pair differ in length.
/// Uniform scaling of a volume field, `c = a * s` — internal field and every
/// boundary patch.
///
/// Name, mesh, and boundary conditions come from `a`. **Units:** `[a]*[s]`.
/// In-place accumulation on a volume field, `y += x` — internal field and every
/// boundary patch.
///
/// Allocation-free and **name-preserving by construction**: `y.name` is never
/// touched. **Units:** `y` and `x` are the same physical quantity.
///
/// # Panics
///
/// Panics if the internal fields or any patch pair differ in length.
/// In-place subtraction on a volume field, `y -= x`. Allocation-free,
/// name-preserving.
///
/// **Units:** `y` and `x` are the same physical quantity.
///
/// # Panics
///
/// Panics if the internal fields or any patch pair differ in length.
/// In-place uniform scaling of a volume field, `y *= s`. Allocation-free,
/// name-preserving. **Units:** the field becomes `[y]*[s]`.
/// In-place fused update on a volume field, `y += a * x` — internal field and
/// every boundary patch.
///
/// This is the explicit-update shape a transient solver runs on every prognostic
/// field every timestep (`rho += dt * ddt(rho)`). Allocation-free and
/// name-preserving — the form that structurally cannot reproduce the
/// `name`-growth bug, because it never constructs a new field.
///
/// **Units:** `y` and `a*x` are the same physical quantity.
///
/// # Panics
///
/// Panics if the internal fields or any patch pair differ in length.
///
/// ```rust
/// use std::sync::Arc;
/// use outram_foam_basic_lib::compute::ComputeBackend;
/// use outram_foam_basic_lib::fields::parallel;
/// use outram_foam_basic_lib::fields::vol_field::VolScalarField;
/// use outram_foam_basic_lib::mesh::fv_mesh::FvMesh;
///
/// let mesh = Arc::new(FvMesh::periodic_1d(16, 1.0, 1.0));
/// let mut rho = VolScalarField::uniform("rho", mesh.clone(), 1.0);
/// let ddt = VolScalarField::uniform("ddt(rho)", mesh, 2.0);
///
/// for _ in 0..10 {
/// parallel::axpy_vol_assign(ComputeBackend::CpuMulti, &mut rho, 0.1, &ddt); // dt = 0.1
/// }
/// assert!((rho.internal[0] - 3.0).abs() < 1e-12);
/// assert_eq!(rho.name, "rho"); // still 3 characters after 10 steps
/// ```
/// Sum of two surface fields — internal faces and every boundary patch.
///
/// Name, mesh, and boundary conditions come from `a`; the name is copied, never
/// composed. **Units:** both operands are the same physical quantity.
///
/// # Panics
///
/// Panics if the internal fields or any patch pair differ in length.
/// Difference of two surface fields — internal faces and every boundary patch.
///
/// Name, mesh, and boundary conditions come from `a`. **Units:** both operands
/// are the same physical quantity.
///
/// # Panics
///
/// Panics if the internal fields or any patch pair differ in length.
/// Uniform scaling of a surface field, `c = a * s` — internal faces and every
/// boundary patch.
///
/// Name, mesh, and boundary conditions come from `a`. **Units:** `[a]*[s]`.
/// In-place fused update on a surface field, `y += a * x` — the flux-field
/// counterpart of [`axpy_vol_assign`] (`phi += dt * ddt(phi)`).
///
/// Allocation-free, name-preserving. **Units:** `y` and `a*x` are the same
/// physical quantity.
///
/// # Panics
///
/// Panics if the internal fields or any patch pair differ in length.
// ── Mesh-weighted reductions on `VolScalarField` ─────────────────────────────
/// Volume integral over the **internal** cells,
/// `integral(phi dV) = sum_i phi[i] * V[i]`.
///
/// `V[i]` is the cell volume in `m^3`, taken from the field's own mesh, so the
/// result carries **units `[phi] * m^3`** — for a density field in `kg/m^3` this
/// is the total mass in `kg`, which is the conservation check a compressible
/// solver runs each timestep.
///
/// Boundary patches are **not** included: they carry face values, not cell
/// values, and have no volume. An empty mesh integrates to `0.0`.
///
/// # Panics
///
/// Panics if the internal field length differs from `mesh.n_cells`.
///
/// # Determinism
///
/// Same guarantee as [`sum`]: reproducible run to run and independent of thread
/// count, not bit-identical to a serial left fold.
///
/// ```rust
/// use std::sync::Arc;
/// use outram_foam_basic_lib::compute::ComputeBackend;
/// use outram_foam_basic_lib::fields::parallel;
/// use outram_foam_basic_lib::fields::vol_field::VolScalarField;
/// use outram_foam_basic_lib::mesh::fv_mesh::FvMesh;
///
/// // 10 cells over a 1 m length, 1 m^2 area => total volume 1 m^3.
/// let mesh = Arc::new(FvMesh::periodic_1d(10, 1.0, 1.0));
/// let rho = VolScalarField::uniform("rho", mesh, 1.2); // [kg/m^3]
/// let mass = parallel::vol_integral(ComputeBackend::CpuMulti, &rho);
/// assert!((mass - 1.2).abs() < 1e-12); // 1.2 kg
/// ```
/// Volume-weighted average over the internal cells,
/// `integral(phi dV) / integral(dV)`.
///
/// **Units:** the field's own units (the `m^3` cancels). Returns `0.0` when the
/// total volume is zero (an empty mesh) rather than `NaN`.
///
/// # Determinism
///
/// Same guarantee as [`sum`].
/// L2 norm of a volume field's **internal** values — the residual measure a
/// solver's outer loop tests for convergence.
///
/// **Units:** the field's own units. Boundary patches are excluded.
///
/// # Determinism
///
/// Same guarantee as [`sum`].
/// Smallest internal value of a volume field (`+inf` on an empty mesh).
///
/// **Units:** the field's own units. Bit-identical to a serial fold.
/// Largest internal value of a volume field (`-inf` on an empty mesh).
///
/// **Units:** the field's own units. Bit-identical to a serial fold.