Debian Codegraph @

dwsys/NUMselect.h

raw symbols SCIP
1 #ifndef _NUMselect_h_
2 #define _NUMselect_h_
3 /* NUMselect.h
4 *
5 * Copyright (C) 2025 David Weenink
6 *
7 * This code is free software; you can redistribute it and/or modify
8 * it under the terms of the GNU General Public License as published by
9 * the Free Software Foundation; either version 3 of the License, or (at
10 * your option) any later version.
11 *
12 * This code is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this work. If not, see <http://www.gnu.org/licenses/>.
19 */
20
21 #include "melder.h"
22 #include "../external/num/median_of_ninthers.h"
23
24 namespace num {
25 template <class T>
26 T& NUMselect (vector<T> const& v, integer kth_asIfSorted) {
27 adaptiveQuickselect (v.asArgumentToFunctionThatExpectsZeroBasedArray (), kth_asIfSorted - 1, v.size);
28 return v [kth_asIfSorted];
29 }
30
31 template <class T>
32 T& NUMget_kth (vector<T> const& v, integer kth_asIfSorted) {
33 num::NUMselect (v, kth_asIfSorted);
34 return v[kth_asIfSorted];
35 }
36
37 template <class T>
38 T& NUMmin_e (struct vector <T> v) {
39 if (v.size == 0)
40 Melder_throw (U"NUMmin_e: cannot determine the minimum of an empty ExtendedReal vector.");
41 if (v.size == 1)
42 return v [1];
43 T *min = & v[1];
44 for (integer i = 2; i <= v.size; i++)
45 if (v[i] < *min)
46 min = & v[i];
47 return *min;
48 }
49
50 template <class T>
51 T& NUMmax_e (struct vector <T> v) {
52 if (v.size == 0)
53 Melder_throw (U"max_e: cannot determine the maximum of an empty vector.");
54 if (v.size == 1)
55 return v [1];
56 T *max = & v[1];
57 for (integer i = 2; i <= v.size; i++)
58 if (v[i] > *max)
59 max = & v[i];
60 return *max;
61 }
62
63 template <typename T>
64 T NUMquantile_e (vector<T> const& v, double factor) {
65 if (v.size < 1)
66 Melder_throw (U"quantile_e: cannot determine quantile from an emplty vector.");
67 if (v.size == 1)
68 return v [1];
69 const double place = factor * v.size + 0.5;
70 const integer left = Melder_clipped (1_integer, Melder_ifloor (place), v.size - 1);
71 trace (U"left:", left, U" size:", v.size);
72 num::NUMselect (v, left);
73 vector<T> highPart = v.part (left + 1, v.size);
74 const T min = num::NUMmin_e (highPart);
75 const double slope = min - v [left];
76 if (slope == 0.0)
77 return v [left]; // or a [left + 1], which is the same
78 return v [left] + (place - left) * slope;
79 }
80 }
81
82 void timeMedian ();
83
84 #endif /* _NUMselect_h_ */