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
// Utility functions for machine learning optimization
//
// This module provides utility functions and helpers for optimization
// tasks in machine learning.
use ;
use ;
use Debug;
use crate;
/// Convert an `f64` value into the generic float type `A`, returning an honest
/// error when `A` cannot represent it.
///
/// Use this at call sites that already return [`Result`]: it replaces the
/// `A::from(x).expect("unwrap failed")` pattern with real error propagation, so
/// a value outside `A`'s range surfaces as an `Err` instead of a panic.
///
/// For the infallible counterpart — constructors, `Default` impls and struct
/// literals, which cannot propagate an error — use [`scalar_or`].
///
/// # Examples
///
/// ```
/// use optirs_core::utils::try_scalar;
///
/// let half: f32 = try_scalar(0.5).expect("0.5 is representable as f32");
/// assert_eq!(half, 0.5f32);
///
/// // Note what the error path does *not* cover: a float-to-float conversion
/// // saturates rather than failing, so an out-of-range `f64` becomes an
/// // infinity in `f32`, not an `Err`. The `Err` arm is a defensive guard for
/// // conversions that genuinely have no image, not an `f32` range check.
/// assert_eq!(
/// try_scalar::<f32, _>(f64::MAX).expect("f64 -> f32 saturates instead of failing"),
/// f32::INFINITY
/// );
/// ```
/// Convert a generic float `A` down into `f64`, returning an honest error when
/// the value has no `f64` representation.
///
/// This is the mirror image of [`try_scalar`]: `try_scalar` widens a concrete
/// literal into the generic parameter type, `try_f64` narrows a generic value
/// back to `f64` for accumulators, metrics and reporting that are natively
/// `f64`. It replaces the `x.to_f64().expect("unwrap failed")` pattern.
///
/// # Examples
///
/// ```
/// use optirs_core::utils::try_f64;
///
/// assert_eq!(try_f64(0.5f32).expect("f32 always fits in f64"), 0.5);
/// assert_eq!(try_f64(f64::INFINITY).expect("infinity is an f64"), f64::INFINITY);
/// ```
/// Error text for a value that the target float type cannot represent.
/// [`try_scalar`] for the call sites whose error type is `String`.
///
/// Several streaming modules return `Result<T, String>` rather than
/// [`OptimError`]; this keeps their conversions honest without forcing a
/// `.map_err(..)` at every site.
///
/// # Examples
///
/// ```
/// use optirs_core::utils::try_scalar_str;
///
/// let half: f32 = try_scalar_str(0.5).expect("0.5 is representable as f32");
/// assert_eq!(half, 0.5f32);
/// // As with [`try_scalar`], `f64 -> f32` saturates rather than failing.
/// assert_eq!(
/// try_scalar_str::<f32, _>(f64::MAX).expect("saturates"),
/// f32::INFINITY
/// );
/// ```
/// Convert an `f64` value into the generic float type `A`, falling back to
/// `fallback` when `A` cannot represent it.
///
/// This is the infallible counterpart to [`try_scalar`], for the call sites
/// that structurally cannot return an error: `Default` impls, constructors and
/// struct literals. For the `f32`/`f64` types this crate targets, conversion of
/// the numeric literals used in those positions always succeeds, so the
/// fallback is defensive rather than a papered-over failure — but pick a
/// fallback that is safe in context (for example `Float::one` for a
/// multiplicative factor or a divisor, so a failed conversion can never
/// introduce a division by zero).
///
/// # Examples
///
/// ```
/// use optirs_core::utils::scalar_or;
///
/// assert_eq!(scalar_or::<f64, _>(0.9, 1.0), 0.9);
/// // The fallback covers conversions with no image at all. A float-to-float
/// // conversion is not one of them: it saturates, so `f64::MAX` reaches `f32`
/// // as an infinity rather than falling back.
/// assert_eq!(scalar_or::<f32, _>(f64::MAX, 1.0), f32::INFINITY);
/// ```
/// Convert a value into the generic float type `A`, or `None` when `A` cannot
/// represent it.
///
/// For call sites that already work in `Option` — typically a configuration
/// lookup whose miss falls through to a default — an unrepresentable value is
/// naturally "absent", so this keeps the existing fallback path instead of
/// inventing an error or a magic number.
///
/// # Examples
///
/// ```
/// use optirs_core::utils::scalar_opt;
///
/// assert_eq!(scalar_opt::<f32, _>(0.25), Some(0.25f32));
/// // Float-to-float conversion saturates rather than returning `None`.
/// assert_eq!(scalar_opt::<f32, _>(f64::MAX), Some(f32::INFINITY));
/// ```
/// Total ordering for floating-point values that never panics.
///
/// `f64::total_cmp`/`f32::total_cmp` are inherent methods and therefore
/// unavailable behind a generic `A: Float` bound, so this reproduces the same
/// contract: a genuine total order in which `NaN` sorts after every real number
/// (and equals itself). Use it instead of
/// `partial_cmp(..).expect("unwrap failed")`, which panics the moment a `NaN`
/// reaches the comparator, in `sort_by`/`min_by`/`max_by`/`select_nth`.
///
/// # Examples
///
/// ```
/// use optirs_core::utils::total_order;
///
/// let mut values = vec![2.0, f64::NAN, 1.0];
/// values.sort_by(total_order);
/// assert_eq!(values[0], 1.0);
/// assert_eq!(values[1], 2.0);
/// assert!(values[2].is_nan(), "NaN sorts last");
/// ```
/// Clip gradient values to a specified range
///
/// # Arguments
///
/// * `gradients` - The gradients to clip
/// * `min_value` - Minimum allowed value
/// * `max_value` - Maximum allowed value
///
/// # Returns
///
/// The clipped gradients (in-place modification)
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::Array1;
/// use optirs_core::utils::clip_gradients;
///
/// let mut gradients = Array1::from_vec(vec![-10.0, 0.5, 8.0, -0.2]);
/// clip_gradients(&mut gradients, -5.0, 5.0);
/// assert_eq!(gradients, Array1::from_vec(vec![-5.0, 0.5, 5.0, -0.2]));
/// ```
/// Clip gradient norm (global gradient clipping)
///
/// # Arguments
///
/// * `gradients` - The gradients to clip
/// * `max_norm` - Maximum allowed L2 norm
///
/// # Returns
///
/// The clipped gradients (in-place modification)
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::Array1;
/// use optirs_core::utils::clip_gradient_norm;
///
/// let mut gradients = Array1::<f64>::from_vec(vec![3.0, 4.0]); // L2 norm = 5.0
/// clip_gradient_norm(&mut gradients, 1.0f64).expect("a finite max-norm is valid");
/// // After clipping, L2 norm = 1.0
/// let diff0 = (gradients[0] - 0.6f64).abs();
/// let diff1 = (gradients[1] - 0.8f64).abs();
/// assert!(diff0 < 1e-5);
/// assert!(diff1 < 1e-5);
/// ```
/// Compute gradient centralization
///
/// Gradient Centralization is a technique that improves training stability
/// by removing the mean from each gradient tensor.
///
/// # Arguments
///
/// * `gradients` - The gradients to centralize
///
/// # Returns
///
/// The centralized gradients (in-place modification)
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::Array1;
/// use optirs_core::utils::gradient_centralization;
///
/// let mut gradients = Array1::from_vec(vec![1.0, 2.0, 3.0, 2.0]);
/// gradient_centralization(&mut gradients);
/// assert_eq!(gradients, Array1::from_vec(vec![-1.0, 0.0, 1.0, 0.0]));
/// ```
/// Zero out small gradient values
///
/// # Arguments
///
/// * `gradients` - The gradients to process
/// * `threshold` - Threshold below which gradients are set to zero
///
/// # Returns
///
/// The processed gradients (in-place modification)
///
/// # Examples
///
/// ```
/// use scirs2_core::ndarray::Array1;
/// use optirs_core::utils::zero_small_gradients;
///
/// let mut gradients = Array1::from_vec(vec![0.001, 0.02, -0.005, 0.3]);
/// zero_small_gradients(&mut gradients, 0.01);
/// assert_eq!(gradients, Array1::from_vec(vec![0.0, 0.02, 0.0, 0.3]));
/// ```